text
stringlengths 2
1.04M
| meta
dict |
---|---|
using System;
namespace MvcGuestbook.Models
{
public class Category
{
public Guid Id { get; set; }
public string Name { get; set; }
}
} | {
"content_hash": "c7940eae01206ce426f87974e0803f23",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 40,
"avg_line_length": 16.4,
"alnum_prop": 0.5914634146341463,
"repo_name": "amshen/Samples",
"id": "7513d6e74a56ec3b76a32ffe7d8f1039f1010242",
"size": "164",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "2009/MvcGuestbook/MvcGuestbook/Models/Category.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "401990"
},
{
"name": "Batchfile",
"bytes": "908"
},
{
"name": "C#",
"bytes": "5541308"
},
{
"name": "CSS",
"bytes": "326785"
},
{
"name": "F#",
"bytes": "3770"
},
{
"name": "Groff",
"bytes": "6284"
},
{
"name": "HTML",
"bytes": "390102"
},
{
"name": "JavaScript",
"bytes": "283105"
},
{
"name": "Pascal",
"bytes": "85316"
},
{
"name": "PowerShell",
"bytes": "660749"
},
{
"name": "Puppet",
"bytes": "2111"
},
{
"name": "XSLT",
"bytes": "12347"
}
],
"symlink_target": ""
} |
The `whereNull` method filters items where the given key is null.
```js
const collection = collect([{
name: 'Mohamed Salah',
}, {
name: null,
}, {
name: 'Sadio Mané',
}]);
const filtered = collection.whereNull();
filtered.all();
// [
// { name: null },
// ]
```
[View source on GitHub](https://github.com/ecrmnn/collect.js/blob/master/src/methods/whereNull.js) | {
"content_hash": "2dd9fc891316e18ae9ff09566df404c9",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 98,
"avg_line_length": 17.761904761904763,
"alnum_prop": 0.6487935656836461,
"repo_name": "ecrmnn/collect.js",
"id": "02ce7b1c53979c035aa0db79afebeca800ab9979",
"size": "391",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/api/whereNull.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "394608"
}
],
"symlink_target": ""
} |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "taco.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| {
"content_hash": "ad725aea1c0c8e586ca8ec0a01c39ee5",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 68,
"avg_line_length": 25,
"alnum_prop": 0.7066666666666667,
"repo_name": "TheTacoScott/tacozmq2",
"id": "6f814941db3b85b9cbf326a12c5fc0d03114d9eb",
"size": "247",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "taco/manage.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2309"
},
{
"name": "Python",
"bytes": "5309"
}
],
"symlink_target": ""
} |
"""Constants for the MusicCast integration."""
from aiomusiccast.capabilities import EntityType
from homeassistant.components.media_player import MediaClass, RepeatMode
from homeassistant.helpers.entity import EntityCategory
DOMAIN = "yamaha_musiccast"
BRAND = "Yamaha Corporation"
# Attributes
ATTR_PLAYLIST = "playlist"
ATTR_PRESET = "preset"
ATTR_MC_LINK = "mc_link"
ATTR_MAIN_SYNC = "main_sync"
ATTR_MC_LINK_SOURCES = [ATTR_MC_LINK, ATTR_MAIN_SYNC]
CONF_UPNP_DESC = "upnp_description"
CONF_SERIAL = "serial"
DEFAULT_ZONE = "main"
HA_REPEAT_MODE_TO_MC_MAPPING = {
RepeatMode.OFF: "off",
RepeatMode.ONE: "one",
RepeatMode.ALL: "all",
}
NULL_GROUP = "00000000000000000000000000000000"
MC_REPEAT_MODE_TO_HA_MAPPING = {
val: key for key, val in HA_REPEAT_MODE_TO_MC_MAPPING.items()
}
MEDIA_CLASS_MAPPING = {
"track": MediaClass.TRACK,
"directory": MediaClass.DIRECTORY,
"categories": MediaClass.DIRECTORY,
}
ENTITY_CATEGORY_MAPPING = {
EntityType.CONFIG: EntityCategory.CONFIG,
EntityType.REGULAR: None,
EntityType.DIAGNOSTIC: EntityCategory.DIAGNOSTIC,
}
DEVICE_CLASS_MAPPING = {
"DIMMER": "yamaha_musiccast__dimmer",
"zone_SLEEP": "yamaha_musiccast__zone_sleep",
"zone_TONE_CONTROL_mode": "yamaha_musiccast__zone_tone_control_mode",
"zone_SURR_DECODER_TYPE": "yamaha_musiccast__zone_surr_decoder_type",
"zone_EQUALIZER_mode": "yamaha_musiccast__zone_equalizer_mode",
"zone_LINK_AUDIO_QUALITY": "yamaha_musiccast__zone_link_audio_quality",
"zone_LINK_CONTROL": "yamaha_musiccast__zone_link_control",
"zone_LINK_AUDIO_DELAY": "yamaha_musiccast__zone_link_audio_delay",
}
| {
"content_hash": "15f81225584d7d8b6bf77492471db69f",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 75,
"avg_line_length": 29.035087719298247,
"alnum_prop": 0.7220543806646526,
"repo_name": "nkgilley/home-assistant",
"id": "79ee3b8e95db5e616dadd65dffa02abb68d33acf",
"size": "1655",
"binary": false,
"copies": "3",
"ref": "refs/heads/dev",
"path": "homeassistant/components/yamaha_musiccast/const.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2963"
},
{
"name": "PLSQL",
"bytes": "840"
},
{
"name": "Python",
"bytes": "51597279"
},
{
"name": "Shell",
"bytes": "6252"
}
],
"symlink_target": ""
} |
namespace pythonic
{
namespace __dispatch__
{
template <class Any>
auto copy(Any const &any) -> decltype(any.copy())
{
return any.copy();
}
DEFINE_FUNCTOR(pythonic::__dispatch__, copy);
}
}
#endif
| {
"content_hash": "e8d39a4e4be3ea7e880a486b358bfd55",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 53,
"avg_line_length": 14.5,
"alnum_prop": 0.5818965517241379,
"repo_name": "pbrunet/pythran",
"id": "685f7814e760ff89c8d728a7dccb8c8384fbc615",
"size": "393",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pythran/pythonic/__dispatch__/copy.hpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "1376833"
},
{
"name": "Makefile",
"bytes": "1185"
},
{
"name": "Python",
"bytes": "1240227"
},
{
"name": "Shell",
"bytes": "264"
}
],
"symlink_target": ""
} |
package org.elasticsearch.xpack.sql.expression;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.sql.parser.ParsingException;
import org.elasticsearch.xpack.sql.parser.SqlParser;
import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan;
import org.elasticsearch.xpack.sql.plan.logical.OrderBy;
import org.elasticsearch.xpack.sql.tree.Source;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.elasticsearch.common.logging.LoggerMessageFormat.format;
public class QuotingTests extends ESTestCase {
private static UnresolvedAttribute from(String s) {
return new UnresolvedAttribute(Source.EMPTY, s);
}
public void testBasicString() {
String s = "someField";
UnresolvedAttribute ua = from(s);
assertThat(ua.name(), equalTo(s));
assertThat(ua.qualifiedName(), equalTo(s));
assertThat(ua.qualifier(), nullValue());
}
public void testSingleQuoteLiteral() {
String name = "@timestamp";
Expression exp = new SqlParser().createExpression("'" + name + "'");
assertThat(exp, instanceOf(Literal.class));
Literal l = (Literal) exp;
assertThat(l.value(), equalTo(name));
}
public void testMultiSingleQuotedLiteral() {
String first = "bucket";
String second = "head";
Expression exp = new SqlParser().createExpression(format(null, "'{}' '{}'", first, second));
assertThat(exp, instanceOf(Literal.class));
Literal l = (Literal) exp;
assertThat(l.value(), equalTo(first + second));
}
public void testQuotedAttribute() {
String quote = "\"";
String name = "@timestamp";
Expression exp = new SqlParser().createExpression(quote + name + quote);
assertThat(exp, instanceOf(UnresolvedAttribute.class));
UnresolvedAttribute ua = (UnresolvedAttribute) exp;
assertThat(ua.name(), equalTo(name));
assertThat(ua.qualifiedName(), equalTo(name));
assertThat(ua.qualifier(), nullValue());
}
public void testBackQuotedAttribute() {
String quote = "`";
String name = "@timestamp";
ParsingException ex = expectThrows(ParsingException.class, () ->
new SqlParser().createExpression(quote + name + quote));
assertThat(ex.getMessage(), equalTo("line 1:1: backquoted identifiers not supported; please use double quotes instead"));
}
public void testQuotedAttributeAndQualifier() {
String quote = "\"";
String qualifier = "table";
String name = "@timestamp";
Expression exp = new SqlParser().createExpression(quote + qualifier + quote + "." + quote + name + quote);
assertThat(exp, instanceOf(UnresolvedAttribute.class));
UnresolvedAttribute ua = (UnresolvedAttribute) exp;
assertThat(ua.name(), equalTo(qualifier + "." + name));
assertThat(ua.qualifiedName(), equalTo(qualifier + "." + name));
assertThat(ua.qualifier(), is(nullValue()));
}
public void testBackQuotedAttributeAndQualifier() {
String quote = "`";
String qualifier = "table";
String name = "@timestamp";
ParsingException ex = expectThrows(ParsingException.class, () ->
new SqlParser().createExpression(quote + qualifier + quote + "." + quote + name + quote));
assertThat(ex.getMessage(), equalTo("line 1:1: backquoted identifiers not supported; please use double quotes instead"));
}
public void testGreedyQuoting() {
LogicalPlan plan = new SqlParser().createStatement("SELECT * FROM \"table\" ORDER BY \"field\"");
final List<LogicalPlan> plans = new ArrayList<>();
plan.forEachDown(plans::add);
assertThat(plans, hasSize(4));
assertThat(plans.get(1), instanceOf(OrderBy.class));
}
}
| {
"content_hash": "144ac6cd4203a1f9fd03408457cdcb38",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 129,
"avg_line_length": 40.37623762376238,
"alnum_prop": 0.6679744973025993,
"repo_name": "coding0011/elasticsearch",
"id": "a7cae7df4312b7d207a00084ea0f975d9720e4c4",
"size": "4319",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/QuotingTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "11081"
},
{
"name": "Batchfile",
"bytes": "18064"
},
{
"name": "Emacs Lisp",
"bytes": "3341"
},
{
"name": "FreeMarker",
"bytes": "45"
},
{
"name": "Groovy",
"bytes": "312193"
},
{
"name": "HTML",
"bytes": "5519"
},
{
"name": "Java",
"bytes": "41505710"
},
{
"name": "Perl",
"bytes": "7271"
},
{
"name": "Python",
"bytes": "55163"
},
{
"name": "Shell",
"bytes": "119286"
}
],
"symlink_target": ""
} |
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| {
"content_hash": "b5fa3387c675992b4ed43501382783b5",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 60,
"avg_line_length": 23.2,
"alnum_prop": 0.7931034482758621,
"repo_name": "hectoregm/ios_apprentice",
"id": "d1ae75b4ffd1a20bd0b3efb5fa4b97e696acc5c7",
"size": "315",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Archive/MyLocations/MyLocations/AppDelegate.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "4313"
},
{
"name": "Objective-C",
"bytes": "582051"
},
{
"name": "Ruby",
"bytes": "118"
},
{
"name": "Shell",
"bytes": "3552"
},
{
"name": "Swift",
"bytes": "102367"
}
],
"symlink_target": ""
} |
class Map < ActiveRecord::Base
mount_uploader :image, MapLoaderUploader
after_destroy :ensure_a_map_remains
validates :image, allow_blank: true, format: {
with: %r{\.(gif|jpeg|jpg|png)}i,
message: 'must be a URL for GIF, JPG or PNG image.'
}
private
def ensure_a_map_remains
if Map.count.zero?
raise "Du kan inte ta bort den sista kartan"
end
end
end
| {
"content_hash": "4b42571147b0dbe4fcd9974060b51e28",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 58,
"avg_line_length": 20.1,
"alnum_prop": 0.6492537313432836,
"repo_name": "Ice-A-Slice/Framtidsmassan2014",
"id": "6290c4c1e4d1ae8f1c874d08295357671bb5383f",
"size": "402",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/map.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "255874"
},
{
"name": "CoffeeScript",
"bytes": "5133"
},
{
"name": "HTML",
"bytes": "67645"
},
{
"name": "JavaScript",
"bytes": "81767"
},
{
"name": "Ruby",
"bytes": "88255"
}
],
"symlink_target": ""
} |
blog
| {
"content_hash": "1c0dbb1d709dec93919bcd640c159392",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 4,
"avg_line_length": 5,
"alnum_prop": 0.8,
"repo_name": "nhpatt/nhpatt.github.io",
"id": "24b32e44c176e59040d65b866d505a8e80a4980f",
"size": "25",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "27726"
},
{
"name": "HTML",
"bytes": "13192"
},
{
"name": "JavaScript",
"bytes": "473"
},
{
"name": "Ruby",
"bytes": "6846"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "81972d8146e3114376a83923a523ce62",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "dea5aab00a9d45bb94c63eb721f02c0b324196b3",
"size": "193",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Iridaceae/Klattia/Klattia flava/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import java.util.concurrent.Executor;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;
/**
* A support class for {@code ListenableFuture} implementations to manage their listeners. An
* instance contains a list of listeners, each with an associated {@code Executor}, and guarantees
* that every {@code Runnable} that is {@linkplain #add added} will be executed after {@link
* #execute()} is called. Any {@code Runnable} added after the call to {@code execute} is still
* guaranteed to execute. There is no guarantee, however, that listeners will be executed in the
* order that they are added.
*
* <p>Exceptions thrown by a listener will be propagated up to the executor. Any exception thrown
* during {@code Executor.execute} (e.g., a {@code RejectedExecutionException} or an exception
* thrown by {@linkplain MoreExecutors#directExecutor direct execution}) will be caught and logged.
*
* @author Nishant Thakkar
* @author Sven Mawson
* @since 1.0
*/
@GwtIncompatible
public final class ExecutionList {
/** Logger to log exceptions caught when running runnables. */
private static final Logger log = Logger.getLogger(ExecutionList.class.getName());
/**
* The runnable, executor pairs to execute. This acts as a stack threaded through the {@link
* RunnableExecutorPair#next} field.
*/
@GuardedBy("this")
@NullableDecl
private RunnableExecutorPair runnables;
@GuardedBy("this")
private boolean executed;
/** Creates a new, empty {@link ExecutionList}. */
public ExecutionList() {}
/**
* Adds the {@code Runnable} and accompanying {@code Executor} to the list of listeners to
* execute. If execution has already begun, the listener is executed immediately.
*
* <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
* the discussion in the {@link ListenableFuture#addListener ListenableFuture.addListener}
* documentation.
*/
public void add(Runnable runnable, Executor executor) {
// Fail fast on a null. We throw NPE here because the contract of Executor states that it throws
// NPE on null listener, so we propagate that contract up into the add method as well.
checkNotNull(runnable, "Runnable was null.");
checkNotNull(executor, "Executor was null.");
// Lock while we check state. We must maintain the lock while adding the new pair so that
// another thread can't run the list out from under us. We only add to the list if we have not
// yet started execution.
synchronized (this) {
if (!executed) {
runnables = new RunnableExecutorPair(runnable, executor, runnables);
return;
}
}
// Execute the runnable immediately. Because of scheduling this may end up getting called before
// some of the previously added runnables, but we're OK with that. If we want to change the
// contract to guarantee ordering among runnables we'd have to modify the logic here to allow
// it.
executeListener(runnable, executor);
}
/**
* Runs this execution list, executing all existing pairs in the order they were added. However,
* note that listeners added after this point may be executed before those previously added, and
* note that the execution order of all listeners is ultimately chosen by the implementations of
* the supplied executors.
*
* <p>This method is idempotent. Calling it several times in parallel is semantically equivalent
* to calling it exactly once.
*
* @since 10.0 (present in 1.0 as {@code run})
*/
public void execute() {
// Lock while we update our state so the add method above will finish adding any listeners
// before we start to run them.
RunnableExecutorPair list;
synchronized (this) {
if (executed) {
return;
}
executed = true;
list = runnables;
runnables = null; // allow GC to free listeners even if this stays around for a while.
}
// If we succeeded then list holds all the runnables we to execute. The pairs in the stack are
// in the opposite order from how they were added so we need to reverse the list to fulfill our
// contract.
// This is somewhat annoying, but turns out to be very fast in practice. Alternatively, we could
// drop the contract on the method that enforces this queue like behavior since depending on it
// is likely to be a bug anyway.
// N.B. All writes to the list and the next pointers must have happened before the above
// synchronized block, so we can iterate the list without the lock held here.
RunnableExecutorPair reversedList = null;
while (list != null) {
RunnableExecutorPair tmp = list;
list = list.next;
tmp.next = reversedList;
reversedList = tmp;
}
while (reversedList != null) {
executeListener(reversedList.runnable, reversedList.executor);
reversedList = reversedList.next;
}
}
/**
* Submits the given runnable to the given {@link Executor} catching and logging all {@linkplain
* RuntimeException runtime exceptions} thrown by the executor.
*/
private static void executeListener(Runnable runnable, Executor executor) {
try {
executor.execute(runnable);
} catch (RuntimeException e) {
// Log it and keep going -- bad runnable and/or executor. Don't punish the other runnables if
// we're given a bad one. We only catch RuntimeException because we want Errors to propagate
// up.
log.log(
Level.SEVERE,
"RuntimeException while executing runnable " + runnable + " with executor " + executor,
e);
}
}
private static final class RunnableExecutorPair {
final Runnable runnable;
final Executor executor;
@NullableDecl RunnableExecutorPair next;
RunnableExecutorPair(Runnable runnable, Executor executor, RunnableExecutorPair next) {
this.runnable = runnable;
this.executor = executor;
this.next = next;
}
}
}
| {
"content_hash": "a9d95e52ec0547c62acb1b54da0e356a",
"timestamp": "",
"source": "github",
"line_count": 153,
"max_line_length": 100,
"avg_line_length": 41.23529411764706,
"alnum_prop": 0.7124742431447139,
"repo_name": "typetools/guava",
"id": "153f425137949496bd315c49190957a6eeabdf73",
"size": "6903",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "android/guava/src/com/google/common/util/concurrent/ExecutionList.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "11478"
},
{
"name": "Java",
"bytes": "26145170"
},
{
"name": "Shell",
"bytes": "4096"
}
],
"symlink_target": ""
} |
===============================
Building From Source on Mac OSX
===============================
.. note::
This document has not been maintained and is retained for reference only.
For building on macOS, please see :ref:`quickstart-mac`.
These instructions describe how to build NumPy and SciPy libraries from
source.
If you just want to use NumPy or SciPy, install pre-built binaries as described
in :ref:`installing-upgrading`.
Python
------
Apple ships its own version of Python with OS X. However, we
*strongly* recommend installing the `official Python distribution
<https://www.python.org/downloads/>`__.
Alternatively, use Python from one of the OS X package managers
(Homebrew, MacPorts, Fink).
Compilers (C/C++/FORTRAN/Cython)
--------------------------------
Though virtually any commercial C/C++ compiler may be used with SciPy, OS X
comes with GNU C compilers pre-installed. The only thing missing is the GNU
FORTRAN compiler.
We recommend gfortran; this is a free, open source, F95 compiler. We suggest you
use the following binaries:
* gfortran installed via `Homebrew <https://brew.sh/>`__, or,
* http://r.research.att.com/tools/gcc-42-5666.3-darwin11.pkg (for Xcode
4.2 or higher)
See `this site <http://r.research.att.com/tools/>`__ for the most recent links.
Unless you are building from released source packages, the `Cython
<https://cython.org/>`__ compiler is also needed.
BLAS/LAPACK Installation
------------------------
You will also need to install a library providing the BLAS and LAPACK
interfaces. ATLAS, OpenBLAS, and MKL all work. OpenBLAS can be installed
via `Homebrew <https://brew.sh/>`.
As of SciPy version 1.2.0, we do not support compiling against the system
Accelerate library for BLAS and LAPACK. It does not support a sufficiently
recent LAPACK interface.
Version-specific notes
----------------------
This section notes only things specific to one version of OS X or Python.
The build instructions in :ref:`Obtaining and Building NumPy and SciPy
<osx-obtaining-and-building>` apply to all versions.
.. _osx-obtaining-and-building:
Obtaining and Building NumPy and SciPy
--------------------------------------
You may install NumPy and SciPy either by checking out the source
files or downloading a source archive file from
`GitHub <https://github.com/scipy/scipy>`__. If you choose the latter,
simply expand the archive (generally a gzipped tar file), otherwise
check out the following branches from the repository:
::
$ git clone https://github.com/numpy/numpy.git
$ git clone https://github.com/scipy/scipy.git
Both NumPy and SciPy are built as follows:
::
$ python setup.py build
$ python setup.py install
The above applies to the `official Python distribution
<https://www.python.org/downloads/>`__, which is 32-bit
only for 2.6 while 32/64-bit bundles are available for 2.7 and
3.x. For alternative 64-bit Pythons (either from Apple or home-built)
on Snow Leopard, you may need to extend your build flags to specify
the architecture by setting LDFLAGS and FFLAGS.
Note that with distutils (setup.py) given build flags like LDFLAGS
**do not extend but override the defaults**, so you have to specify
all necessary flags. Only try this if you know what you're doing!
After a successful build, you may try running the built-in unit tests
for SciPy:
::
$ python
>>> import numpy as np
>>> np.test('full')
>>> import scipy
>>> scipy.test()
Be sure not to import numpy or scipy while you're in the numpy/scipy
source tree. Change directory first.
If you have any problems installing SciPy on your Mac
based on these instructions, please check the `scipy-users and
scipy-dev mailing list archives
<https://www.scipy.org/scipylib/mailing-lists.html>`__
for possible solutions. If you
are still stuck, feel free to join scipy-users for further
assistance. Please have the following information ready:
* Your OS version
* The versions of gcc and gfortran and where you obtained gfortran
* ``$ gcc --version``
* ``$ gfortran --version``
* The versions of numpy and scipy that you are trying to install
* The full output of ``$ python setup.py build``
| {
"content_hash": "18cf16186082d28e6f782cc763bf3bf8",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 80,
"avg_line_length": 32.55038759689923,
"alnum_prop": 0.7151702786377709,
"repo_name": "jor-/scipy",
"id": "3a01f88a90a2ea18bbbbb504dea15156892ac359",
"size": "4199",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "doc/source/building/macosx.rst",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "4395724"
},
{
"name": "C++",
"bytes": "649714"
},
{
"name": "Dockerfile",
"bytes": "1236"
},
{
"name": "Fortran",
"bytes": "5367732"
},
{
"name": "MATLAB",
"bytes": "4346"
},
{
"name": "Makefile",
"bytes": "778"
},
{
"name": "Python",
"bytes": "12479679"
},
{
"name": "Shell",
"bytes": "538"
},
{
"name": "TeX",
"bytes": "52106"
}
],
"symlink_target": ""
} |
#include "fmacros.h"
#include <stdlib.h>
#include <string.h>
#ifndef HIREDIS_WIN
#include <strings.h>
#endif
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include "async.h"
#include "net.h"
#include "dict.c"
#include "sds.h"
#define _EL_ADD_READ(ctx) do { \
if ((ctx)->ev.addRead) (ctx)->ev.addRead((ctx)->ev.data); \
} while(0)
#define _EL_DEL_READ(ctx) do { \
if ((ctx)->ev.delRead) (ctx)->ev.delRead((ctx)->ev.data); \
} while(0)
#define _EL_ADD_WRITE(ctx) do { \
if ((ctx)->ev.addWrite) (ctx)->ev.addWrite((ctx)->ev.data); \
} while(0)
#define _EL_DEL_WRITE(ctx) do { \
if ((ctx)->ev.delWrite) (ctx)->ev.delWrite((ctx)->ev.data); \
} while(0)
#define _EL_CLEANUP(ctx) do { \
if ((ctx)->ev.cleanup) (ctx)->ev.cleanup((ctx)->ev.data); \
} while(0);
/* Forward declaration of function in hiredis.c */
void __redisAppendCommand(redisContext *c, char *cmd, size_t len);
/* Functions managing dictionary of callbacks for pub/sub. */
static unsigned int callbackHash(const void *key) {
return dictGenHashFunction((unsigned char*)key,sdslen((char*)key));
}
static void *callbackValDup(void *privdata, const void *src) {
#ifndef HIREDIS_WIN
((void) privdata);
#endif
redisCallback *dup = malloc(sizeof(*dup));
memcpy(dup,src,sizeof(*dup));
return dup;
}
static int callbackKeyCompare(void *privdata, const void *key1, const void *key2) {
int l1, l2;
((void) privdata);
l1 = sdslen((sds)key1);
l2 = sdslen((sds)key2);
if (l1 != l2) return 0;
return memcmp(key1,key2,l1) == 0;
}
static void callbackKeyDestructor(void *privdata, void *key) {
((void) privdata);
sdsfree((sds)key);
}
static void callbackValDestructor(void *privdata, void *val) {
((void) privdata);
free(val);
}
static dictType callbackDict = {
callbackHash,
NULL,
callbackValDup,
callbackKeyCompare,
callbackKeyDestructor,
callbackValDestructor
};
static redisAsyncContext *redisAsyncInitialize(redisContext *c) {
redisAsyncContext *ac = realloc(c,sizeof(redisAsyncContext));
c = &(ac->c);
/* The regular connect functions will always set the flag REDIS_CONNECTED.
* For the async API, we want to wait until the first write event is
* received up before setting this flag, so reset it here. */
c->flags &= ~REDIS_CONNECTED;
ac->err = 0;
ac->errstr = NULL;
ac->data = NULL;
ac->ev.data = NULL;
ac->ev.addRead = NULL;
ac->ev.delRead = NULL;
ac->ev.addWrite = NULL;
ac->ev.delWrite = NULL;
ac->ev.cleanup = NULL;
ac->onConnect = NULL;
ac->onDisconnect = NULL;
ac->replies.head = NULL;
ac->replies.tail = NULL;
ac->sub.invalid.head = NULL;
ac->sub.invalid.tail = NULL;
ac->sub.channels = dictCreate(&callbackDict,NULL);
ac->sub.patterns = dictCreate(&callbackDict,NULL);
return ac;
}
/* We want the error field to be accessible directly instead of requiring
* an indirection to the redisContext struct. */
static void __redisAsyncCopyError(redisAsyncContext *ac) {
redisContext *c = &(ac->c);
ac->err = c->err;
ac->errstr = c->errstr;
}
redisAsyncContext *redisAsyncConnect(const char *ip, int port) {
redisContext *c = redisConnectNonBlock(ip,port);
redisAsyncContext *ac = redisAsyncInitialize(c);
__redisAsyncCopyError(ac);
return ac;
}
#ifndef HIREDIS_WIN
redisAsyncContext *redisAsyncConnectUnix(const char *path) {
redisContext *c = redisConnectUnixNonBlock(path);
redisAsyncContext *ac = redisAsyncInitialize(c);
__redisAsyncCopyError(ac);
return ac;
}
#endif
int redisAsyncSetConnectCallback(redisAsyncContext *ac, redisConnectCallback *fn) {
if (ac->onConnect == NULL) {
ac->onConnect = fn;
/* The common way to detect an established connection is to wait for
* the first write event to be fired. This assumes the related event
* library functions are already set. */
_EL_ADD_WRITE(ac);
return REDIS_OK;
}
return REDIS_ERR;
}
int redisAsyncSetDisconnectCallback(redisAsyncContext *ac, redisDisconnectCallback *fn) {
if (ac->onDisconnect == NULL) {
ac->onDisconnect = fn;
return REDIS_OK;
}
return REDIS_ERR;
}
/* Helper functions to push/shift callbacks */
static int __redisPushCallback(redisCallbackList *list, redisCallback *source) {
redisCallback *cb;
/* Copy callback from stack to heap */
cb = malloc(sizeof(*cb));
if (source != NULL) {
memcpy(cb,source,sizeof(*cb));
cb->next = NULL;
}
/* Store callback in list */
if (list->head == NULL)
list->head = cb;
if (list->tail != NULL)
list->tail->next = cb;
list->tail = cb;
return REDIS_OK;
}
static int __redisShiftCallback(redisCallbackList *list, redisCallback *target) {
redisCallback *cb = list->head;
if (cb != NULL) {
list->head = cb->next;
if (cb == list->tail)
list->tail = NULL;
/* Copy callback from heap to stack */
if (target != NULL)
memcpy(target,cb,sizeof(*cb));
free(cb);
return REDIS_OK;
}
return REDIS_ERR;
}
static void __redisRunCallback(redisAsyncContext *ac, redisCallback *cb, redisReply *reply) {
redisContext *c = &(ac->c);
if (cb->fn != NULL) {
c->flags |= REDIS_IN_CALLBACK;
cb->fn(ac,reply,cb->privdata);
c->flags &= ~REDIS_IN_CALLBACK;
}
}
/* Helper function to free the context. */
static void __redisAsyncFree(redisAsyncContext *ac) {
redisContext *c = &(ac->c);
redisCallback cb;
dictIterator *it;
dictEntry *de;
/* Execute pending callbacks with NULL reply. */
while (__redisShiftCallback(&ac->replies,&cb) == REDIS_OK)
__redisRunCallback(ac,&cb,NULL);
/* Execute callbacks for invalid commands */
while (__redisShiftCallback(&ac->sub.invalid,&cb) == REDIS_OK)
__redisRunCallback(ac,&cb,NULL);
/* Run subscription callbacks callbacks with NULL reply */
it = dictGetIterator(ac->sub.channels);
while ((de = dictNext(it)) != NULL)
__redisRunCallback(ac,dictGetEntryVal(de),NULL);
dictReleaseIterator(it);
dictRelease(ac->sub.channels);
it = dictGetIterator(ac->sub.patterns);
while ((de = dictNext(it)) != NULL)
__redisRunCallback(ac,dictGetEntryVal(de),NULL);
dictReleaseIterator(it);
dictRelease(ac->sub.patterns);
/* Signal event lib to clean up */
_EL_CLEANUP(ac);
/* Execute disconnect callback. When redisAsyncFree() initiated destroying
* this context, the status will always be REDIS_OK. */
if (ac->onDisconnect && (c->flags & REDIS_CONNECTED)) {
if (c->flags & REDIS_FREEING) {
ac->onDisconnect(ac,REDIS_OK);
} else {
ac->onDisconnect(ac,(ac->err == 0) ? REDIS_OK : REDIS_ERR);
}
}
/* Cleanup self */
redisFree(c);
}
/* Free the async context. When this function is called from a callback,
* control needs to be returned to redisProcessCallbacks() before actual
* free'ing. To do so, a flag is set on the context which is picked up by
* redisProcessCallbacks(). Otherwise, the context is immediately free'd. */
void redisAsyncFree(redisAsyncContext *ac) {
redisContext *c = &(ac->c);
c->flags |= REDIS_FREEING;
if (!(c->flags & REDIS_IN_CALLBACK))
__redisAsyncFree(ac);
}
/* Helper function to make the disconnect happen and clean up. */
static void __redisAsyncDisconnect(redisAsyncContext *ac) {
redisContext *c = &(ac->c);
/* Make sure error is accessible if there is any */
__redisAsyncCopyError(ac);
if (ac->err == 0) {
/* For clean disconnects, there should be no pending callbacks. */
assert(__redisShiftCallback(&ac->replies,NULL) == REDIS_ERR);
} else {
/* Disconnection is caused by an error, make sure that pending
* callbacks cannot call new commands. */
c->flags |= REDIS_DISCONNECTING;
}
/* For non-clean disconnects, __redisAsyncFree() will execute pending
* callbacks with a NULL-reply. */
__redisAsyncFree(ac);
}
/* Tries to do a clean disconnect from Redis, meaning it stops new commands
* from being issued, but tries to flush the output buffer and execute
* callbacks for all remaining replies. When this function is called from a
* callback, there might be more replies and we can safely defer disconnecting
* to redisProcessCallbacks(). Otherwise, we can only disconnect immediately
* when there are no pending callbacks. */
void redisAsyncDisconnect(redisAsyncContext *ac) {
redisContext *c = &(ac->c);
c->flags |= REDIS_DISCONNECTING;
if (!(c->flags & REDIS_IN_CALLBACK) && ac->replies.head == NULL)
__redisAsyncDisconnect(ac);
}
static int __redisGetSubscribeCallback(redisAsyncContext *ac, redisReply *reply, redisCallback *dstcb) {
redisContext *c = &(ac->c);
dict *callbacks;
dictEntry *de;
int pvariant;
char *stype;
sds sname;
/* Custom reply functions are not supported for pub/sub. This will fail
* very hard when they are used... */
if (reply->type == REDIS_REPLY_ARRAY) {
assert(reply->elements >= 2);
assert(reply->element[0]->type == REDIS_REPLY_STRING);
stype = reply->element[0]->str;
pvariant = (tolower(stype[0]) == 'p') ? 1 : 0;
if (pvariant)
callbacks = ac->sub.patterns;
else
callbacks = ac->sub.channels;
/* Locate the right callback */
assert(reply->element[1]->type == REDIS_REPLY_STRING);
sname = sdsnewlen(reply->element[1]->str,reply->element[1]->len);
de = dictFind(callbacks,sname);
if (de != NULL) {
memcpy(dstcb,dictGetEntryVal(de),sizeof(*dstcb));
/* If this is an unsubscribe message, remove it. */
#ifndef HIREDIS_WIN
if (strcasecmp(stype+pvariant,"unsubscribe") == 0) {
#else
if (stricmp(stype+pvariant,"unsubscribe") == 0) {
#endif
dictDelete(callbacks,sname);
/* If this was the last unsubscribe message, revert to
* non-subscribe mode. */
assert(reply->element[2]->type == REDIS_REPLY_INTEGER);
if (reply->element[2]->integer == 0)
c->flags &= ~REDIS_SUBSCRIBED;
}
}
sdsfree(sname);
} else {
/* Shift callback for invalid commands. */
__redisShiftCallback(&ac->sub.invalid,dstcb);
}
return REDIS_OK;
}
void redisProcessCallbacks(redisAsyncContext *ac) {
redisContext *c = &(ac->c);
redisCallback cb;
void *reply = NULL;
int status;
while((status = redisGetReply(c,&reply)) == REDIS_OK) {
if (reply == NULL) {
/* When the connection is being disconnected and there are
* no more replies, this is the cue to really disconnect. */
if (c->flags & REDIS_DISCONNECTING && sdslen(c->obuf) == 0) {
__redisAsyncDisconnect(ac);
return;
}
/* If monitor mode, repush callback */
if(c->flags & REDIS_MONITORING) {
__redisPushCallback(&ac->replies,&cb);
}
/* When the connection is not being disconnected, simply stop
* trying to get replies and wait for the next loop tick. */
break;
}
/* Even if the context is subscribed, pending regular callbacks will
* get a reply before pub/sub messages arrive. */
if (__redisShiftCallback(&ac->replies,&cb) != REDIS_OK) {
/*
* A spontaneous reply in a not-subscribed context can be the error
* reply that is sent when a new connection exceeds the maximum
* number of allowed connections on the server side.
*
* This is seen as an error instead of a regular reply because the
* server closes the connection after sending it.
*
* To prevent the error from being overwritten by an EOF error the
* connection is closed here. See issue #43.
*
* Another possibility is that the server is loading its dataset.
* In this case we also want to close the connection, and have the
* user wait until the server is ready to take our request.
*/
if (((redisReply*)reply)->type == REDIS_REPLY_ERROR) {
c->err = REDIS_ERR_OTHER;
#ifndef HIREDIS_WIN
snprintf(c->errstr,sizeof(c->errstr),"%s",((redisReply*)reply)->str);
#else
sprintf_s(c->errstr,sizeof(c->errstr),"%s",((redisReply*)reply)->str);
#endif
__redisAsyncDisconnect(ac);
return;
}
/* No more regular callbacks and no errors, the context *must* be subscribed or monitoring. */
assert((c->flags & REDIS_SUBSCRIBED || c->flags & REDIS_MONITORING));
if(c->flags & REDIS_SUBSCRIBED)
__redisGetSubscribeCallback(ac,reply,&cb);
}
if (cb.fn != NULL) {
__redisRunCallback(ac,&cb,reply);
c->reader->fn->freeObject(reply);
/* Proceed with free'ing when redisAsyncFree() was called. */
if (c->flags & REDIS_FREEING) {
__redisAsyncFree(ac);
return;
}
} else {
/* No callback for this reply. This can either be a NULL callback,
* or there were no callbacks to begin with. Either way, don't
* abort with an error, but simply ignore it because the client
* doesn't know what the server will spit out over the wire. */
c->reader->fn->freeObject(reply);
}
}
/* Disconnect when there was an error reading the reply */
if (status != REDIS_OK)
__redisAsyncDisconnect(ac);
}
/* Internal helper function to detect socket status the first time a read or
* write event fires. When connecting was not succesful, the connect callback
* is called with a REDIS_ERR status and the context is free'd. */
static int __redisAsyncHandleConnect(redisAsyncContext *ac) {
redisContext *c = &(ac->c);
if (redisCheckSocketError(c,c->fd) == REDIS_ERR) {
/* Try again later when connect(2) is still in progress. */
#ifndef HIREDIS_WIN
if (errno == EINPROGRESS)
#else
if (errno == WSAEINPROGRESS || errno == WSAEWOULDBLOCK )
#endif
return REDIS_OK;
if (ac->onConnect) ac->onConnect(ac,REDIS_ERR);
__redisAsyncDisconnect(ac);
return REDIS_ERR;
}
/* Mark context as connected. */
c->flags |= REDIS_CONNECTED;
if (ac->onConnect) ac->onConnect(ac,REDIS_OK);
return REDIS_OK;
}
/* This function should be called when the socket is readable.
* It processes all replies that can be read and executes their callbacks.
*/
void redisAsyncHandleRead(redisAsyncContext *ac) {
redisContext *c = &(ac->c);
if (!(c->flags & REDIS_CONNECTED)) {
/* Abort connect was not successful. */
if (__redisAsyncHandleConnect(ac) != REDIS_OK)
return;
/* Try again later when the context is still not connected. */
if (!(c->flags & REDIS_CONNECTED))
return;
}
if (redisBufferRead(c) == REDIS_ERR) {
__redisAsyncDisconnect(ac);
} else {
/* Always re-schedule reads */
_EL_ADD_READ(ac);
redisProcessCallbacks(ac);
}
}
void redisAsyncHandleWrite(redisAsyncContext *ac) {
redisContext *c = &(ac->c);
int done = 0;
if (!(c->flags & REDIS_CONNECTED)) {
/* Abort connect was not successful. */
if (__redisAsyncHandleConnect(ac) != REDIS_OK)
return;
/* Try again later when the context is still not connected. */
if (!(c->flags & REDIS_CONNECTED))
return;
}
if (redisBufferWrite(c,&done) == REDIS_ERR) {
__redisAsyncDisconnect(ac);
} else {
/* Continue writing when not done, stop writing otherwise */
if (!done)
_EL_ADD_WRITE(ac);
else
_EL_DEL_WRITE(ac);
/* Always schedule reads after writes */
_EL_ADD_READ(ac);
}
}
/* Sets a pointer to the first argument and its length starting at p. Returns
* the number of bytes to skip to get to the following argument. */
static char *nextArgument(char *start, char **str, size_t *len) {
char *p = start;
if (p[0] != '$') {
p = strchr(p,'$');
if (p == NULL) return NULL;
}
*len = (int)strtol(p+1,NULL,10);
p = strchr(p,'\r');
assert(p);
*str = p+2;
return p+2+(*len)+2;
}
/* Helper function for the redisAsyncCommand* family of functions. Writes a
* formatted command to the output buffer and registers the provided callback
* function with the context. */
static int __redisAsyncCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, char *cmd, size_t len) {
redisContext *c = &(ac->c);
redisCallback cb;
int pvariant, hasnext;
char *cstr, *astr;
size_t clen, alen;
char *p;
sds sname;
/* Don't accept new commands when the connection is about to be closed. */
if (c->flags & (REDIS_DISCONNECTING | REDIS_FREEING)) return REDIS_ERR;
/* Setup callback */
cb.fn = fn;
cb.privdata = privdata;
/* Find out which command will be appended. */
p = nextArgument(cmd,&cstr,&clen);
assert(p != NULL);
hasnext = (p[0] == '$');
pvariant = (tolower(cstr[0]) == 'p') ? 1 : 0;
cstr += pvariant;
clen -= pvariant;
#ifndef HIREDIS_WIN
if (hasnext && strncasecmp(cstr,"subscribe\r\n",11) == 0) {
#else
if (hasnext && strnicmp(cstr,"subscribe\r\n",11) == 0) {
#endif
c->flags |= REDIS_SUBSCRIBED;
/* Add every channel/pattern to the list of subscription callbacks. */
while ((p = nextArgument(p,&astr,&alen)) != NULL) {
sname = sdsnewlen(astr,alen);
if (pvariant)
dictReplace(ac->sub.patterns,sname,&cb);
else
dictReplace(ac->sub.channels,sname,&cb);
}
#ifndef HIREDIS_WIN
} else if (strncasecmp(cstr,"unsubscribe\r\n",13) == 0) {
#else
} else if (strnicmp(cstr,"unsubscribe\r\n",13) == 0) {
#endif
/* It is only useful to call (P)UNSUBSCRIBE when the context is
* subscribed to one or more channels or patterns. */
if (!(c->flags & REDIS_SUBSCRIBED)) return REDIS_ERR;
/* (P)UNSUBSCRIBE does not have its own response: every channel or
* pattern that is unsubscribed will receive a message. This means we
* should not append a callback function for this command. */
#ifndef HIREDIS_WIN
} else if(strncasecmp(cstr,"monitor\r\n",9) == 0) {
#else
} else if(strnicmp(cstr,"monitor\r\n",9) == 0) {
#endif
/* Set monitor flag and push callback */
c->flags |= REDIS_MONITORING;
__redisPushCallback(&ac->replies,&cb);
} else {
if (c->flags & REDIS_SUBSCRIBED)
/* This will likely result in an error reply, but it needs to be
* received and passed to the callback. */
__redisPushCallback(&ac->sub.invalid,&cb);
else
__redisPushCallback(&ac->replies,&cb);
}
__redisAppendCommand(c,cmd,len);
/* Always schedule a write when the write buffer is non-empty */
_EL_ADD_WRITE(ac);
return REDIS_OK;
}
int redisvAsyncCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, const char *format, va_list ap) {
char *cmd;
int len;
int status;
len = redisvFormatCommand(&cmd,format,ap);
status = __redisAsyncCommand(ac,fn,privdata,cmd,len);
free(cmd);
return status;
}
int redisAsyncCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, const char *format, ...) {
va_list ap;
int status;
va_start(ap,format);
status = redisvAsyncCommand(ac,fn,privdata,format,ap);
va_end(ap);
return status;
}
int redisAsyncCommandArgv(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, int argc, const char **argv, const size_t *argvlen) {
char *cmd;
int len;
int status;
len = redisFormatCommandArgv(&cmd,argc,argv,argvlen);
status = __redisAsyncCommand(ac,fn,privdata,cmd,len);
free(cmd);
return status;
}
| {
"content_hash": "cc3c57f30f02a4918d45a5f9e993688c",
"timestamp": "",
"source": "github",
"line_count": 624,
"max_line_length": 139,
"avg_line_length": 32.80448717948718,
"alnum_prop": 0.6132877381533952,
"repo_name": "ayrb13/hiredis-win",
"id": "32a35b18c67ba9a6eb88ec00cb621e470ada68d9",
"size": "22216",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "async.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "166379"
}
],
"symlink_target": ""
} |
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>
#include "vtkUnstructuredGridBaseWrap.h"
#include "vtkCPExodusIIElementBlockWrap.h"
#include "vtkObjectWrap.h"
#include "../../plus/plus.h"
using namespace v8;
extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkCPExodusIIElementBlockWrap::ptpl;
VtkCPExodusIIElementBlockWrap::VtkCPExodusIIElementBlockWrap()
{ }
VtkCPExodusIIElementBlockWrap::VtkCPExodusIIElementBlockWrap(vtkSmartPointer<vtkCPExodusIIElementBlock> _native)
{ native = _native; }
VtkCPExodusIIElementBlockWrap::~VtkCPExodusIIElementBlockWrap()
{ }
void VtkCPExodusIIElementBlockWrap::Init(v8::Local<v8::Object> exports)
{
Nan::SetAccessor(exports, Nan::New("vtkCPExodusIIElementBlock").ToLocalChecked(), ConstructorGetter);
Nan::SetAccessor(exports, Nan::New("CPExodusIIElementBlock").ToLocalChecked(), ConstructorGetter);
}
void VtkCPExodusIIElementBlockWrap::ConstructorGetter(
v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info)
{
InitPtpl();
info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}
void VtkCPExodusIIElementBlockWrap::InitPtpl()
{
if (!ptpl.IsEmpty()) return;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
VtkUnstructuredGridBaseWrap::InitPtpl( );
tpl->Inherit(Nan::New<FunctionTemplate>(VtkUnstructuredGridBaseWrap::ptpl));
tpl->SetClassName(Nan::New("VtkCPExodusIIElementBlockWrap").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName);
Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName);
Nan::SetPrototypeMethod(tpl, "IsA", IsA);
Nan::SetPrototypeMethod(tpl, "isA", IsA);
Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);
#ifdef VTK_NODE_PLUS_VTKCPEXODUSIIELEMENTBLOCKWRAP_INITPTPL
VTK_NODE_PLUS_VTKCPEXODUSIIELEMENTBLOCKWRAP_INITPTPL
#endif
ptpl.Reset( tpl );
}
void VtkCPExodusIIElementBlockWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
if(!info.IsConstructCall())
{
Nan::ThrowError("Constructor not called in a construct call.");
return;
}
if(info.Length() == 0)
{
vtkSmartPointer<vtkCPExodusIIElementBlock> native = vtkSmartPointer<vtkCPExodusIIElementBlock>::New();
VtkCPExodusIIElementBlockWrap* obj = new VtkCPExodusIIElementBlockWrap(native);
obj->Wrap(info.This());
}
else
{
if(info[0]->ToObject() != vtkNodeJsNoWrap )
{
Nan::ThrowError("Parameter Error");
return;
}
}
info.GetReturnValue().Set(info.This());
}
void VtkCPExodusIIElementBlockWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkCPExodusIIElementBlockWrap *wrapper = ObjectWrap::Unwrap<VtkCPExodusIIElementBlockWrap>(info.Holder());
vtkCPExodusIIElementBlock *native = (vtkCPExodusIIElementBlock *)wrapper->native.GetPointer();
char const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetClassName();
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}
void VtkCPExodusIIElementBlockWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkCPExodusIIElementBlockWrap *wrapper = ObjectWrap::Unwrap<VtkCPExodusIIElementBlockWrap>(info.Holder());
vtkCPExodusIIElementBlock *native = (vtkCPExodusIIElementBlock *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsString())
{
Nan::Utf8String a0(info[0]);
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->IsA(
*a0
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkCPExodusIIElementBlockWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkCPExodusIIElementBlockWrap *wrapper = ObjectWrap::Unwrap<VtkCPExodusIIElementBlockWrap>(info.Holder());
vtkCPExodusIIElementBlock *native = (vtkCPExodusIIElementBlock *)wrapper->native.GetPointer();
vtkCPExodusIIElementBlock * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->NewInstance();
VtkCPExodusIIElementBlockWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkCPExodusIIElementBlockWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkCPExodusIIElementBlockWrap *w = new VtkCPExodusIIElementBlockWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkCPExodusIIElementBlockWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkCPExodusIIElementBlockWrap *wrapper = ObjectWrap::Unwrap<VtkCPExodusIIElementBlockWrap>(info.Holder());
vtkCPExodusIIElementBlock *native = (vtkCPExodusIIElementBlock *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0]))
{
VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject());
vtkCPExodusIIElementBlock * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->SafeDownCast(
(vtkObject *) a0->native.GetPointer()
);
VtkCPExodusIIElementBlockWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkCPExodusIIElementBlockWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkCPExodusIIElementBlockWrap *w = new VtkCPExodusIIElementBlockWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
Nan::ThrowError("Parameter mismatch");
}
| {
"content_hash": "27bc3b38f51b5d778378b338971b0dd5",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 112,
"avg_line_length": 32.63387978142077,
"alnum_prop": 0.7474882786336235,
"repo_name": "axkibe/node-vtk",
"id": "de943b778ce3474a7af880be1c3784ec0fde7ee6",
"size": "5972",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "wrappers/7.0.0/vtkCPExodusIIElementBlockWrap.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "75388342"
},
{
"name": "CMake",
"bytes": "915"
},
{
"name": "JavaScript",
"bytes": "70"
},
{
"name": "Roff",
"bytes": "145455"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<CompatibilityEntry Name=".NET Framework 2.0 Service Pack 2"
Platform="Desktop"
Version="2.0.2"
Priority="3515">
<Member>System.String.#Compare(System.String,System.String,System.Globalization.CultureInfo,System.Globalization.CompareOptions)</Member>
<Member>System.String.#Compare(System.String,System.Int32,System.String,System.Int32,System.Int32,System.Globalization.CultureInfo,System.Globalization.CompareOptions)</Member>
<Member>System.AppDomainManager.#CheckSecuritySettings(System.Security.SecurityState)</Member>
<Type>System.GCNotificationStatus</Type>
<Member>System.GC.#RegisterForFullGCNotification(System.Int32,System.Int32)</Member>
<Member>System.GC.#CancelFullGCNotification()</Member>
<Member>System.GC.#WaitForFullGCApproach()</Member>
<Member>System.GC.#WaitForFullGCApproach(System.Int32)</Member>
<Member>System.GC.#WaitForFullGCComplete()</Member>
<Member>System.GC.#WaitForFullGCComplete(System.Int32)</Member>
<Member>System.PlatformID.#Xbox</Member>
<Member>System.PlatformID.#MacOSX</Member>
<Member>System.Threading.WaitHandle.#WaitOne(System.Int32)</Member>
<Member>System.Threading.WaitHandle.#WaitOne(System.TimeSpan)</Member>
<Member>System.Threading.WaitHandle.#WaitAll(System.Threading.WaitHandle[],System.Int32)</Member>
<Member>System.Threading.WaitHandle.#WaitAll(System.Threading.WaitHandle[],System.TimeSpan)</Member>
<Member>System.Threading.WaitHandle.#WaitAny(System.Threading.WaitHandle[],System.Int32)</Member>
<Member>System.Threading.WaitHandle.#WaitAny(System.Threading.WaitHandle[],System.TimeSpan)</Member>
<Member>System.Reflection.MethodImplAttributes.#NoOptimization</Member>
<Member>System.Security.Policy.AllMembershipCondition.#System.Security.Policy.IReportMatchMembershipCondition.Check(System.Security.Policy.Evidence,System.Object&)</Member>
<Member>System.Security.Policy.ApplicationDirectoryMembershipCondition.#System.Security.Policy.IReportMatchMembershipCondition.Check(System.Security.Policy.Evidence,System.Object&)</Member>
<Member>System.Security.Policy.SiteMembershipCondition.#System.Security.Policy.IReportMatchMembershipCondition.Check(System.Security.Policy.Evidence,System.Object&)</Member>
<Member>System.Security.Policy.StrongName.#System.Security.Policy.IDelayEvaluatedEvidence.get_IsVerified()</Member>
<Member>System.Security.Policy.StrongName.#System.Security.Policy.IDelayEvaluatedEvidence.get_WasUsed()</Member>
<Member>System.Security.Policy.StrongName.#System.Security.Policy.IDelayEvaluatedEvidence.MarkUsed()</Member>
<Member>System.Security.Policy.StrongNameMembershipCondition.#System.Security.Policy.IReportMatchMembershipCondition.Check(System.Security.Policy.Evidence,System.Object&)</Member>
<Member>System.Security.Policy.UrlMembershipCondition.#System.Security.Policy.IReportMatchMembershipCondition.Check(System.Security.Policy.Evidence,System.Object&)</Member>
<Member>System.Security.Policy.ZoneMembershipCondition.#System.Security.Policy.IReportMatchMembershipCondition.Check(System.Security.Policy.Evidence,System.Object&)</Member>
<Member>System.Security.Policy.GacMembershipCondition.#System.Security.Policy.IReportMatchMembershipCondition.Check(System.Security.Policy.Evidence,System.Object&)</Member>
<Member>System.Security.Policy.HashMembershipCondition.#System.Security.Policy.IReportMatchMembershipCondition.Check(System.Security.Policy.Evidence,System.Object&)</Member>
<Member>System.Security.Policy.PublisherMembershipCondition.#System.Security.Policy.IReportMatchMembershipCondition.Check(System.Security.Policy.Evidence,System.Object&)</Member>
<Type>System.Runtime.InteropServices.AllowReversePInvokeCallsAttribute</Type>
<Member>System.Runtime.CompilerServices.InternalsVisibleToAttribute.#get_AllInternalsVisible()</Member>
<Member>System.Runtime.CompilerServices.InternalsVisibleToAttribute.#set_AllInternalsVisible(System.Boolean)</Member>
<Member>System.Runtime.CompilerServices.MethodImplOptions.#NoOptimization</Member>
<Type>System.Security.SecuritySafeCriticalAttribute</Type>
<Type>System.Security.SecurityState</Type>
<Type>System.Data.SqlTypes.SqlFileStream</Type>
<Member>System.Deployment.Application.ApplicationDeployment.#CheckForDetailedUpdate(System.Boolean)</Member>
<Member>System.Deployment.Application.ApplicationDeployment.#CheckForUpdate(System.Boolean)</Member>
<Member>System.Deployment.Application.DeploymentServiceCom.#ActivateDeploymentEx(System.String,System.Int32,System.Int32)</Member>
<Member>System.Deployment.Application.InPlaceHostingManager.#AssertApplicationRequirements(System.Boolean)</Member>
<Member>System.Deployment.Application.InPlaceHostingManager.#UninstallCustomUXApplication(System.String)</Member>
<Member>System.Deployment.Application.DownloadApplicationCompletedEventArgs.#get_ShortcutAppId()</Member>
<Member>System.Web.UI.Design.WebControls.WizardDesigner.#OnComponentChanged(System.Object,System.ComponentModel.Design.ComponentChangedEventArgs)</Member>
<Type>System.Web.UI.Design.WebControls.DataControlFieldDesigner</Type>
<Type>System.ComponentModel.DateTimeOffsetConverter</Type>
<Member>System.Net.ServicePoint.#SetTcpKeepAlive(System.Boolean,System.Int32,System.Int32)</Member>
<Member>System.Net.ServicePointManager.#SetTcpKeepAlive(System.Boolean,System.Int32,System.Int32)</Member>
<Member>System.Web.HttpContext.#RemapHandler(System.Web.IHttpHandler)</Member>
<Member>System.Web.HttpRuntime.#get_UsingIntegratedPipeline()</Member>
<Type>System.Web.Caching.CacheItemUpdateCallback</Type>
<Type>System.Web.Caching.CacheItemUpdateReason</Type>
<Member>System.Web.Caching.Cache.#Insert(System.String,System.Object,System.Web.Caching.CacheDependency,System.DateTime,System.TimeSpan,System.Web.Caching.CacheItemUpdateCallback)</Member>
<Member>System.Web.Compilation.ClientBuildManagerCallback.#InitializeLifetimeService()</Member>
<Member>System.Web.Configuration.BrowserCapabilitiesFactoryBase.#ConfigureCustomCapabilities(System.Collections.Specialized.NameValueCollection,System.Web.HttpBrowserCapabilities)</Member>
<Type>System.Web.Configuration.CustomErrorsRedirectMode</Type>
<Member>System.Web.Configuration.CustomErrorsSection.#get_RedirectMode()</Member>
<Member>System.Web.Configuration.CustomErrorsSection.#set_RedirectMode(System.Web.Configuration.CustomErrorsRedirectMode)</Member>
<Type>System.Web.Configuration.MachineKeyCompatibilityMode</Type>
<Member>System.Web.Configuration.MachineKeySection.#get_CompatibilityMode()</Member>
<Member>System.Web.Configuration.MachineKeySection.#set_CompatibilityMode(System.Web.Configuration.MachineKeyCompatibilityMode)</Member>
<Member>System.Web.Configuration.PagesSection.#get_RenderAllHiddenFieldsAtTopOfForm()</Member>
<Member>System.Web.Configuration.PagesSection.#set_RenderAllHiddenFieldsAtTopOfForm(System.Boolean)</Member>
<Member>System.Web.UI.Page.#get_AutoPostBackControl()</Member>
<Member>System.Web.UI.Page.#set_AutoPostBackControl(System.Web.UI.Control)</Member>
<Member>System.Web.UI.Page.#get_IsPostBackEventControlRegistered()</Member>
<Member>System.Web.UI.HtmlControls.HtmlForm.#get_Action()</Member>
<Member>System.Web.UI.HtmlControls.HtmlForm.#set_Action(System.String)</Member>
<Type>System.Web.UI.IAutoFieldGenerator</Type>
<Type>System.Web.UI.IBindableControl</Type>
<Member>System.Web.UI.WebControls.DataBoundControl.#get_DataSourceObject()</Member>
<Member>System.Web.UI.WebControls.BoundField.#LoadViewState(System.Object)</Member>
<Member>System.Web.UI.WebControls.Parameter.#.ctor(System.String,System.Data.DbType)</Member>
<Member>System.Web.UI.WebControls.Parameter.#.ctor(System.String,System.Data.DbType,System.String)</Member>
<Member>System.Web.UI.WebControls.Parameter.#get_DbType()</Member>
<Member>System.Web.UI.WebControls.Parameter.#set_DbType(System.Data.DbType)</Member>
<Member>System.Web.UI.WebControls.Parameter.#GetDatabaseType()</Member>
<Member>System.Web.UI.WebControls.Parameter.#ConvertDbTypeToTypeCode(System.Data.DbType)</Member>
<Member>System.Web.UI.WebControls.Parameter.#ConvertTypeCodeToDbType(System.TypeCode)</Member>
<Member>System.Web.UI.WebControls.ControlParameter.#.ctor(System.String,System.Data.DbType,System.String,System.String)</Member>
<Member>System.Web.UI.WebControls.CookieParameter.#.ctor(System.String,System.Data.DbType,System.String)</Member>
<Type>System.Web.UI.WebControls.DataBoundControlMode</Type>
<Member>System.Web.UI.WebControls.DetailsView.#get_EnableModelValidation()</Member>
<Member>System.Web.UI.WebControls.DetailsView.#set_EnableModelValidation(System.Boolean)</Member>
<Member>System.Web.UI.WebControls.DetailsView.#get_RowsGenerator()</Member>
<Member>System.Web.UI.WebControls.DetailsView.#set_RowsGenerator(System.Web.UI.IAutoFieldGenerator)</Member>
<Member>System.Web.UI.WebControls.FormParameter.#.ctor(System.String,System.Data.DbType,System.String)</Member>
<Member>System.Web.UI.WebControls.FormView.#get_EnableModelValidation()</Member>
<Member>System.Web.UI.WebControls.FormView.#set_EnableModelValidation(System.Boolean)</Member>
<Type>System.Web.UI.WebControls.IPersistedSelector</Type>
<Member>System.Web.UI.WebControls.GridView.#get_ColumnsGenerator()</Member>
<Member>System.Web.UI.WebControls.GridView.#set_ColumnsGenerator(System.Web.UI.IAutoFieldGenerator)</Member>
<Member>System.Web.UI.WebControls.GridView.#get_EnableModelValidation()</Member>
<Member>System.Web.UI.WebControls.GridView.#set_EnableModelValidation(System.Boolean)</Member>
<Member>System.Web.UI.WebControls.GridView.#get_SelectedPersistedDataKey()</Member>
<Member>System.Web.UI.WebControls.GridView.#set_SelectedPersistedDataKey(System.Web.UI.WebControls.DataKey)</Member>
<Member>System.Web.UI.WebControls.GridView.#System.Web.UI.WebControls.IPersistedSelector.get_DataKey()</Member>
<Member>System.Web.UI.WebControls.GridView.#System.Web.UI.WebControls.IPersistedSelector.set_DataKey(System.Web.UI.WebControls.DataKey)</Member>
<Member>System.Web.UI.WebControls.ParameterCollection.#Add(System.String,System.Data.DbType,System.String)</Member>
<Member>System.Web.UI.WebControls.ProfileParameter.#.ctor(System.String,System.Data.DbType,System.String)</Member>
<Member>System.Web.UI.WebControls.QueryStringParameter.#.ctor(System.String,System.Data.DbType,System.String)</Member>
<Member>System.Web.UI.WebControls.SessionParameter.#.ctor(System.String,System.Data.DbType,System.String)</Member>
<Member>System.Windows.Forms.Control.#get_ImeModeBase()</Member>
<Member>System.Windows.Forms.Control.#set_ImeModeBase(System.Windows.Forms.ImeMode)</Member>
<Member>System.Windows.Forms.Control.#get_PropagatingImeMode()</Member>
<Type>System.Windows.Forms.ImeContext</Type>
<Type>System.Windows.Forms.ImeModeConversion</Type>
<Member>System.Windows.Forms.TextBoxBase.#get_ImeModeBase()</Member>
<Member>System.Windows.Forms.TextBoxBase.#set_ImeModeBase(System.Windows.Forms.ImeMode)</Member>
<Member>System.Windows.Forms.SplitContainer.#OnMove(System.EventArgs)</Member>
<Member>System.Windows.Forms.WebBrowserBase.#ProcessDialogKey(System.Windows.Forms.Keys)</Member>
</CompatibilityEntry> | {
"content_hash": "05642cd3ce09cee620009ae1023b67a1",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 195,
"avg_line_length": 96.49579831932773,
"alnum_prop": 0.8080640947487591,
"repo_name": "luomingui/LCLFramework",
"id": "74f741080df0fc15868025d59f926f51c15f0518",
"size": "11483",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "Source/tools/FxCop/Repository/Compatibility/Desktop2.0SP2.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "303"
},
{
"name": "Batchfile",
"bytes": "2385"
},
{
"name": "C#",
"bytes": "1463270"
},
{
"name": "CSS",
"bytes": "3088"
},
{
"name": "HTML",
"bytes": "3945"
},
{
"name": "JavaScript",
"bytes": "14028"
},
{
"name": "PowerShell",
"bytes": "979"
},
{
"name": "XSLT",
"bytes": "58161"
}
],
"symlink_target": ""
} |
<%= @ArticleText %> | {
"content_hash": "29fbe8cb0518b428baebe22e50e77a1e",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 19,
"avg_line_length": 19,
"alnum_prop": 0.5789473684210527,
"repo_name": "nickloose/DisOrder",
"id": "369cd451e80a35717ebc7d168c8e12acc846be07",
"size": "19",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/DisOrder/defaults/themes/baseArticle.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "10779"
}
],
"symlink_target": ""
} |
#define ROOT_NAME "testTimedSemaphore"
#include "fw_helper.hpp"
#include <ace/Synch.h>
class ThreadAcquire : public ACE_Task_Base {
public:
ThreadAcquire(ACE_Thread_Semaphore& sema, int acquireSecs)
: ACE_Task_Base(),
m_sema(sema),
m_acquireSecs(acquireSecs),
m_status(0) {}
int svc() {
ACE_Time_Value start = ACE_OS::gettimeofday();
ACE_Time_Value interval(m_acquireSecs, 0); // 10 seconds
ACE_Time_Value expireAt = start + interval;
printf("Thread acquiring lock at %ld msecs.\n", start.msec());
if (m_sema.acquire(expireAt) == 0) {
interval = ACE_OS::gettimeofday() - start;
printf("Thread acquired lock after %ld msecs.\n", interval.msec());
m_status = 0;
} else {
interval = ACE_OS::gettimeofday() - start;
printf("Thread failed to acquire lock after %ld msecs.\n",
interval.msec());
m_status = -1;
}
return m_status;
}
int getStatus() { return m_status; }
private:
ACE_Thread_Semaphore& m_sema;
int m_acquireSecs;
int m_status;
};
BEGIN_TEST(CheckTimedAcquire)
{
ACE_Thread_Semaphore sema(1);
ThreadAcquire* thread = new ThreadAcquire(sema, 10);
sema.acquire();
thread->activate();
LOG("Sleeping for 8 secs.");
ACE_OS::sleep(8);
ASSERT(thread->thr_count() == 1, "Expected thread to be running.");
sema.release();
SLEEP(50); // Sleep for a few millis for the thread to end.
ASSERT(thread->thr_count() == 0, "Expected no thread to be running.");
ASSERT(thread->wait() == 0, "Expected successful end of thread.");
ASSERT(thread->getStatus() == 0, "Expected zero exit status from thread.");
delete thread;
}
END_TEST(CheckTimedAcquire)
BEGIN_TEST(CheckTimedAcquireFail)
{
ACE_Thread_Semaphore sema(0);
ThreadAcquire* thread = new ThreadAcquire(sema, 10);
thread->activate();
LOG("Sleeping for 8 secs.");
ACE_OS::sleep(8);
ASSERT(thread->thr_count() == 1, "Expected thread to be running.");
ACE_OS::sleep(3);
ASSERT(thread->thr_count() == 0, "Expected no thread to be running.");
ASSERT(thread->wait() == 0, "Expected successful end of thread.");
ASSERT(thread->getStatus() == -1,
"Expected non-zero exit status from thread.");
delete thread;
}
END_TEST(CheckTimedAcquireFail)
BEGIN_TEST(CheckNoWait)
{
ACE_Thread_Semaphore sema(0);
ThreadAcquire* thread = new ThreadAcquire(sema, 10);
sema.release();
thread->activate();
ACE_OS::sleep(1);
ASSERT(thread->thr_count() == 0, "Expected no thread to be running.");
ASSERT(thread->wait() == 0, "Expected successful end of thread.");
ASSERT(thread->getStatus() == 0, "Expected zero exit status from thread.");
delete thread;
}
END_TEST(CheckNoWait)
BEGIN_TEST(CheckResetAndTimedAcquire)
{
ACE_Thread_Semaphore sema(1);
ThreadAcquire* thread = new ThreadAcquire(sema, 10);
sema.acquire();
ACE_OS::sleep(1);
sema.release();
sema.release();
sema.release();
while (sema.tryacquire() != -1) {
;
}
thread->activate();
LOG("Sleeping for 8 secs.");
ACE_OS::sleep(8);
ASSERT(thread->thr_count() == 1, "Expected thread to be running.");
sema.release();
SLEEP(50); // Sleep for a few millis for the thread to end.
ASSERT(thread->thr_count() == 0, "Expected no thread to be running.");
ASSERT(thread->wait() == 0, "Expected successful end of thread.");
ASSERT(thread->getStatus() == 0, "Expected zero exit status from thread.");
delete thread;
}
END_TEST(CheckResetAndTimedAcquire)
| {
"content_hash": "e1d8909adb8d2df3d886f6041fe0e22a",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 79,
"avg_line_length": 28.4251968503937,
"alnum_prop": 0.6335180055401662,
"repo_name": "mhansonp/geode-native",
"id": "4031f468c6ed22638017c4bc46974a5cd4aee46c",
"size": "4412",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "cppcache/integration-test/testTimedSemaphore.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1899"
},
{
"name": "C#",
"bytes": "3515617"
},
{
"name": "C++",
"bytes": "10771399"
},
{
"name": "CMake",
"bytes": "107196"
},
{
"name": "GAP",
"bytes": "73860"
},
{
"name": "Java",
"bytes": "408387"
},
{
"name": "Perl",
"bytes": "2704"
},
{
"name": "PowerShell",
"bytes": "20450"
},
{
"name": "Shell",
"bytes": "35505"
}
],
"symlink_target": ""
} |
import { bindable, customElement, noView } from 'aurelia-templating';
import { inject } from 'aurelia-dependency-injection';
import { computedFrom } from 'aurelia-framework';
import { AttributeManager } from '../common/attributeManager';
import { getBooleanFromAttributeValue } from '../common/attributes';
import { Ui5ListBase} from '../list-base/list-base';
@customElement('ui5-list')
@inject(Element)
export class Ui5List extends Ui5ListBase{
_list = null;
_parent = null;
_relation = null;
@bindable ui5Id = null;
@bindable ui5Class = null;
@bindable ui5Tooltip = null;
@bindable prevId = null;
@bindable() backgroundDesign = 'Solid';
/* inherited from sap.m.ListBase*/
@bindable() inset = false;
@bindable() headerText = null;
@bindable() footerText = null;
@bindable() mode = 'None';
@bindable() width = '100%';
@bindable() includeItemInSelection = false;
@bindable() showUnread = false;
@bindable() noDataText = null;
@bindable() showNoData = true;
@bindable() enableBusyIndicator = true;
@bindable() modeAnimationOn = true;
@bindable() showSeparators = 'All';
@bindable() swipeDirection = 'Both';
@bindable() growing = false;
@bindable() growingThreshold = 20;
@bindable() growingTriggerText = null;
@bindable() growingScrollToLoad = false;
@bindable() growingDirection = 'Downwards';
@bindable() rememberSelections = true;
@bindable() keyboardMode = 'Navigation';
@bindable() sticky = null;
@bindable() selectionChange = this.defaultFunc;
@bindable() delete = this.defaultFunc;
@bindable() swipe = this.defaultFunc;
@bindable() updateStarted = this.defaultFunc;
@bindable() updateFinished = this.defaultFunc;
@bindable() itemPress = this.defaultFunc;
@bindable() beforeOpenContextMenu = this.defaultFunc;
/* inherited from sap.ui.core.Control*/
@bindable() busy = false;
@bindable() busyIndicatorDelay = 1000;
@bindable() busyIndicatorSize = 'Medium';
@bindable() visible = true;
@bindable() fieldGroupIds = '[]';
@bindable() validateFieldGroup = this.defaultFunc;
/* inherited from sap.ui.core.Element*/
/* inherited from sap.ui.base.ManagedObject*/
@bindable() validationSuccess = this.defaultFunc;
@bindable() validationError = this.defaultFunc;
@bindable() parseError = this.defaultFunc;
@bindable() formatError = this.defaultFunc;
@bindable() modelContextChange = this.defaultFunc;
/* inherited from sap.ui.base.EventProvider*/
/* inherited from sap.ui.base.Object*/
constructor(element) {
super(element);
this.element = element;
this.attributeManager = new AttributeManager(this.element);
}
@computedFrom('_list')
get UIElement() {
return this._list;
}
fillProperties(params){
params.backgroundDesign = this.backgroundDesign;
super.fillProperties(params);
}
defaultFunc() {
}
attached() {
var that = this;
var params = {};
this.fillProperties(params);
if (this.ui5Id)
this._list = new sap.m.List(this.ui5Id, params);
else
this._list = new sap.m.List(params);
if(this.ui5Class)
this._list.addStyleClass(this.ui5Class);
if(this.ui5Tooltip)
this._list.setTooltip(this.ui5Tooltip);
if (this._list._oGrowingDelegate){this._list._oGrowingDelegate.updateItems = function(sChangeReason) { this._onBeforePageLoaded(sChangeReason);this._onAfterPageLoaded(sChangeReason); }; }
if ($(this.element).closest("[ui5-container]").length > 0) {
this._parent = $(this.element).closest("[ui5-container]")[0].au.controller.viewModel;
if (!this._parent.UIElement || (this._parent.UIElement.sId != this._list.sId)) {
var prevSibling = null;
this._relation = this._parent.addChild(this._list, this.element, this.prevId);
this.attributeManager.addAttributes({"ui5-container": '' });
}
else {
this._parent = $(this.element.parentElement).closest("[ui5-container]")[0].au.controller.viewModel;
var prevSibling = null;
this._relation = this._parent.addChild(this._list, this.element, this.prevId);
this.attributeManager.addAttributes({"ui5-container": '' });
}
}
else {
if(this._list.placeAt)
this._list.placeAt(this.element.parentElement);
this.attributeManager.addAttributes({"ui5-container": '' });
this.attributeManager.addClasses("ui5-hide");
}
//<!container>
//</!container>
this.attributeManager.addAttributes({"ui5-id": this._list.sId});
}
detached() {
try{
if ($(this.element).closest("[ui5-container]").length > 0) {
if (this._parent && this._relation) {
if(this._list)
this._parent.removeChildByRelation(this._list, this._relation);
}
}
else{
this._list.destroy();
}
super.detached();
}
catch(err){}
}
addChild(child, elem, afterElement) {
var path = jQuery.makeArray($(elem).parentsUntil(this.element));
for (elem of path) {
try{
if (elem.localName == 'items') { var _index = afterElement?Math.floor(afterElement+1):null; if (_index)this._list.insertItem(child, _index); else this._list.addItem(child, 0); return elem.localName; }
if (elem.localName == 'swipecontent') { this._list.setSwipeContent(child); return elem.localName;}
if (elem.localName == 'headertoolbar') { this._list.setHeaderToolbar(child); return elem.localName;}
if (elem.localName == 'infotoolbar') { this._list.setInfoToolbar(child); return elem.localName;}
if (elem.localName == 'contextmenu') { this._list.setContextMenu(child); return elem.localName;}
if (elem.localName == 'tooltip') { this._list.setTooltip(child); return elem.localName;}
if (elem.localName == 'customdata') { var _index = afterElement?Math.floor(afterElement+1):null; if (_index)this._list.insertCustomData(child, _index); else this._list.addCustomData(child, 0); return elem.localName; }
if (elem.localName == 'layoutdata') { this._list.setLayoutData(child); return elem.localName;}
if (elem.localName == 'dependents') { var _index = afterElement?Math.floor(afterElement+1):null; if (_index)this._list.insertDependent(child, _index); else this._list.addDependent(child, 0); return elem.localName; }
if (elem.localName == 'dragdropconfig') { var _index = afterElement?Math.floor(afterElement+1):null; if (_index)this._list.insertDragDropConfig(child, _index); else this._list.addDragDropConfig(child, 0); return elem.localName; }
}
catch(err){}
}
}
removeChildByRelation(child, relation) {
try{
if (relation == 'items') { this._list.removeItem(child);}
if (relation == 'swipecontent') { this._list.destroySwipeContent(child); }
if (relation == 'headertoolbar') { this._list.destroyHeaderToolbar(child); }
if (relation == 'infotoolbar') { this._list.destroyInfoToolbar(child); }
if (relation == 'contextmenu') { this._list.destroyContextMenu(child); }
if (relation == 'tooltip') { this._list.destroyTooltip(child); }
if (relation == 'customdata') { this._list.removeCustomData(child);}
if (relation == 'layoutdata') { this._list.destroyLayoutData(child); }
if (relation == 'dependents') { this._list.removeDependent(child);}
if (relation == 'dragdropconfig') { this._list.removeDragDropConfig(child);}
}
catch(err){}
}
backgroundDesignChanged(newValue){if(newValue!=null && newValue!=undefined && this._list!==null){ this._list.setBackgroundDesign(newValue);}}
insetChanged(newValue){if(this._list!==null){ this._list.setInset(getBooleanFromAttributeValue(newValue));}}
headerTextChanged(newValue){if(this._list!==null){ this._list.setHeaderText(newValue);}}
footerTextChanged(newValue){if(this._list!==null){ this._list.setFooterText(newValue);}}
modeChanged(newValue){if(this._list!==null){ this._list.setMode(newValue);}}
widthChanged(newValue){if(this._list!==null){ this._list.setWidth(newValue);}}
includeItemInSelectionChanged(newValue){if(this._list!==null){ this._list.setIncludeItemInSelection(getBooleanFromAttributeValue(newValue));}}
showUnreadChanged(newValue){if(this._list!==null){ this._list.setShowUnread(getBooleanFromAttributeValue(newValue));}}
noDataTextChanged(newValue){if(this._list!==null){ this._list.setNoDataText(newValue);}}
showNoDataChanged(newValue){if(this._list!==null){ this._list.setShowNoData(getBooleanFromAttributeValue(newValue));}}
enableBusyIndicatorChanged(newValue){if(this._list!==null){ this._list.setEnableBusyIndicator(getBooleanFromAttributeValue(newValue));}}
modeAnimationOnChanged(newValue){if(this._list!==null){ this._list.setModeAnimationOn(getBooleanFromAttributeValue(newValue));}}
showSeparatorsChanged(newValue){if(this._list!==null){ this._list.setShowSeparators(newValue);}}
swipeDirectionChanged(newValue){if(this._list!==null){ this._list.setSwipeDirection(newValue);}}
growingChanged(newValue){if(this._list!==null){ this._list.setGrowing(getBooleanFromAttributeValue(newValue));}}
growingThresholdChanged(newValue){if(this._list!==null){ this._list.setGrowingThreshold(newValue);}}
growingTriggerTextChanged(newValue){if(this._list!==null){ this._list.setGrowingTriggerText(newValue);}}
growingScrollToLoadChanged(newValue){if(this._list!==null){ this._list.setGrowingScrollToLoad(getBooleanFromAttributeValue(newValue));}}
growingDirectionChanged(newValue){if(this._list!==null){ this._list.setGrowingDirection(newValue);}}
rememberSelectionsChanged(newValue){if(this._list!==null){ this._list.setRememberSelections(getBooleanFromAttributeValue(newValue));}}
keyboardModeChanged(newValue){if(this._list!==null){ this._list.setKeyboardMode(newValue);}}
stickyChanged(newValue){if(this._list!==null){ this._list.setSticky(newValue);}}
/* inherited from sap.m.ListBase*/
selectionChangeChanged(newValue){if(newValue!=null && newValue!=undefined && this._list!==null){ this._list.attachSelectionChange(newValue);}}
deleteChanged(newValue){if(newValue!=null && newValue!=undefined && this._list!==null){ this._list.attachDelete(newValue);}}
swipeChanged(newValue){if(newValue!=null && newValue!=undefined && this._list!==null){ this._list.attachSwipe(newValue);}}
updateStartedChanged(newValue){if(newValue!=null && newValue!=undefined && this._list!==null){ this._list.attachUpdateStarted(newValue);}}
updateFinishedChanged(newValue){if(newValue!=null && newValue!=undefined && this._list!==null){ this._list.attachUpdateFinished(newValue);}}
itemPressChanged(newValue){if(newValue!=null && newValue!=undefined && this._list!==null){ this._list.attachItemPress(newValue);}}
beforeOpenContextMenuChanged(newValue){if(newValue!=null && newValue!=undefined && this._list!==null){ this._list.attachBeforeOpenContextMenu(newValue);}}
busyChanged(newValue){if(this._list!==null){ this._list.setBusy(getBooleanFromAttributeValue(newValue));}}
busyIndicatorDelayChanged(newValue){if(this._list!==null){ this._list.setBusyIndicatorDelay(newValue);}}
busyIndicatorSizeChanged(newValue){if(this._list!==null){ this._list.setBusyIndicatorSize(newValue);}}
visibleChanged(newValue){if(this._list!==null){ this._list.setVisible(getBooleanFromAttributeValue(newValue));}}
fieldGroupIdsChanged(newValue){if(this._list!==null){ this._list.setFieldGroupIds(newValue);}}
/* inherited from sap.ui.core.Control*/
validateFieldGroupChanged(newValue){if(newValue!=null && newValue!=undefined && this._list!==null){ this._list.attachValidateFieldGroup(newValue);}}
/* inherited from sap.ui.core.Element*/
/* inherited from sap.ui.base.ManagedObject*/
validationSuccessChanged(newValue){if(newValue!=null && newValue!=undefined && this._list!==null){ this._list.attachValidationSuccess(newValue);}}
validationErrorChanged(newValue){if(newValue!=null && newValue!=undefined && this._list!==null){ this._list.attachValidationError(newValue);}}
parseErrorChanged(newValue){if(newValue!=null && newValue!=undefined && this._list!==null){ this._list.attachParseError(newValue);}}
formatErrorChanged(newValue){if(newValue!=null && newValue!=undefined && this._list!==null){ this._list.attachFormatError(newValue);}}
modelContextChangeChanged(newValue){if(newValue!=null && newValue!=undefined && this._list!==null){ this._list.attachModelContextChange(newValue);}}
/* inherited from sap.ui.base.EventProvider*/
/* inherited from sap.ui.base.Object*/
} | {
"content_hash": "a64aed840c19749e6c288117cafe7994",
"timestamp": "",
"source": "github",
"line_count": 222,
"max_line_length": 230,
"avg_line_length": 64.28378378378379,
"alnum_prop": 0.6185971550697218,
"repo_name": "Hochfrequenz/aurelia-openui5-bridge",
"id": "d4d4911f33d0a0a6c6983b9730c699e558c11084",
"size": "14271",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "dist/es6/list/list.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "59606"
},
{
"name": "JavaScript",
"bytes": "1265604"
}
],
"symlink_target": ""
} |
package br.ufc.lps.splar.core.fm.randomization;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import br.ufc.lps.splar.core.constraints.PropositionalFormula;
import br.ufc.lps.splar.core.fm.FeatureGroup;
import br.ufc.lps.splar.core.fm.FeatureModel;
import br.ufc.lps.splar.core.fm.FeatureModelException;
import br.ufc.lps.splar.core.fm.FeatureTreeNode;
import br.ufc.lps.splar.core.fm.GroupedFeature;
import br.ufc.lps.splar.core.fm.RootNode;
import br.ufc.lps.splar.core.fm.SolitaireFeature;
import br.ufc.lps.splar.core.fm.TreeNodeRendererFactory;
public class RandomFeatureModel extends FeatureModel {
private int numberOfFeaturesToCreate; // total number of features in the feature model not counting feature group nodes
private int maxChildrenPerNode; // max number of children for a given node (opt, mand, and group count as one)
private int minChildrenPerNode; // min number of children for a given node (opt, mand, and group count as one)
private int mandatoryOdds; // odds for mandatory features
private int optionalOdds; // odds for optional features
private int group1NOdds; // odds for [1,*] groups
private int group11Odds; // odds for [1,1] groups
private int maxGroupCardinality; // max number of grouped features in a group
private int balanceFactor; // [0%-100%] indicate the % of nodes that will NOT have children
public RandomFeatureModel(String name,int numberOfFeaturesToCreate, int mandatoryOdds, int optionalOdds, int group1NOdds, int group11Odds, int minChildrenPerNode, int maxChildrenPerNode, int maxGroupCardinality, int balanceFactor) {
super();
setName(name);
// feature tree parameters
this.numberOfFeaturesToCreate = numberOfFeaturesToCreate;
this.maxChildrenPerNode = maxChildrenPerNode;
this.minChildrenPerNode = minChildrenPerNode;
this.mandatoryOdds = mandatoryOdds;
this.optionalOdds = optionalOdds;
this.group1NOdds = group1NOdds;
this.group11Odds = group11Odds;
this.maxGroupCardinality = maxGroupCardinality;
this.balanceFactor = balanceFactor;
}
protected FeatureTreeNode createNodes() throws FeatureModelException {
int countFeatures = 1;
Vector<FeatureTreeNode> fmNodes = new Vector<FeatureTreeNode>();
String featureName = "R";
countFeatures++;
RootNode root = new RootNode( featureName, featureName, TreeNodeRendererFactory.createRootRenderer());
fmNodes.add(root);
FeatureTreeNode parentNode = null;
while ( countFeatures <= numberOfFeaturesToCreate ) {
parentNode = fmNodes.firstElement();
fmNodes.removeElement(parentNode);
int numberOfChildNodesToCreate = Math.min(numberOfFeaturesToCreate-countFeatures+1, (Math.abs(new Random().nextInt())%(maxChildrenPerNode-minChildrenPerNode+1))+minChildrenPerNode);
// root node always has the maximum allowed number of children
if ( parentNode.getParent() == null ) {
numberOfChildNodesToCreate = maxChildrenPerNode;
}
else if ( isRoot((FeatureTreeNode)parentNode.getParent()) ) {
numberOfChildNodesToCreate = maxChildrenPerNode;
}
// prevents an early end of the recursion when all nodes happen to have no children
if ( numberOfChildNodesToCreate == 0 ) {
if ( fmNodes.size() == 0 ) {
numberOfChildNodesToCreate = 1;
}
}
if ( numberOfChildNodesToCreate > 0 ) {
for( int i = 0 ; i < numberOfChildNodesToCreate && countFeatures <= numberOfFeaturesToCreate ; i++ ) {
String childFeatureName = parentNode.getID().substring(1) + (i+1);
FeatureTreeNode randomNode = createRandomNode(childFeatureName, randonlyChooseNodeTypeToCreate());
parentNode.add(randomNode);
if ( randomNode instanceof FeatureGroup ) {
FeatureGroup groupRandomNode = (FeatureGroup)randomNode;
int countGroupedNodes = groupRandomNode.getChildCount();
if ( Math.abs(new Random().nextInt()) % 100 > balanceFactor || fmNodes.size() == 0 ) {
for( int j = 0 ; j < countGroupedNodes ; j++ ) {
fmNodes.add((FeatureTreeNode)groupRandomNode.getChildAt(j));
}
}
countFeatures += (countGroupedNodes);
}
else {
if ( Math.abs(new Random().nextInt()) % 100 > balanceFactor || fmNodes.size() == 0 ) {
fmNodes.add(randomNode);
}
countFeatures++;
}
}
}
}
return root;
}
private String randonlyChooseNodeTypeToCreate() {
int randomIndex = Math.abs(new Random().nextInt()) % (mandatoryOdds+optionalOdds+group1NOdds+group11Odds);
if ( randomIndex < mandatoryOdds ) {
return "mandatory";
}
else if ( randomIndex < (mandatoryOdds+optionalOdds)) {
return "optional";
}
else if ( randomIndex < (mandatoryOdds+optionalOdds+group1NOdds)) {
return "group1N";
}
return "group11";
}
private FeatureTreeNode createRandomNode(String childFeatureName, String nodeType) {
FeatureTreeNode node = null;
String featureName = "";
// should create a solitaire feature (optional/mandatory)?
if ( nodeType.compareToIgnoreCase("optional") == 0 ) {
featureName = "o" + childFeatureName;
node = new SolitaireFeature( true, featureName, featureName, TreeNodeRendererFactory.createOptionalRenderer());
}
else if ( nodeType.compareToIgnoreCase("mandatory") == 0 ) {
featureName = "m" + childFeatureName;
node = new SolitaireFeature( false, featureName, featureName, TreeNodeRendererFactory.createOptionalRenderer());
}
// should create a feature group?
else if ( nodeType.compareToIgnoreCase("group1N") == 0 ) {
// number of grouped features
int groupSize = (Math.abs(new Random().nextInt())%(maxGroupCardinality))+1;
if (groupSize <= 1) groupSize=2;
int lower = 1;
int upper = -1;
String groupName = "_Gi_" + childFeatureName;
node = new FeatureGroup( groupName, groupName, lower,upper,TreeNodeRendererFactory.createFeatureGroupRenderer() );
// create grouped feature nodes
for( int i = 0 ; i < groupSize ; i++ ) {
featureName = "g" + childFeatureName + (i+1);
node.add( new GroupedFeature( featureName, featureName, TreeNodeRendererFactory.createGroupedRenderer() ));
}
}
else if ( nodeType.compareToIgnoreCase("group11") == 0 ) {
// number of grouped features
int groupSize = (Math.abs(new Random().nextInt())%(maxGroupCardinality))+1;
if (groupSize <= 1) groupSize=2;
int lower = 1;
int upper = 1;
String groupName = "_Ge_" + childFeatureName;
node = new FeatureGroup( groupName, groupName, lower,upper,TreeNodeRendererFactory.createFeatureGroupRenderer() );
// create grouped feature nodes
for( int i = 0 ; i < groupSize ; i++ ) {
featureName = "g" + childFeatureName + (i+1);
node.add( new GroupedFeature( featureName, featureName, TreeNodeRendererFactory.createGroupedRenderer() ));
}
}
return node;
}
// returns the number of levels for which constraints were created for
public int createExtraConstraints(int numVars, int numConstraints, int maxArity, int [][] modularityParameters) {
return RandomFeatureModel.createExtraConstraints(this, numVars, numConstraints, maxArity, modularityParameters);
}
public static int createExtraConstraints(FeatureModel fm, int numVars, int numConstraints, int maxArity, int [][] modularityParameters) {
int levelsToConsider = modularityParameters.length;
int depth = fm.depth()-1; // last level are the leaves, ie, cannot be considered as no children nodes are available
levelsToConsider = ( levelsToConsider > depth ) ? depth : levelsToConsider;
// discover levels to be worked out based on percentages passed as parameters
for( int i = 0 ; i < levelsToConsider; i++ ) {
modularityParameters[i][0] = Math.round(modularityParameters[i][0]/100f * (depth));
modularityParameters[i][1] = Math.round(modularityParameters[i][1]/100f * numVars);
}
fm.resetNodesAttachedData();
// generates constraints for each level
int countLevelsWithContraints = 0;
for( int i = levelsToConsider-1 ; i >= 0 ; i-- ) {
// at least two variables to consider level
if ( modularityParameters[i][1] >= 2 ) {
int numConstraintsLevel = Math.round((numConstraints * modularityParameters[i][1]) / numVars);
_LevelConstraintGenerator constraintGenerator = new _LevelConstraintGenerator(fm, modularityParameters[i][0], modularityParameters[i][1], numConstraintsLevel, maxArity, modularityParameters[i][2]);
List<PropositionalFormula> levelFormulas = constraintGenerator.createExtraConstraints();
countLevelsWithContraints = (levelFormulas.size() > 0) ? countLevelsWithContraints + 1 : countLevelsWithContraints;
for( PropositionalFormula formula : levelFormulas) {
fm.addConstraint(formula);
}
}
}
return countLevelsWithContraints;
}
public void saveNodes() {}
}
class _LevelConstraintGenerator {
private FeatureModel fm;
private int level;
private int numVars;
private int numConstraints;
private int maxArity;
private int percentage;
public _LevelConstraintGenerator(FeatureModel fm, int level, int numVars, int numConstraints, int maxArity, int percentage) {
this.fm = fm;
this.level = level;
this.numVars = numVars;
this.numConstraints = numConstraints;
this.maxArity = maxArity;
this.percentage = percentage;
}
public int getNumberOfVariables() {
return numVars;
}
public List<PropositionalFormula> createExtraConstraints() {
List<PropositionalFormula> formulas = new ArrayList<PropositionalFormula>();
// select clusters to add constraints based on the percentage specified
List<FeatureTreeNode> selectedClusters = selectClusters(fm.getNodesAtLevel(level), percentage);
int numClusters = selectedClusters.size();
if ( numClusters > 0 ) {
// makes number of variables/constraints proportional to each cluster size
// minimum is 2 vars/1 constraint per cluster
int clustersTotalSize = 0;
for( FeatureTreeNode cluster : selectedClusters ) {
clustersTotalSize += fm.countNodes(cluster);
}
// for each selected cluster, select features for constraints
for( FeatureTreeNode cluster : selectedClusters ) {
float percVarsConst = fm.countNodes(cluster)/(1f*clustersTotalSize);
int numVarsCluster = Math.round(percVarsConst*numVars);
int numConstraintsCluster = numVarsCluster/3; //Math.round(percVarsConst*numConstraints);
if ( numVarsCluster < 2 || numConstraintsCluster < 1) {
numVarsCluster = 2;
numConstraintsCluster = 1;
}
// System.out.println("Cluster: " + cluster.getID());
// System.out.println("********** vars: " + numVarsCluster);
// System.out.println("********** const: " + numConstraintsCluster);
formulas.addAll(createClusterConstraints(cluster, numVarsCluster, numConstraintsCluster));
}
}
return formulas;
}
private List<PropositionalFormula> createClusterConstraints(FeatureTreeNode clusterNode, int numVarsCluster, int numConstraintsCluster) {
List<PropositionalFormula> formulas = new ArrayList<PropositionalFormula>();
List<FeatureTreeNode> nodes = new ArrayList<FeatureTreeNode>();
for( int i = 0 ; i < clusterNode.getChildCount() ; i++ ) {
nodes.add((FeatureTreeNode)clusterNode.getChildAt(i));
}
// initializations
ArrayList<List<FeatureTreeNode>> pickedNodesForVariables = new ArrayList<List<FeatureTreeNode>>();
int countNodes = nodes.size();
for( int i = 0 ; i < countNodes; i++ ) {
pickedNodesForVariables.add(i, new ArrayList<FeatureTreeNode>());
}
List<FeatureTreeNode> tempNodes = new ArrayList<FeatureTreeNode>();
tempNodes.addAll(nodes);
int nodeIndex = 0;
for( int i = 0 ; i < numVarsCluster && tempNodes.size() > 0 ; i++ ) {
FeatureTreeNode node = tempNodes.get(nodeIndex);
if ( !selectVariableFeature(node, pickedNodesForVariables.get(nodeIndex)) ) {
tempNodes.remove(nodeIndex);
nodeIndex = (nodeIndex == (tempNodes.size())) ? 0 : nodeIndex;
}
else {
nodeIndex = (++nodeIndex % tempNodes.size());
}
}
// Remove subtrees that have no variables selected for them (eg. when numVars is very small some subtrees may never get any features picked)
int indexToRemove = 0;
for( int i = 0 ; i < countNodes ; i++ ) {
List<FeatureTreeNode> pickedFeatures = pickedNodesForVariables.get(indexToRemove);
if ( pickedFeatures.size() == 0 ) {
pickedNodesForVariables.remove(indexToRemove);
nodes.remove(indexToRemove);
}
else {
indexToRemove++;
}
}
countNodes = nodes.size();
// // remove 34% of the nodes if the number of nodes is larger than 2
// if ( countNodes > 2 ) {
// countNodes = Math.round(0.60f * countNodes);
// }
if ( countNodes > 0 ) {
// create indexes to track down variables selected for each subtree
int varsIndex[] = new int[countNodes];
for( int i = 0 ; i < countNodes ; i++ ) {
varsIndex[i] = 0;
}
// generate constraints
Collections.shuffle(pickedNodesForVariables);
nodeIndex = 0;
for( int i = 0 ; i < numConstraintsCluster ; i++ ) {
List<FeatureTreeNode> variables = new ArrayList<FeatureTreeNode>();
int arity = 2; // + Math.abs(new Random().nextInt())%(maxArity-1);
for( int j = 0 ; j < arity ; j++ ) {
List<FeatureTreeNode> variablesForNode = pickedNodesForVariables.get(nodeIndex);
variables.add(variablesForNode.get(varsIndex[nodeIndex]));
varsIndex[nodeIndex] = (++varsIndex[nodeIndex])%pickedNodesForVariables.get(nodeIndex).size();
if ( varsIndex[nodeIndex] == 0) {
Collections.shuffle(pickedNodesForVariables.get(nodeIndex));
}
// nodeIndex = (Math.abs(new Random().nextInt())%countNodes);
// nodeIndex = (++nodeIndex)%countNodes;
if ( Math.abs(new Random().nextInt())%2 == 0 ) {
nodeIndex = (Math.abs(new Random().nextInt())%countNodes);
}
else if ( (++nodeIndex) == countNodes ) {
nodeIndex = 0;
}
}
String formulaStr = "";
for( Iterator<FeatureTreeNode> it = variables.iterator() ; it.hasNext() ; ) {
formulaStr += it.next().getID();
if ( it.hasNext() ) {
formulaStr += " OR ";
}
}
try {
formulas.add( new PropositionalFormula("C_"+(level+1)+"_"+clusterNode.getID()+"_"+i,formulaStr) );
}
catch( Exception e ) {
System.out.println("Error: " + formulaStr);
// e.printStackTrace();
}
}
}
return formulas;
}
// returns true if a node was found and false if no node is available, ie, they have all been previously picked
private boolean selectVariableFeature(FeatureTreeNode subtreeRootNode, List<FeatureTreeNode> pickedNodesForVariables) {
List<FeatureTreeNode> subtreeNodes = new ArrayList<FeatureTreeNode>();
fm.getSubtreeNodes(subtreeRootNode, subtreeNodes);
if( !(subtreeRootNode instanceof FeatureGroup) ) {
subtreeNodes.add(subtreeRootNode);
}
// remove nodes that have been already picked
for( Iterator<FeatureTreeNode> it = subtreeNodes.iterator() ; it.hasNext() ; ) {
FeatureTreeNode node = it.next();
if ( !(node instanceof FeatureGroup ) ) {
Integer isSelected = (Integer)node.getAttachedData();
if ( (isSelected != null && isSelected.intValue() == 1) || pickedNodesForVariables.contains(node)) {
it.remove();
}
}
}
int countNodes = subtreeNodes.size();
if ( countNodes > 0 ) {
FeatureTreeNode nodeSelected = subtreeNodes.get(Math.abs(new Random().nextInt())%countNodes);
nodeSelected.attachData(new Integer(1));
pickedNodesForVariables.add(nodeSelected);
return true;
}
return false;
}
// to be selected as a cluster a subtree must have:
// - at least two subtreess
// - each subtree must have at least
public List<FeatureTreeNode> selectClusters(List<FeatureTreeNode> nodes, int percentage) {
int totalCandidateClusters = nodes.size();
// ELIMINATION PHASE 1: Eliminate subtrees that do not qualify as clusters
// find cluster candidate based on the number of subtrees (minimum 2) and features availability (minimum 1 per subtree)
for( Iterator<FeatureTreeNode> it = nodes.iterator() ; it.hasNext() ; ) {
FeatureTreeNode node = it.next();
// at least two subtrees are necessary for a cluster to qualify
boolean qualifies = false;
if ( node.getChildCount() >= 2 ) {
int countCandidateSubTrees = 0;
for( int i = 0 ; i < node.getChildCount() ; i++ ) {
FeatureTreeNode childNode = (FeatureTreeNode)node.getChildAt(i);
// each subtree must have at least one available feature
if ( countAvailableFeatures(childNode, !(node instanceof GroupedFeature)) >= 1 ) {
countCandidateSubTrees++;
}
}
qualifies = (countCandidateSubTrees >= 2);
}
if ( !qualifies ) {
it.remove();
}
}
// Shuffle candidate clusters for fairness
java.util.Collections.shuffle(nodes);
// ELIMINATION PHASE 2: Eliminate nodes based on specified percentage parameter
int nodesToEliminate = Math.min(nodes.size(), Math.round((1-(percentage/100f))*totalCandidateClusters));
for( int i = 0 ; i < nodesToEliminate ; i++ ) {
nodes.remove(Math.abs(new Random().nextInt())%nodes.size());
}
// ELIMINATION PHASE 3: When number of clusters is larger in comparison to the number of variables for the cluster,
// Eliminate clusters so that each remaining cluster has at least two variables
float numClusters = nodes.size();
if ( (2*numClusters) > numVars) {
int clustersToRemove = Math.round(numClusters-(numVars/2f));
for( int i = 0 ; i < clustersToRemove ; i++ ) {
nodes.remove(Math.round(Math.abs(new Random().nextInt())%nodes.size()));
}
}
return nodes;
}
private int countAvailableFeatures(FeatureTreeNode node, boolean includesNodeItSelf) {
List<FeatureTreeNode> nodes = new ArrayList<FeatureTreeNode>();
fm.getSubtreeNodes(node, nodes);
if ( includesNodeItSelf ) {
nodes.add(node);
}
int countFeatures = 0;
for( FeatureTreeNode descendantNode : nodes ) {
if ( !(descendantNode instanceof FeatureGroup ) && descendantNode.getAttachedData() == null ) {
countFeatures++;
}
}
return countFeatures;
}
// Select Subtrees based on the percentage indicated
// public List<FeatureTreeNode> selectSubtrees(List<FeatureTreeNode> nodes, int percentage, int minChildren) {
//
// if ( nodes.size() == 1 ) {
// return nodes;
// }
//
// java.util.Collections.shuffle(nodes);
//
// /*********************************/
// int countNodes = nodes.size();
// int nodesToEliminate = Math.round((1-(percentage/100f))*countNodes);
//
//// System.out.println("Subtrees picked: " + (countNodes-nodesToEliminate));
//
// // at least two nodes must be left
//// nodesToEliminate = (nodes.size()-nodesToEliminate)<=1 ? (countNodes-2) : nodesToEliminate;
// for( int i = 0 ; i < nodesToEliminate ; i++ ) {
// nodes.remove(Math.abs(new Random().nextInt())%nodes.size());
// }
///*********************************/
// // remove nodes with less than 2 features
// for( Iterator<FeatureTreeNode> it = nodes.iterator() ; it.hasNext() ; ) {
// FeatureTreeNode node = it.next();
// int minChildrenAllowed = minChildren;
// if ( node instanceof FeatureGroup ) {
// minChildrenAllowed += node.getChildCount();
// }
//// System.out.println("Subtree size: " + fm.countNodes(node));
// if ( (fm.countNodes(node) <= minChildrenAllowed) || ( node instanceof FeatureGroup )) {
// it.remove();
// }
// }
//
// // select nodes based on the specified percentage
//
// return nodes;
// }
}
/*
* Produce constraints for a particular level of the Feature Tree by linking the subtrees in the level through particular selected features
*/
//class _LevelConstraintGenerator {
//
// private FeatureModel fm;
// private int level;
// private int numVars;
// private int numConstraints;
// private int maxArity;
// private int percentage;
//
// public _LevelConstraintGenerator(FeatureModel fm, int level, int numVars, int numConstraints, int maxArity, int percentage) {
// this.fm = fm;
// this.level = level;
// this.numVars = numVars;
// this.numConstraints = numConstraints;
// this.maxArity = maxArity;
// this.percentage = percentage;
// }
//
// public int getNumberOfVariables() {
// return numVars;
// }
//
// public List<PropositionalFormula> createExtraConstraints() {
//
// List<PropositionalFormula> formulas = new ArrayList<PropositionalFormula>();
//
// // select subtrees to add constraints based on the percentage specified
// List<FeatureTreeNode> selectedClusters = selectSubtrees();
//
// // at least two subtrees have been selected?
// int countSubTrees = selectedClusters.size();
// if ( countSubTrees > 1 ) {
// // select variables and mark them so that they wont be used at other levels
// ArrayList<List<FeatureTreeNode>> pickedNodesForVariables = new ArrayList<List<FeatureTreeNode>>();
// for( int i = 0 ; i < countSubTrees; i++ ) {
// pickedNodesForVariables.add(i, new ArrayList<FeatureTreeNode>());
// }
// int subtreeIndex = 0;
// int countNotPickedVariables = 0;
// for( int i = 0 ; i < numVars ; i++ ) {
// FeatureTreeNode subtreeRootNode = selectedClusters.get(subtreeIndex);
// if ( !selectVariableFeature(subtreeRootNode, pickedNodesForVariables.get(subtreeIndex)) ) {
// countNotPickedVariables++;
// }
// subtreeIndex = (++subtreeIndex % countSubTrees);
// }
//
// // update number of variables actually used
// numVars -= countNotPickedVariables;
//
// // Remove subtrees that have no variables selected for them (eg. when numVars is very small some subtrees may never get any features picked)
// int indexToRemove = 0;
// for( int i = 0 ; i < countSubTrees ; i++ ) {
// List<FeatureTreeNode> pickedFeatures = pickedNodesForVariables.get(indexToRemove);
// if ( pickedFeatures.size() == 0 ) {
// pickedNodesForVariables.remove(indexToRemove);
// selectedClusters.remove(indexToRemove);
//// System.out.println("Removed! + " + indexToRemove);
// }
// else {
// indexToRemove++;
// }
// }
//
// // DEBUG
// for( int i = 0 ; i < selectedClusters.size() ; i++ ) {
//
// System.out.print("\n" + selectedClusters.get(i).getID() + ": ");
// List<FeatureTreeNode> list = pickedNodesForVariables.get(i);
// for( FeatureTreeNode node : list ) {
// System.out.print(node.getID() + ",");
// }
// System.out.print("\n");
// }
//
// // create indexes to track down variables selected for each subtree
// int varsIndex[] = new int[countSubTrees];
// for( int i = 0 ; i < countSubTrees ; i++ ) {
// varsIndex[i] = 0;
// }
//
// // generate constraints
// subtreeIndex = 0;
// for( int i = 0 ; i < numConstraints ; i++ ) {
// List<FeatureTreeNode> variables = new ArrayList<FeatureTreeNode>();
// for( int j = 0 ; j < maxArity ; j++ ) {
// variables.add(pickedNodesForVariables.get(subtreeIndex).get(varsIndex[subtreeIndex]));
// varsIndex[subtreeIndex] = (++varsIndex[subtreeIndex])%pickedNodesForVariables.get(subtreeIndex).size();
// if ( varsIndex[subtreeIndex] == 0) {
// Collections.shuffle(pickedNodesForVariables.get(subtreeIndex));
// }
// subtreeIndex = (++subtreeIndex)%countSubTrees;
// }
//
// String formulaStr = "";
// for( Iterator<FeatureTreeNode> it = variables.iterator() ; it.hasNext() ; ) {
// formulaStr += it.next().getID();
// if ( it.hasNext() ) {
// formulaStr += " OR ";
// }
// }
// try {
// formulas.add( new PropositionalFormula("C_"+level+"_"+i,formulaStr) );
// }
// catch( Exception e ) {
// e.printStackTrace();
// }
//
// }
// }
//
// return formulas;
// }
//
// // returns true if a node was found and false if no node is available, ie, they have all been previously picked
// private boolean selectVariableFeature(FeatureTreeNode subtreeRootNode, List<FeatureTreeNode> pickedNodesForVariables) {
//
// List<FeatureTreeNode> subtreeNodes = new ArrayList<FeatureTreeNode>();
// fm.getSubtreeNodes(subtreeRootNode, subtreeNodes);
//
// // remove nodes that have been already picked
// for( Iterator<FeatureTreeNode> it = subtreeNodes.iterator() ; it.hasNext() ; ) {
// FeatureTreeNode node = it.next();
// Integer isSelected = (Integer)node.getAttachedData();
// if ( (isSelected != null && isSelected.intValue() == 1) || pickedNodesForVariables.contains(node)) {
// it.remove();
// }
// }
//
// int countNodes = subtreeNodes.size();
// if ( countNodes > 0 ) {
// FeatureTreeNode nodeSelected = subtreeNodes.get(Math.abs(new Random().nextInt())%countNodes);
// nodeSelected.attachData(new Integer(1));
// pickedNodesForVariables.add(nodeSelected);
// return true;
// }
//
// return false;
// }
//
// // Select Subtrees at level "level" based on the percentage indicated
// public List<FeatureTreeNode> selectSubtrees() {
//
// // candidate nodes
// List<FeatureTreeNode> nodes = fm.getNodesAtLevel(level);
//
// // remove nodes without children
// for( Iterator<FeatureTreeNode> it = nodes.iterator() ; it.hasNext() ; ) {
// FeatureTreeNode node = it.next();
//// System.out.println("Subtree size: " + fm.countNodes(node));
// if ( fm.countNodes(node) <= 1 ) {
// it.remove();
// }
// }
//
// // select nodes based on the specified percentage
// int countNodes = nodes.size();
// int nodesToEliminate = Math.round((1-(percentage/100f))*countNodes);
//
//// System.out.println("Subtrees picked: " + (countNodes-nodesToEliminate));
//
// // at least two nodes must be left
//// nodesToEliminate = (nodes.size()-nodesToEliminate)<=1 ? (countNodes-2) : nodesToEliminate;
// for( int i = 0 ; i < nodesToEliminate ; i++ ) {
// nodes.remove(Math.abs(new Random().nextInt())%nodes.size());
// }
//
// return nodes;
// }
//}
//
//
//
//
//
| {
"content_hash": "19c8c165c679c528513c7a818da9c7ec",
"timestamp": "",
"source": "github",
"line_count": 696,
"max_line_length": 233,
"avg_line_length": 37.39367816091954,
"alnum_prop": 0.6817797587028356,
"repo_name": "anderson-uchoa/DyMMer",
"id": "2b2abe07b7aed1b75f7496f5bb3781803e72cda8",
"size": "26026",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "src/br/ufc/lps/splar/core/fm/randomization/RandomFeatureModel.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1091"
},
{
"name": "HTML",
"bytes": "205432"
},
{
"name": "Java",
"bytes": "939830"
},
{
"name": "JavaScript",
"bytes": "220782"
}
],
"symlink_target": ""
} |
SenchaTilt
==========
A Sencha Touch implementation of John Tregoning's JavaScript version of the new Facebook Paper tilt functionality
| {
"content_hash": "4d3a6eaa02081801dce8ca5c2a2b86b5",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 113,
"avg_line_length": 34.25,
"alnum_prop": 0.781021897810219,
"repo_name": "joshuamorony/SenchaTilt",
"id": "22e2c486018803e01c2f4f63a615cf413c516a6a",
"size": "137",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3673837"
},
{
"name": "JavaScript",
"bytes": "10280100"
},
{
"name": "Ruby",
"bytes": "2164"
}
],
"symlink_target": ""
} |
var mongoose = require('mongoose');
var utils = require('utility');
var config = require('../config');
var Schema = mongoose.Schema;
var _getArticle = function () {
var articleSchema = new Schema({
title: {type: String, required: true}, // 标题
url: {type: String}, // 相关链接
summary: {type: String}, // 摘要
up: {type: Boolean, default: false}, // 置顶
source: {type: String}, // 文章来源
views: {type: Number, default: 0}, // 阅读数
zan: {type: Number, default: 0}, // 点赞数
tags: {type: Array, default: []}, // 文章标签
favorite_count: {type: Number, default: 0}, // 收藏数量
_user: {
type: Schema.Types.ObjectId,
ref: 'User'
},
status: {type: Boolean, default: false} // 文章是否发布
}, {
timestamps: {
createdAt: 'created_at',
updatedAt: 'updated_at'
}
});
return mongoose.model('Article', articleSchema);
};
module.exports = _getArticle(); | {
"content_hash": "65ff52fe67781570421e92b7b7f7ed97",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 63,
"avg_line_length": 32.696969696969695,
"alnum_prop": 0.4976830398517145,
"repo_name": "gefangshuai/wincndotnet",
"id": "891aebc42f2a05b1f576c2ddeb7a5bb8643ec6ee",
"size": "1147",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "model/article.model.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "350548"
},
{
"name": "JavaScript",
"bytes": "140210"
},
{
"name": "Shell",
"bytes": "96"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `LLVMAddPruneEHPass` fn in crate `rustc_llvm`.">
<meta name="keywords" content="rust, rustlang, rust-lang, LLVMAddPruneEHPass">
<title>rustc_llvm::LLVMAddPruneEHPass - Rust</title>
<link rel="stylesheet" type="text/css" href="../main.css">
<link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<section class="sidebar">
<a href='../rustc_llvm/index.html'><img src='http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='' width='100'></a>
<p class='location'><a href='index.html'>rustc_llvm</a></p><script>window.sidebarCurrent = {name: 'LLVMAddPruneEHPass', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</section>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press 'S' to search, '?' for more options..."
type="search">
</div>
</form>
</nav>
<section id='main' class="content fn">
<h1 class='fqn'><span class='in-band'><a href='index.html'>rustc_llvm</a>::<wbr><a class='fn' href=''>LLVMAddPruneEHPass</a><wbr><a class='stability Unstable' title=''>Unstable</a></span><span class='out-of-band'><span id='render-detail'>
<a id="collapse-all" href="#">[-]</a> <a id="expand-all" href="#">[+]</a>
</span><a id='src-7816' href='../src/rustc_llvm/lib.rs.html#1637'>[src]</a></span></h1>
<pre class='rust fn'>pub unsafe fn LLVMAddPruneEHPass(PM: <a class='type' href='../rustc_llvm/type.PassManagerRef.html' title='rustc_llvm::PassManagerRef'>PassManagerRef</a>)</pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<div id="help" class="hidden">
<div class="shortcuts">
<h1>Keyboard shortcuts</h1>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h1>Search tricks</h1>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>typedef</code> (or
<code>tdef</code>).
</p>
</div>
</div>
<script>
window.rootPath = "../";
window.currentCrate = "rustc_llvm";
window.playgroundUrl = "";
</script>
<script src="../jquery.js"></script>
<script src="../main.js"></script>
<script async src="../search-index.js"></script>
</body>
</html> | {
"content_hash": "2327d14e3a7b345f24ccf38db183628a",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 238,
"avg_line_length": 39.11578947368421,
"alnum_prop": 0.5479009687836384,
"repo_name": "ArcherSys/ArcherSys",
"id": "67bd7db69434ff2dbfb69da11b5b57c923322f5c",
"size": "3716",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Rust/share/doc/rust/html/rustc_llvm/fn.LLVMAddPruneEHPass.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
@echo off
mkdir Temp
set TMP=Temp
set TEMP=Temp
rem set IAREXE=..\..\..\..\..\common\bin\iarbuild.exe
set IAREXE=iarbuild.exe
echo.
echo Building DSP Libraries ARM
echo Building DSP Library for Cortex-M0 Little Endian
%IAREXE% arm_cortexM_math.ewp -build cortexM0l
echo Building DSP Library for Cortex-M3 Little Endian
%IAREXE% arm_cortexM_math.ewp -build cortexM3l
echo Building DSP Library for Cortex-M4 Little Endian
%IAREXE% arm_cortexM_math.ewp -build cortexM4l
echo Building DSP Library for Cortex-M4 Little Endian with single precision FPU
%IAREXE% arm_cortexM_math.ewp -build cortexM4lf
echo Building DSP Library for Cortex-M7 Little Endian
%IAREXE% arm_cortexM_math.ewp -build cortexM7l
echo Building DSP Library for Cortex-M7 Little Endian with single precision FPU
%IAREXE% arm_cortexM_math.ewp -build cortexM7lfsp
echo Building DSP Library for Cortex-M7 Little Endian with double precision FPU
%IAREXE% arm_cortexM_math.ewp -build cortexM7lfdp
echo Building DSP Library for ARMv8-M Baseline Little Endian
%IAREXE% arm_cortexM_math.ewp -build ARMv8MBLl
echo Building DSP Library for ARMv8-M Mainline Little Endian
%IAREXE% arm_cortexM_math.ewp -build ARMv8MMLl
echo Building DSP Library for ARMv8-M Mainline Little Endian with single precision FPU
%IAREXE% arm_cortexM_math.ewp -build ARMv8MMLlfsp
echo Building DSP Library for ARMv8-M Mainline Little Endian with double precision FPU
%IAREXE% arm_cortexM_math.ewp -build ARMv8MMLlfdp
echo Building DSP Library for ARMv8-M Mainline Little Endian with DSP instructions
%IAREXE% arm_cortexM_math.ewp -build ARMv8MMLld
echo Building DSP Library for ARMv8-M Mainline Little Endian with DSP instructions, single precision FPU
%IAREXE% arm_cortexM_math.ewp -build ARMv8MMLldfsp
echo Building DSP Library for ARMv8-M Mainline Little Endian with DSP instructions, double precision FPU
%IAREXE% arm_cortexM_math.ewp -build ARMv8MMLldfdp
REM big endian libraries
echo Building DSP Library for Cortex-M0 Big Endian
%IAREXE% arm_cortexM_math.ewp -build cortexM0b
echo Building DSP Library for Cortex-M3 Big Endian
%IAREXE% arm_cortexM_math.ewp -build cortexM3b
echo Building DSP Library for Cortex-M4 Big Endian
%IAREXE% arm_cortexM_math.ewp -build cortexM4b
echo Building DSP Library for Cortex-M4 Big Endian with single precision FPU
%IAREXE% arm_cortexM_math.ewp -build cortexM4bf
echo Building DSP Library for Cortex-M7 Big Endian
%IAREXE% arm_cortexM_math.ewp -build cortexM7b
echo Building DSP Library for Cortex-M7 Big Endian with single precision FPU
%IAREXE% arm_cortexM_math.ewp -build cortexM7bfsp
echo Building DSP Library for Cortex-M7 Big Endian with double precision FPU
%IAREXE% arm_cortexM_math.ewp -build cortexM7bfdp
echo Copy libs to CMSIS\lib\IAR
mkdir ..\..\..\lib\IAR
copy ReleaseM0BE\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ReleaseM0LE\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ReleaseM3BE\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ReleaseM3LE\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ReleaseM4BE\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ReleaseM4BE_FPU\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ReleaseM4LE\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ReleaseM4LE_FPU\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ReleaseM7BE\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ReleaseM7BE_FPU_DP\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ReleaseM7BE_FPU_SP\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ReleaseM7LE\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ReleaseM7LE_FPU_DP\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ReleaseM7LE_FPU_SP\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ARMv8MBLl\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ARMv8MMLl\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ARMv8MMLld\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ARMv8MMLldfdp\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ARMv8MMLldfsp\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ARMv8MMLlfdp\Exe\*.a ..\..\..\lib\IAR\ /Y
copy ARMv8MMLlfsp\Exe\*.a ..\..\..\lib\IAR\ /Y
echo.
echo Deleting intermediate files
for /d %%a in (Temp ARMv8M* ReleaseM*) do rmdir /s /q "%%~a"
del /Q *.bak
del /Q *.dep
| {
"content_hash": "94df3cb0fb36417fa558d0c89ee08100",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 106,
"avg_line_length": 38.86538461538461,
"alnum_prop": 0.710786739238001,
"repo_name": "ryankurte/stm32f4-base",
"id": "63b24b643c8569bb73d9e6869e5e0d85ca2c913e",
"size": "4042",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "drivers/CMSIS/DSP/Projects/IAR/arm_cortexM_math_Build.bat",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "3602768"
},
{
"name": "Batchfile",
"bytes": "11662"
},
{
"name": "C",
"bytes": "81530519"
},
{
"name": "C++",
"bytes": "709211"
},
{
"name": "CMake",
"bytes": "23561"
},
{
"name": "CSS",
"bytes": "7390"
},
{
"name": "HTML",
"bytes": "2865790"
},
{
"name": "Makefile",
"bytes": "27107"
},
{
"name": "Objective-C",
"bytes": "20595"
},
{
"name": "Perl",
"bytes": "17688"
},
{
"name": "Shell",
"bytes": "12212"
},
{
"name": "Tcl",
"bytes": "72"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System.Windows.Input;
using MvvmCross.Commands;
using MvvmCross.Navigation;
using MvvmCross.Plugin.Messenger;
using Nethereum.UI.Core.Model;
using Nethereum.UI.Core.Services;
using Xamarin.Forms;
namespace Nethereum.UI.Core.ViewModels
{
public class MenuViewModel : BaseViewModel
{
private readonly IHomeMenuService homeMenuService;
private readonly IMvxNavigationService navigationService;
private List<ShellMenuItem> menuItems;
private readonly IMvxMessenger messenger;
private ShellMenuItem selectedMenuItem;
public MenuViewModel(IHomeMenuService homeMenuService, IMvxNavigationService navigationService)
{
//this.messenger = messenger;
this.homeMenuService = homeMenuService;
this.navigationService = navigationService;
}
public List<ShellMenuItem> MenuItems
{
get { return menuItems; }
set
{
menuItems = value;
RaisePropertyChanged(() => MenuItems);
}
}
public ShellMenuItem SelectedMenuItem
{
get { return selectedMenuItem; }
set
{
if (selectedMenuItem != value)
{
selectedMenuItem = value;
RaisePropertyChanged(() => SelectedMenuItem);
NavigateToSelectedMenuCommand.Execute(null);
}
}
}
public ICommand NavigateToSelectedMenuCommand
{
get
{
return new MvxAsyncCommand(async () =>
{
var vmType = SelectedMenuItem.PageViewModelType;
await navigationService.Navigate(vmType);
},
() => SelectedMenuItem != null);
}
}
public override void Start()
{
base.Start();
Title = "Nethereum Wallet";
Icon = "slideout.png";
MenuItems = homeMenuService.GetMenuItems();
SelectedMenuItem = MenuItems[0];
}
}
} | {
"content_hash": "2f04cb503bfb3e6207d3311db49b0a4f",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 103,
"avg_line_length": 27.8375,
"alnum_prop": 0.5550067355186349,
"repo_name": "Nethereum/Nethereum.UI.Wallet.Sample",
"id": "1083454af9ddd00ef45684e93b5167bf82b8a06d",
"size": "2229",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Nethereum.UI/Nethereum.UI.Core/ViewModels/MenuViewModel.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "104713"
}
],
"symlink_target": ""
} |
'use strict';
angular.module('app').controller("ConfigController", function($scope, $http, remotes) {
$scope.state=0;
$scope.user = remotes.get().success(function (data) {
$scope.remotes = (typeof data==="string")?[]:data;
$scope.state = 1;
// loop through the remotes and add each
// remote to the page scope.
for (remote in $scope.remotes) {
switch (remote.type) {
case 'github.com':
$scope.github = remote;
break;
case 'enterprise.github.com':
$scope.githubEnterprise = remote;
break;
case 'gitlab.com':
$scope.gitlab = remote;
break;
case 'bitbucket.org':
$scope.bitbucket = remote;
break;
case 'stash.atlassian.com':
$scope.stash = remote;
break;
}
}
})
.error(function (error) {
$scope.remotes = [];
$scope.state = 1;
});
});
| {
"content_hash": "3f0687b422e2989e00d62d9c797280f4",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 87,
"avg_line_length": 21.225,
"alnum_prop": 0.5959952885747939,
"repo_name": "NextThingCo/drone",
"id": "6e42b7f8979d6a75273775fce492744dde2e90ad",
"size": "849",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "server/app/scripts/controllers/conf.js",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
module Krikri::Enrichments
##
# Enrichment to capitalize sentences in a text field
#
# StripHtml.new.enrich_value('<html>Moomin <i><b>Valley</i></b>')
# => 'Moomin Valley'
#
class StripHtml
include Audumbla::FieldEnrichment
def enrich_value(value)
return value unless value.is_a? String
ActionView::Base.full_sanitizer.sanitize(value)
end
end
end
| {
"content_hash": "0ad4243cb61f519302bb369bc4ce8c73",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 69,
"avg_line_length": 24.5,
"alnum_prop": 0.673469387755102,
"repo_name": "dpla/KriKri",
"id": "897d00692dde3fb86a5b9fb4e203f8ac1b645a64",
"size": "392",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "lib/krikri/enrichments/strip_html.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "882"
},
{
"name": "HTML",
"bytes": "14771"
},
{
"name": "JavaScript",
"bytes": "599"
},
{
"name": "Ruby",
"bytes": "576868"
},
{
"name": "Shell",
"bytes": "1577"
}
],
"symlink_target": ""
} |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE CPP #-}
module Laborantin.CLI (defaultMain) where
import Control.Exception (finally)
import Options.Applicative
import Data.Time
#if !(MIN_VERSION_time(1,5,0))
import System.Locale
#endif
import System.Exit (exitFailure)
import System.Directory (doesFileExist)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Map as M
import Data.Either (rights)
import Data.Maybe (catMaybes)
import Control.Concurrent (readChan, writeChan, Chan (..), newChan)
import Control.Concurrent.Async (async)
import Control.Monad (replicateM_, forM_, void, (<=<))
import Data.Monoid
import Data.Aeson (encode)
import Data.List (intercalate)
import qualified Data.ByteString.Lazy.Char8 as C
import Laborantin.Types (UExpr (..), TExpr (..), ScenarioDescription (..), Execution (..), ParameterDescription (..), expandValue, paramSets, ResultDescription (..), FlowDirection (..), Dependency (..))
import Laborantin.Implementation (EnvIO, runEnvIO, defaultBackend, executionResultPath)
import Laborantin (load, remove, runAnalyze, prepare)
import Laborantin.Query.Interpret (toTExpr)
import Laborantin.Query.Parse (parseUExpr, ParsePrefs (..))
import Laborantin.Query (simplifyOneBoolLevel)
data Run = Run
{ runScenarios :: [String]
, runParams :: [String]
, runMatchers :: [String]
, runConcurrency :: Int
} deriving (Show)
data Continue = Continue
{ continueScenarios :: [String]
, continueParams :: [String]
, continueMatchers :: [String]
, continueFailed :: Bool
, continueTodayOnly :: Bool
, continueConcurrency :: Int
} deriving (Show)
data Describe = Describe
{ describeScenarios :: [String]
} deriving (Show)
data Find = Find
{ findScenarios :: [String]
, findParams :: [String]
, findMatchers :: [String]
, findFailed :: Bool
, findTodayOnly :: Bool
} deriving (Show)
data Results = Results
{ resultsScenarios :: [String]
, resultsNames :: [String]
, resultsParams :: [String]
, resultsMatchers :: [String]
, resultsFailed :: Bool
, resultsTodayOnly :: Bool
} deriving (Show)
data Analyze = Analyze
{ analyzeScenarios :: [String]
, analyzeParams :: [String]
, analyzeMatchers :: [String]
, analyzeFailed :: Bool
, analyzeTodayOnly :: Bool
, analyzeConcurrency :: Int
} deriving (Show)
data Rm = Rm
{ rmScenarios :: [String]
, rmParams :: [String]
, rmMatchers :: [String]
, rmFailed :: Bool
, rmTodayOnly :: Bool
} deriving (Show)
data Params = Params
{ paramsScenarios :: [String]
, paramsParams :: [String]
, paramsMatchers :: [String]
} deriving (Show)
data Query = Query
{ queryScenarios :: [String]
, queryParams :: [String]
, queryMatchers :: [String]
, queryFailed :: Bool
, queryTodayOnly :: Bool
} deriving (Show)
data Command = RunCommand Run
| ContinueCommand Continue
| DescribeCommand Describe
| AnalyzeCommand Analyze
| FindCommand Find
| ResultsCommand Results
| RmCommand Rm
| ParamsCommand Params
| QueryCommand Query
deriving (Show)
scenariosOpt scii = many $ strOption (
long "scenario"
<> short 's'
<> metavar "SCENARIOS"
<> help "Names of the scenarios to run."
<> completeWith scii)
paramsOpt = many $ strOption (
long "param"
<> short 'p'
<> metavar "PARAMS"
<> help "name:type:value tuple for parameter.")
resultNamesOpt = many $ strOption (
long "result-names"
<> short 'r'
<> metavar "RESULTS"
<> help "name of the result(s) to show")
matchersOpt = many $ strOption (
long "matcher"
<> short 'm'
<> metavar "MATCHERS"
<> help "Matcher queries to specify the parameter space.")
concurrencyLeveLOpt = option auto (
long "concurrency"
<> short 'C'
<> value 1
<> help "Max concurrent runs.")
failedFlag = switch (
long "failed-only"
<> help "Only account for failed runs.")
todayFlag = switch (
long "today"
<> help "Only account for today's runs.")
run :: [String] -> Parser Run
run scii = Run <$> scenariosOpt scii <*> paramsOpt <*> matchersOpt <*> concurrencyLeveLOpt
continue :: [String] -> Parser Continue
continue scii = Continue <$> scenariosOpt scii <*> paramsOpt <*> matchersOpt <*> failedFlag <*> todayFlag <*> concurrencyLeveLOpt
describe :: [String] -> Parser Describe
describe scii = Describe <$> scenariosOpt scii
find :: [String] -> Parser Find
find scii = Find <$> scenariosOpt scii <*> paramsOpt <*> matchersOpt <*> failedFlag <*> todayFlag
results :: [String] -> Parser Results
results scii = Results <$> scenariosOpt scii <*> resultNamesOpt <*> paramsOpt <*> matchersOpt <*> failedFlag <*> todayFlag
analyze :: [String] -> Parser Analyze
analyze scii = Analyze <$> scenariosOpt scii <*> paramsOpt <*> matchersOpt <*> failedFlag <*> todayFlag <*> concurrencyLeveLOpt
rm :: [String] -> Parser Rm
rm scii = Rm <$> scenariosOpt scii <*> paramsOpt <*> matchersOpt <*> failedFlag <*> todayFlag
query :: [String] -> Parser Query
query scii = Query <$> scenariosOpt scii <*> paramsOpt <*> matchersOpt <*> failedFlag <*> todayFlag
params :: [String] -> Parser Params
params scii = Params <$> scenariosOpt scii <*> paramsOpt <*> matchersOpt
runOpts :: [String] -> ParserInfo Run
runOpts scii = info (helper <*> run scii)
( fullDesc
<> progDesc "Executes experiment scenarios."
<> header "runs a scenario")
continueOpts :: [String] -> ParserInfo Continue
continueOpts scii = info (helper <*> continue scii)
( fullDesc
<> progDesc "Executes missing scenarios."
<> header "continues scenarios")
describeOpts :: [String] -> ParserInfo Describe
describeOpts scii = info (helper <*> describe scii)
( fullDesc
<> progDesc "Describe scenarios in this project."
<> header "describes scenarios")
findOpts :: [String] -> ParserInfo Find
findOpts scii = info (helper <*> find scii)
( fullDesc
<> progDesc "Find scenarios executions."
<> header "finds scenarios")
resultsOpts :: [String] -> ParserInfo Results
resultsOpts scii = info (helper <*> results scii)
( fullDesc
<> progDesc "Find results from scenarios executions."
<> header "finds results")
analyzeOpts :: [String] -> ParserInfo Analyze
analyzeOpts scii = info (helper <*> analyze scii)
( fullDesc
<> progDesc "Analyze scenarios runs by replaying the 'analyze' hook."
<> header "analyzes scenarios")
rmOpts :: [String] -> ParserInfo Rm
rmOpts scii = info (helper <*> rm scii)
( fullDesc
<> progDesc "Deletes scenario runs, use carefully."
<> header "removes scenarios")
queryOpts :: [String] -> ParserInfo Query
queryOpts scii = info (helper <*> query scii)
( fullDesc
<> progDesc "Prints the query (for find-like commands) given other program args."
<> header "removes scenarios")
paramsOpts :: [String] -> ParserInfo Params
paramsOpts scii = info (helper <*> params scii)
( fullDesc
<> progDesc "Prints the params expansion (for run-like commands) given other program args."
<> header "removes scenarios")
cmd :: [String] -> Parser Command
cmd scii = subparser ( command "run" (RunCommand <$> runOpts scii)
<> command "continue" (ContinueCommand <$> continueOpts scii)
<> command "describe" (DescribeCommand <$> describeOpts scii)
<> command "find" (FindCommand <$> findOpts scii)
<> command "results" (ResultsCommand <$> resultsOpts scii)
<> command "analyze" (AnalyzeCommand <$> analyzeOpts scii)
<> command "rm" (RmCommand <$> rmOpts scii)
<> command "params" (ParamsCommand <$> paramsOpts scii)
<> command "query" (QueryCommand <$> queryOpts scii))
mainCmd :: [String] -> ParserInfo Command
mainCmd scii = info (helper <*> cmd scii)
( fullDesc
<> progDesc "Use subcommands to work with your Laborantin experiments."
<> header "default Laborantin main script")
defaultMain :: [ScenarioDescription EnvIO] -> IO ()
defaultMain xs = do
command <- execParser $ mainCmd (map T.unpack $ map sName xs)
case command of
RunCommand y -> runMain xs y
ContinueCommand y -> continueMain xs y
DescribeCommand y -> describeMain xs y
FindCommand y -> findMain xs y
ResultsCommand y -> resultsMain xs y
AnalyzeCommand y -> analyzeMain xs y
RmCommand y -> rmMain xs y
ParamsCommand y -> paramsMain xs y
QueryCommand y -> queryMain xs y
-- double-plus non-good helper, should use a "saferead" version instead
unsafeReadText :: (Read a) => Text -> a
unsafeReadText = read . T.unpack
-- concurrency helper
concurrentmapM_ :: Int -> (a -> IO b) -> [a] -> IO ()
concurrentmapM_ n f xs = do
goChan <- newChan :: IO (Chan ())
joinChan <- newChan :: IO (Chan ())
let f' a = readChan goChan >> f a `finally` (writeChan goChan () >> writeChan joinChan ())
mapM_ (async . f') xs
replicateM_ n (writeChan goChan ())
mapM_ (\_ -> readChan joinChan) xs
-- handy types to match Laborantin Scenario executions
newtype Conjunction a = Conjunction {unConjunction :: a}
newtype Disjunction a = Disjunction {unDisjunction :: a}
type QueryExpr = TExpr Bool
instance Monoid (Conjunction QueryExpr) where
mempty = Conjunction (B True)
mappend (Conjunction x) (Conjunction y) = Conjunction (And x y)
instance Monoid (Disjunction QueryExpr) where
mempty = Disjunction (B False)
mappend (Disjunction x) (Disjunction y) = Disjunction (Or x y)
allQueries :: [QueryExpr] -> QueryExpr
allQueries = unConjunction . mconcat . map Conjunction
anyQuery :: [QueryExpr] -> QueryExpr
anyQuery = unDisjunction . mconcat . map Disjunction
-- class and types to turn CLI parameters into Laborantin queries
class ToQueryExpr a where
toQuery :: ParsePrefs -> a -> QueryExpr
instance ToQueryExpr QueryExpr where
toQuery _ = id
newtype Params' = Params' {unParams :: [String]}
newtype Scenarios' = Scenarios' {unScenarios :: [String]}
newtype Matchers' = Matchers' {unMatchers :: [String]}
newtype Failed' = Failed' {unFailed :: Bool}
newtype TodayOnly' = TodayOnly' {unTodayOnly :: (Bool, UTCTime)}
instance ToQueryExpr Params' where
toQuery _ = paramsToTExpr . unParams
where paramsToTExpr :: [String] -> QueryExpr
paramsToTExpr xs =
let atoms = catMaybes (map (parseParamTExpr . T.pack) xs)
in allQueries atoms
parseParamTExpr :: Text -> Maybe QueryExpr
parseParamTExpr str =
let vals = T.splitOn ":" str in
case vals of
[k,"str",v] -> Just (Eq (SCoerce (ScParam k))
(S v))
[k,"int",v] -> Just (Eq (NCoerce (ScParam k))
(N . toRational $ unsafeReadText v))
[k,"ratio",v] -> Just (Eq (NCoerce (ScParam k))
(N $ unsafeReadText v))
[k,"float",v] -> Just (Eq (NCoerce (ScParam k))
(N $ toRational
(unsafeReadText v :: Float)))
_ -> Nothing
instance ToQueryExpr Scenarios' where
toQuery _ = scenarsToTExpr . unScenarios
where scenarsToTExpr :: [String] -> QueryExpr
scenarsToTExpr [] = B True
scenarsToTExpr scii =
let atoms = map (\name -> (Eq ScName (S $ T.pack name))) scii
in anyQuery atoms
instance ToQueryExpr Matchers' where
toQuery prefs = allQueries
. map (toTExpr (B True))
. rights
. map (parseUExpr prefs)
. unMatchers
instance ToQueryExpr Failed' where
toQuery _ = statusToTExpr . unFailed
where statusToTExpr :: Bool -> TExpr Bool
statusToTExpr True = Not (Eq ScStatus (S "success"))
statusToTExpr False = (Eq ScStatus (S "success"))
instance ToQueryExpr TodayOnly' where
toQuery _ = uncurry todayToTExpr . unTodayOnly
where todayToTExpr :: Bool -> UTCTime -> TExpr Bool
todayToTExpr True today = (Or (Eq ScTimestamp (T today))
(Gt ScTimestamp (T today)))
todayToTExpr False _ = B True
instance (ToQueryExpr a) => ToQueryExpr (Conjunction a) where
toQuery prefs (Conjunction x) = toQuery prefs x
instance (ToQueryExpr a) => ToQueryExpr (Disjunction a) where
toQuery prefs (Disjunction x) = toQuery prefs x
instance ToQueryExpr Run where
toQuery prefs args = let
wrap :: ToQueryExpr a => a -> Conjunction QueryExpr
wrap a = Conjunction $ toQuery prefs $ a
params' = wrap $ Params' $ runParams args
scenarios' = wrap $ Scenarios'$ runScenarios args
matchers' = wrap $ Matchers' $ runMatchers args
in toQuery prefs (params' <> scenarios' <> matchers')
instance ToQueryExpr (Continue, UTCTime) where
toQuery prefs (args, tst) = let
wrap :: ToQueryExpr a => a -> Conjunction QueryExpr
wrap a = Conjunction $ toQuery prefs $ a
params' = wrap $ Params' $ continueParams args
scenarios' = wrap $ Scenarios' $ continueScenarios args
matchers' = wrap $ Matchers' $ continueMatchers args
status' = wrap $ Failed' $ continueFailed args
date' = wrap $ TodayOnly' $ (continueTodayOnly args, tst)
in toQuery prefs (params' <> scenarios' <> matchers' <> status' <> date')
instance ToQueryExpr (Find, UTCTime) where
toQuery prefs (args, tst) = let
wrap :: ToQueryExpr a => a -> Conjunction QueryExpr
wrap a = Conjunction $ toQuery prefs $ a
params' = wrap $ Params' $ findParams args
scenarios' = wrap $ Scenarios' $ findScenarios args
matchers' = wrap $ Matchers' $ findMatchers args
status' = wrap $ Failed' $ findFailed args
date' = wrap $ TodayOnly' $ (findTodayOnly args, tst)
in toQuery prefs (params' <> scenarios' <> matchers' <> status' <> date')
instance ToQueryExpr (Results, UTCTime) where
toQuery prefs (args, tst) = let
wrap :: ToQueryExpr a => a -> Conjunction QueryExpr
wrap a = Conjunction $ toQuery prefs $ a
params' = wrap $ Params' $ resultsParams args
scenarios' = wrap $ Scenarios' $ resultsScenarios args
matchers' = wrap $ Matchers' $ resultsMatchers args
status' = wrap $ Failed' $ resultsFailed args
date' = wrap $ TodayOnly' $ (resultsTodayOnly args, tst)
in toQuery prefs (params' <> scenarios' <> matchers' <> status' <> date')
instance ToQueryExpr (Analyze, UTCTime) where
toQuery prefs (args, tst) = let
wrap :: ToQueryExpr a => a -> Conjunction QueryExpr
wrap a = Conjunction $ toQuery prefs $ a
params' = wrap $ Params' $ analyzeParams args
scenarios' = wrap $ Scenarios' $ analyzeScenarios args
matchers' = wrap $ Matchers' $ analyzeMatchers args
status' = wrap $ Failed' $ analyzeFailed args
date' = wrap $ TodayOnly' $ (analyzeTodayOnly args, tst)
in toQuery prefs (params' <> scenarios' <> matchers' <> status' <> date')
instance ToQueryExpr (Rm, UTCTime) where
toQuery prefs (args, tst) = let
wrap :: ToQueryExpr a => a -> Conjunction QueryExpr
wrap a = Conjunction $ toQuery prefs $ a
params' = wrap $ Params' $ rmParams args
scenarios' = wrap $ Scenarios' $ rmScenarios args
matchers' = wrap $ Matchers' $ rmMatchers args
status' = wrap $ Failed' $ rmFailed args
date' = wrap $ TodayOnly' $ (rmTodayOnly args, tst)
in toQuery prefs (params' <> scenarios' <> matchers' <> status' <> date')
instance ToQueryExpr Params where
toQuery prefs args = let
wrap :: ToQueryExpr a => a -> Conjunction QueryExpr
wrap a = Conjunction $ toQuery prefs $ a
params' = wrap $ Params' $ paramsParams args
scenarios' = wrap $ Scenarios' $ paramsScenarios args
matchers' = wrap $ Matchers' $ paramsMatchers args
in toQuery prefs (params' <> scenarios' <> matchers')
instance ToQueryExpr (Query, UTCTime) where
toQuery prefs (args, tst) = let
wrap :: ToQueryExpr a => a -> Conjunction QueryExpr
wrap a = Conjunction $ toQuery prefs $ a
params' = wrap $ Params' $ queryParams args
scenarios' = wrap $ Scenarios' $ queryScenarios args
matchers' = wrap $ Matchers' $ queryMatchers args
status' = wrap $ Failed' $ queryFailed args
date' = wrap $ TodayOnly' $ (queryTodayOnly args, tst)
in toQuery prefs (params' <> scenarios' <> matchers' <> status' <> date')
-- Extra helpers
cliScenarios :: [String] -> [ScenarioDescription m] -> [ScenarioDescription m]
cliScenarios [] scii = scii
cliScenarios names scii = [sc | sc <- scii, sName sc `elem` map T.pack names]
-- | Main program for the 'run' command.
runMain :: [ScenarioDescription EnvIO] -> Run -> IO ()
runMain scii args = do
let scenarios = cliScenarios (runScenarios args) scii
query = toQuery (ParsePrefs defaultTimeLocale) args
execs = concatMap (prepare defaultBackend query []) scenarios
concurrentmapM_ (runConcurrency args) runEnvIO execs
-- | Main program for the 'continue' command.
continueMain :: [ScenarioDescription EnvIO] -> Continue -> IO ()
continueMain scii args = do
now <- getCurrentTime
let scenarios = cliScenarios (continueScenarios args) scii
query = toQuery (ParsePrefs defaultTimeLocale) (args, now)
loadMatching = load defaultBackend scenarios query
matching <- runEnvIO loadMatching
let execs = concatMap (prepare defaultBackend query matching) scenarios
concurrentmapM_ (continueConcurrency args) runEnvIO execs
-- | Main program for the 'describe' command.
-- TODO: use the query information to expand parameter values
describeMain :: [ScenarioDescription EnvIO] -> Describe -> IO ()
describeMain scii args = do
let scenarios = cliScenarios (describeScenarios args) scii
forM_ scenarios (T.putStrLn . describeScenario)
where describeScenario :: ScenarioDescription m -> Text
describeScenario sc = T.unlines [
T.append "# Scenario: " (sName sc)
, T.append " " (sDesc sc)
, T.concat [" ", (T.pack . show . length . paramSets $ sParams sc), " parameter combinations by default"]
, "## Dependencies:"
, unlines' $ map depLine $ sDeps sc
, "## Produces:"
, unlines' $ map productLine $ sProduced sc
, "## Consumes:"
, unlines' $ map consumableLine $ sConsumed sc
, "## Parameters:"
, unlines' $ map (uncurry paramLine) $ M.toList $ sParams sc
]
unlines' :: [Text] -> Text
unlines' = T.intercalate "\n"
depLine d = T.concat [dName d, " (", dDesc d, ")"]
paramLine n p = unlines' [
T.append "### " n
, describeParameter p
]
productLine p = describeProduct p
consumableLine p = describeConsumedResult p
describeParameter :: ParameterDescription -> Text
describeParameter p = unlines' [
T.concat ["(", pName p , ")"]
, T.concat [" ", pDesc p]
, T.concat [" ", (T.pack . show . length $ concatMap expandValue $ pValues p), " values:"]
, T.pack $ unlines $ map ((" - " ++) . show) (pValues p)
]
describeProduct :: ResultDescription Produced -> Text
describeProduct (RDesc path) = T.pack path
describeConsumedResult :: ResultDescription Consumed -> Text
describeConsumedResult (RDescC (SDesc {sName=n}) path) = T.concat [T.pack path, " from ", n]
-- | Main program for the 'find' command.
findMain :: [ScenarioDescription EnvIO] -> Find -> IO ()
findMain scii args = do
now <- getCurrentTime
let scenarios = cliScenarios (findScenarios args) scii
query = toQuery (ParsePrefs defaultTimeLocale) (args, now)
loadMatching = load defaultBackend scenarios query
matching <- runEnvIO loadMatching
forM_ matching (T.putStrLn . describeExecution)
where describeExecution :: Execution m -> Text
describeExecution e = T.pack $ intercalate " " [ ePath e
, T.unpack $ sName (eScenario e)
, "(" ++ show (eStatus e) ++ ")"
, C.unpack $ encode (eParamSet e)
]
-- | Main program for the 'results' command.
resultsMain :: [ScenarioDescription EnvIO] -> Results -> IO ()
resultsMain scii args = do
now <- getCurrentTime
let scenarios = cliScenarios (resultsScenarios args) scii
resultnames = resultsNames args
query = toQuery (ParsePrefs defaultTimeLocale) (args, now)
loadMatching = load defaultBackend scenarios query
if null resultnames
then T.putStrLn "needs at least one result name" >> exitFailure
else do
matching <- runEnvIO loadMatching
forM_ matching (T.putStrLn <=< describeResults resultnames)
where describeResults :: [FilePath] -> Execution m -> IO Text
describeResults names e = do
let rPaths = map (executionResultPath e) names
validPaths <- mapM doesFileExist rPaths
return $ T.pack $ unlines $ zipWith (\x y -> showSuccess x ++ (' ':y)) validPaths rPaths
showSuccess :: Bool -> String
showSuccess True = "(ok)"
showSuccess _rue = "(KO)"
-- | Main program for the 'analyze' command.
analyzeMain :: [ScenarioDescription EnvIO] -> Analyze -> IO ()
analyzeMain scii args = do
now <- getCurrentTime
let scenarios = cliScenarios (analyzeScenarios args) scii
query = toQuery (ParsePrefs defaultTimeLocale) (args, now)
loadMatching = load defaultBackend scenarios query
matching <- runEnvIO loadMatching
let analyses = map (runAnalyze defaultBackend) matching
concurrentmapM_ (analyzeConcurrency args) runEnvIO analyses
-- | Main program for the 'rm' command.
rmMain :: [ScenarioDescription EnvIO] -> Rm -> IO ()
rmMain scii args = do
now <- getCurrentTime
let scenarios = cliScenarios (rmScenarios args) scii
query = toQuery (ParsePrefs defaultTimeLocale) (args, now)
loadMatching = load defaultBackend scenarios query
matching <- runEnvIO loadMatching
let deletions = map (remove defaultBackend) matching
forM_ deletions runEnvIO
-- | Main program for the 'params' command.
paramsMain :: [ScenarioDescription EnvIO] -> Params -> IO ()
paramsMain scii args = do
let query = toQuery (ParsePrefs defaultTimeLocale) args
print $ simplifyOneBoolLevel $ query
-- | Main program for the 'query' command.
queryMain :: [ScenarioDescription EnvIO] -> Query -> IO ()
queryMain scii args = do
now <- getCurrentTime
let query = toQuery (ParsePrefs defaultTimeLocale) (args, now)
print $ simplifyOneBoolLevel $ query
| {
"content_hash": "4b3fcedf1b6019d9a51e98f5286a9a2b",
"timestamp": "",
"source": "github",
"line_count": 608,
"max_line_length": 202,
"avg_line_length": 38.82401315789474,
"alnum_prop": 0.6321965685236178,
"repo_name": "lucasdicioccio/laborantin-hs",
"id": "c23a2bf83237718bde452fe175e1f63633843ebb",
"size": "23606",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Laborantin/CLI.hs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Haskell",
"bytes": "88725"
},
{
"name": "TeX",
"bytes": "11637"
}
],
"symlink_target": ""
} |
FROM balenalib/photon-xavier-nx-ubuntu:focal-build
ENV NODE_VERSION 12.21.0
ENV YARN_VERSION 1.22.4
RUN for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-arm64.tar.gz" \
&& echo "5748bfc5bbf7d9c1c8e79bd4f71d8f049c7fc7bc5b52e04685633319843c4f93 node-v$NODE_VERSION-linux-arm64.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-arm64.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-arm64.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@node" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Ubuntu focal \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v12.21.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {
"content_hash": "e794c37d1172337586946749a3174ad6",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 693,
"avg_line_length": 66.8780487804878,
"alnum_prop": 0.7097009482129832,
"repo_name": "nghiant2710/base-images",
"id": "661bccbba898143c0f1d6750be8e42e3251da054",
"size": "2763",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/node/photon-xavier-nx/ubuntu/focal/12.21.0/build/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "144558581"
},
{
"name": "JavaScript",
"bytes": "16316"
},
{
"name": "Shell",
"bytes": "368690"
}
],
"symlink_target": ""
} |
macro(build_header)
set(GLOB_DIR "${DIR_ROOT}/src/")
file(REMOVE ${DIR_ROOT}/src/flat.h)
file(GLOB headers RELATIVE ${GLOB_DIR} ${GLOB_DIR}/*.h)
file(WRITE ${DIR_ROOT}/src/flat.h "#ifndef FLAT_H_\n")
file(APPEND ${DIR_ROOT}/src/flat.h "#define FLAT_H_\n")
foreach(header ${headers})
file(APPEND ${DIR_ROOT}/src/flat.h "#include <flat/${header}>\n")
endforeach()
file(APPEND ${DIR_ROOT}/src/flat.h "#endif // FLAT_H_\n")
endmacro(build_header)
build_header()
| {
"content_hash": "8141a603c285f13c25b2c34bc2057b44",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 67,
"avg_line_length": 36.07692307692308,
"alnum_prop": 0.6631130063965884,
"repo_name": "LiquidityC/flat",
"id": "2e8ea9bb6faa94264d02ad999676e2834af7a718",
"size": "469",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "cmake/build_header.cmake",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "563273"
},
{
"name": "CMake",
"bytes": "30340"
},
{
"name": "Makefile",
"bytes": "290"
},
{
"name": "Vim script",
"bytes": "224"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>SystemServiceServlet</servlet-name>
<servlet-class>com.google.api.server.spi.SystemServiceServlet</servlet-class>
<init-param>
<param-name>services</param-name>
<param-value>com.google.devrel.training.conference.spi.ConferenceApi</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SystemServiceServlet</servlet-name>
<url-pattern>/_ah/spi/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SetAnnouncementServlet</servlet-name>
<servlet-class> com.google.devrel.training.conference.servlet.SetAnnouncementServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SetAnnouncementServlet</servlet-name>
<url-pattern>/crons/set_announcement</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<security-constraint>
<web-resource-collection>
<web-resource-name>all</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
<servlet>
<servlet-name>SendConfirmationEmailServlet</servlet-name>
<servlet-class>com.google.devrel.training.conference.servlet.SendConfirmationEmailServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SendConfirmationEmailServlet</servlet-name>
<url-pattern>/send_confirmation_email</url-pattern>
</servlet-mapping>
</web-app>
| {
"content_hash": "03417c0c10d2fe219e0e9bcad4d50cdc",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 286,
"avg_line_length": 41.5,
"alnum_prop": 0.6957831325301205,
"repo_name": "a77a78/Practice7",
"id": "78d60c44b8b91ee0284534371fe6ec5a2f1ed40a",
"size": "1992",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/webapp/WEB-INF/web.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2710"
},
{
"name": "HTML",
"bytes": "23880"
},
{
"name": "Java",
"bytes": "62935"
},
{
"name": "JavaScript",
"bytes": "32264"
}
],
"symlink_target": ""
} |
import { NgModule } from '@angular/core';
import { CoreMainMenuDelegate } from '@core/mainmenu/providers/delegate';
import { CoreContentLinksDelegate } from '@core/contentlinks/providers/delegate';
import { CoreTagProvider } from './providers/tag';
import { CoreTagHelperProvider } from './providers/helper';
import { CoreTagAreaDelegate } from './providers/area-delegate';
import { CoreTagMainMenuHandler } from './providers/mainmenu-handler';
import { CoreTagIndexLinkHandler } from './providers/index-link-handler';
import { CoreTagSearchLinkHandler } from './providers/search-link-handler';
@NgModule({
declarations: [
],
imports: [
],
providers: [
CoreTagProvider,
CoreTagHelperProvider,
CoreTagAreaDelegate,
CoreTagMainMenuHandler,
CoreTagIndexLinkHandler,
CoreTagSearchLinkHandler
]
})
export class CoreTagModule {
constructor(mainMenuDelegate: CoreMainMenuDelegate, mainMenuHandler: CoreTagMainMenuHandler,
contentLinksDelegate: CoreContentLinksDelegate, indexLinkHandler: CoreTagIndexLinkHandler,
searchLinkHandler: CoreTagSearchLinkHandler) {
mainMenuDelegate.registerHandler(mainMenuHandler);
contentLinksDelegate.registerHandler(indexLinkHandler);
contentLinksDelegate.registerHandler(searchLinkHandler);
}
}
| {
"content_hash": "9c6c7a7c306cf70942ffb2275ea4b8ea",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 102,
"avg_line_length": 39.73529411764706,
"alnum_prop": 0.7424130273871207,
"repo_name": "moodlehq/moodlemobile2",
"id": "07aad9c86b5c0043f9cb42b28f797267878b2492",
"size": "1948",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/core/tag/tag.module.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "215100"
},
{
"name": "Dockerfile",
"bytes": "619"
},
{
"name": "HTML",
"bytes": "698205"
},
{
"name": "Java",
"bytes": "1782"
},
{
"name": "JavaScript",
"bytes": "240820"
},
{
"name": "PHP",
"bytes": "31462"
},
{
"name": "Shell",
"bytes": "14375"
},
{
"name": "TypeScript",
"bytes": "8373893"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using Couchbase.Lite;
using Couchbase.Lite.Auth;
using Couchbase.Lite.Util;
using Sharpen;
namespace Couchbase.Lite.Auth
{
internal class FacebookAuthorizer : Authorizer
{
public const string LoginParameterAccessToken = "access_token";
public const string QueryParameter = "facebookAccessToken";
public const string QueryParameterEmail = "email";
private static IDictionary<IList<string>, string> accessTokens;
private string emailAddress;
public FacebookAuthorizer(string emailAddress)
{
this.emailAddress = emailAddress;
}
public override string UserInfo { get { return null; } }
public override string Scheme { get { return null; } }
public override bool UsesCookieBasedLogin { get { return true; } }
public override IDictionary<string, string> LoginParametersForSite(Uri site)
{
IDictionary<string, string> loginParameters = new Dictionary<string, string>();
string accessToken = AccessTokenForEmailAndSite(this.emailAddress, site);
if (accessToken != null)
{
loginParameters[LoginParameterAccessToken] = accessToken;
return loginParameters;
}
else
{
return null;
}
}
public override string LoginPathForSite(Uri site)
{
return new Uri(site.AbsolutePath + "/_facebook").AbsoluteUri;
}
public static bool RegisterAccessToken(string accessToken, string email, string
origin)
{
lock (typeof(FacebookAuthorizer))
{
IList<string> key = new List<string>();
key.AddItem(email);
key.AddItem(origin);
if (accessTokens == null)
{
accessTokens = new Dictionary<IList<string>, string>();
}
Log.D(Database.TAG, "FacebookAuthorizer registering key: " + key);
accessTokens[key] = accessToken;
return true;
}
}
public static string AccessTokenForEmailAndSite(string email, Uri site)
{
try
{
IList<string> key = new List<string>();
key.AddItem(email);
key.AddItem(site.ToString().ToLower());
Log.D(Database.TAG, "FacebookAuthorizer looking up key: " + key + " from list of access tokens");
return accessTokens.Get(key);
}
catch (Exception e)
{
Log.E(Database.TAG, "Error looking up access token", e);
}
return null;
}
}
}
| {
"content_hash": "ed998dc111a790bc18b604e865036719",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 113,
"avg_line_length": 32.11363636363637,
"alnum_prop": 0.5633404104741684,
"repo_name": "mpapp/couchbase-lite-net",
"id": "93c0351d618c7c187bfd303ce88e65c537feedff",
"size": "4683",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Couchbase.Lite.Shared/Auth/FacebookAuthorizer.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "132"
},
{
"name": "C#",
"bytes": "4814278"
},
{
"name": "Makefile",
"bytes": "663"
},
{
"name": "Shell",
"bytes": "963"
}
],
"symlink_target": ""
} |
/* jshint node: true */
'use strict';
var CopyTask = require('../tasks/copy');
var Promise = require('rsvp').Promise;
var fs = require('fs-extra');
var path = require('path');
var chalk = require('chalk');
var quickTemp = require('quick-temp');
module.exports = {
name: 'ship-it',
aliases: ['ship'],
description: 'Build the project and ship it to your destination.',
works: 'insideProject',
availableOptions: [
{ name: 'environment', type: String, default: 'production' },
{ name: 'destination-path', type: path, default: './build' },
{ name: 'javascripts-path', type: path, default: '/javascripts' },
{ name: 'stylesheets-path', type: path, default: '/stylesheets' },
{ name: 'verbose', type: Boolean, default: false },
{ name: 'skip-npm', type: Boolean, default: false },
{ name: 'skip-bower', type: Boolean, default: false }
],
config: function() {
return {
ui: this.ui,
analytics: this.analytics,
project: this.project,
settings: this.settings
};
},
start: function(options) {
var destinationPath = path.resolve(options.destinationPath);
if (fs.existsSync(destinationPath)) {
return Promise.resolve();
} else {
return Promise.reject([
'The destination-path',
chalk.yellow(destinationPath),
'does not exist!'
].join(' '));
}
},
run: function(options) {
quickTemp.makeOrRemake(options, 'outputPath');
var BowerInstall = this.tasks.BowerInstall;
var BuildTask = this.tasks.Build;
var NpmInstallTask = this.tasks.NpmInstall;
var bowerInstall = new BowerInstall(this.config());
var buildTask = new BuildTask(this.config());
var copyTask = new CopyTask(this.config());
var npmInstallTask = new NpmInstallTask(this.config());
var packageOptions = {
verbose: options.verbose
};
var ui = this.ui;
return this.start(options)
.then(function() {
if (!options.skipNpm) {
return npmInstallTask.run(packageOptions);
}
})
.then(function() {
if (!options.skipBower) {
return bowerInstall.run(packageOptions);
}
})
.then(function() {
return buildTask.run(options);
})
.then(function() {
return copyTask.run(options);
})
.finally(function() {
quickTemp.remove(options, 'outputPath');
})
.then(function() {
ui.writeLine(chalk.green('Shipped project successfully.'));
})
.catch(function(err) {
ui.writeLine(chalk.red('Shipping failed.'));
ui.writeError(err);
return 1;
});
}
};
| {
"content_hash": "9045d51b805920bc52f36c3000fb3198",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 70,
"avg_line_length": 27.454545454545453,
"alnum_prop": 0.5901398086828551,
"repo_name": "atsjj/ember-cli-squirrel",
"id": "c8b4b4705fb2bf5a714e4eae103ffb728afb406d",
"size": "2718",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/commands/ship-it.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1623"
},
{
"name": "JavaScript",
"bytes": "9865"
}
],
"symlink_target": ""
} |
title: sharepoint 온라인 k1
inshort: 정의 되지 않은
translator: Microsoft Cognitive Services
---
| {
"content_hash": "e3c6f3f1baf90ec9b5f337b86dea0387",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 40,
"avg_line_length": 13,
"alnum_prop": 0.7582417582417582,
"repo_name": "Hexatown/docs",
"id": "080f7d4faf47a3f62919668ba89b6f2e9a46ad83",
"size": "113",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "microsoft/office365/sharepoint-online-k1/ko.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "58"
},
{
"name": "CSS",
"bytes": "62970"
},
{
"name": "HTML",
"bytes": "50886"
},
{
"name": "PowerShell",
"bytes": "104690"
},
{
"name": "Ruby",
"bytes": "72"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.sql.models;
import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;
/** Defines values for PrivateEndpointProvisioningState. */
public final class PrivateEndpointProvisioningState extends ExpandableStringEnum<PrivateEndpointProvisioningState> {
/** Static value Approving for PrivateEndpointProvisioningState. */
public static final PrivateEndpointProvisioningState APPROVING = fromString("Approving");
/** Static value Ready for PrivateEndpointProvisioningState. */
public static final PrivateEndpointProvisioningState READY = fromString("Ready");
/** Static value Dropping for PrivateEndpointProvisioningState. */
public static final PrivateEndpointProvisioningState DROPPING = fromString("Dropping");
/** Static value Failed for PrivateEndpointProvisioningState. */
public static final PrivateEndpointProvisioningState FAILED = fromString("Failed");
/** Static value Rejecting for PrivateEndpointProvisioningState. */
public static final PrivateEndpointProvisioningState REJECTING = fromString("Rejecting");
/**
* Creates or finds a PrivateEndpointProvisioningState from its string representation.
*
* @param name a name to look for.
* @return the corresponding PrivateEndpointProvisioningState.
*/
@JsonCreator
public static PrivateEndpointProvisioningState fromString(String name) {
return fromString(name, PrivateEndpointProvisioningState.class);
}
/** @return known PrivateEndpointProvisioningState values. */
public static Collection<PrivateEndpointProvisioningState> values() {
return values(PrivateEndpointProvisioningState.class);
}
}
| {
"content_hash": "680d940137fff74ce1a568daacd17635",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 116,
"avg_line_length": 44.86046511627907,
"alnum_prop": 0.7786417833074132,
"repo_name": "selvasingh/azure-sdk-for-java",
"id": "9b8ba66c63fe68cb8c267d2d0a156dc682969d8b",
"size": "1929",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/models/PrivateEndpointProvisioningState.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "29891970"
},
{
"name": "JavaScript",
"bytes": "6198"
},
{
"name": "PowerShell",
"bytes": "160"
},
{
"name": "Shell",
"bytes": "609"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "027092b6e6af84a310585a448aa6c02e",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "d8936a371bb71101700c156fd56fb156fa47b0cf",
"size": "191",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Iridaceae/Sisyrinchium/Sisyrinchium macrophyllum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
session_start();
echo '<link rel="stylesheet" type="text/css" href="style.css">';
echo '<table border="1"><tr><td onclick="window.location=\'index.php\'">Home</td></tr></table>';
echo '<h1>' . $_SESSION['user'] . '</h1>';
$con=mysqli_connect("localhost","root","","users");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT email FROM " . $_SESSION['user'];
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<p>Email: ' . $row['email'] . '</p>';
echo '<h2>Classes</h2>';
echo '<table><tr>';
if (empty($row['classes'])) {
echo'<td>None</td></tr><tr><td onclick="window.location=\'addclass.php\'">Add a Class</td></tr>';
}
echo '</tr></table>';
}
} else {
echo "Error";
}
$con->close();
| {
"content_hash": "2f680e7b6686fbe99a6e8776a896e50f",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 105,
"avg_line_length": 29.580645161290324,
"alnum_prop": 0.5616139585605234,
"repo_name": "minecrafttechwiz/online-elementary",
"id": "c26d4da48510ed812be78a2b77bdb49a3fd1c4e2",
"size": "917",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "account.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "188"
},
{
"name": "PHP",
"bytes": "4616"
}
],
"symlink_target": ""
} |
/*jshint node:true*/
'use strict'
var mongoose = require('mongoose')
var schema = mongoose.Schema({
name: String,
group: String,
subgroup: String,
creator : String,
authors: Array,
ctime: Number,
utime: Number,
description: String,
simple_url: String,
ie: String,
code : String,
available: String,
type: String
});
mongoose.model('template', schema)
module.exports = function (connection) {
return (connection || mongoose).model('template')
}
| {
"content_hash": "3c982e543b35d81ca39f255a1e8f1f15",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 53,
"avg_line_length": 18.035714285714285,
"alnum_prop": 0.6415841584158416,
"repo_name": "smallertomato/harvest",
"id": "122b5f5b87044bd4a8cdb78df105a9e4b82214d9",
"size": "593",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "model/template.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "291195"
},
{
"name": "JavaScript",
"bytes": "188328"
},
{
"name": "Shell",
"bytes": "177"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Metadata;
using Microsoft.Xrm.Client.Security;
using Microsoft.Xrm.Portal.Cms;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
namespace Microsoft.Xrm.Portal.Web.UI.WebControls
{
/// <summary>
/// Renders a web link set (adx_weblinkset) as a list of links.
/// </summary>
public class WebLinks : EditableCrmEntityDataBoundControl // MSBug #120119: Won't seal, Inheritance is expected extension point.
{
private bool _showCopy = true;
private bool _showLinkDescriptions = true;
private bool _showImage = true;
private bool _showTitle = true;
/// <summary>
/// Gets or sets a CSS class value to be added to the hyperlink if the target node of
/// the hyperlink is the current site map node.
/// </summary>
[Description("A CSS class value to be added to a weblink if the target node of the weblink is the current site map node")]
[Category("Data")]
[DefaultValue((string)null)]
public string CurrentSiteMapNodeCssClass { get; set; }
/// <summary>
/// Gets or sets a CSS class value to be added to the hyperlink if the current site map
/// node is a descendant of the target node of the hyperlink.
/// </summary>
[Description("A CSS class value to be added to a weblink if the current site map node is a descendant of the target node of the weblink")]
[Category("Data")]
[DefaultValue((string)null)]
public string ParentOfCurrentSiteMapNodeCssClass { get; set; }
public string DescriptionCssClass { get; set; }
public bool ShowCopy
{
get { return _showCopy; }
set { _showCopy = value; }
}
public bool ShowImage
{
get { return _showImage; }
set { _showImage = value; }
}
public bool ShowLinkDescriptions
{
get { return _showLinkDescriptions; }
set { _showLinkDescriptions = value; }
}
public bool ShowTitle
{
get { return _showTitle; }
set { _showTitle = value; }
}
protected override HtmlTextWriterTag TagKey
{
get { return HtmlTextWriterTag.Div; }
}
public string WebLinkSetName { get; set; }
protected override void OnLoad(EventArgs args)
{
Entity webLinkSet;
if (TryGetWebLinkSetEntity(WebLinkSetName, out webLinkSet))
{
DataItem = webLinkSet;
}
base.OnLoad(args);
}
protected override void PerformDataBindingOfCrmEntity(Entity entity)
{
var portal = PortalCrmConfigurationManager.CreatePortalContext(PortalName);
var context = portal.ServiceContext;
entity = context.MergeClone(entity);
if (ShowTitle)
{
Controls.Add(new Property
{
PropertyName = GetPropertyName(context, entity, "adx_title"),
CssClass = "weblinkset-title",
EditType = "text",
DataItem = entity
});
}
if (ShowCopy)
{
Controls.Add(new Property
{
PropertyName = GetPropertyName(context, entity, "adx_copy"),
CssClass = "weblinkset-copy",
EditType = "html",
DataItem = entity
});
}
var securityProvider = PortalCrmConfigurationManager.CreateCrmEntitySecurityProvider(PortalName);
var weblinks = entity.GetRelatedEntities(context, "adx_weblinkset_weblink")
.Where(e => securityProvider.TryAssert(context, e, CrmEntityRight.Read))
.OrderBy(weblink => weblink.GetAttributeValue<int?>("adx_displayorder"))
.ToList();
var weblinkCount = weblinks.Count();
var listItems = weblinks.Select((weblink, index) =>
{
var li = new HtmlGenericControl("li");
SetPositionalClassAttribute(li, weblinkCount, index);
if (ItemTemplate != null)
{
var item = CreateItem(this, index, ListItemType.Item, true, weblink);
Controls.Remove(item);
li.Controls.Add(item);
}
else
{
li.Controls.Add(GetHyperLinkForWebLink(weblink));
if (ShowLinkDescriptions)
{
var description = new HtmlGenericControl("div");
description.Controls.Add(new Property
{
PropertyName = GetPropertyName(context, weblink, "adx_description"),
DataItem = weblink,
Literal = true
});
if (!string.IsNullOrEmpty(DescriptionCssClass))
{
description.Attributes["class"] = DescriptionCssClass;
}
li.Controls.Add(description);
}
}
return li;
});
var container = new HtmlGenericControl("div");
var containerCssClasses = new List<string> { "weblinkset-weblinks" };
Controls.Add(container);
if (listItems.Any())
{
var list = new HtmlGenericControl("ul");
foreach (var li in listItems)
{
list.Controls.Add(li);
}
container.Controls.Add(list);
}
if (Editable)
{
containerCssClasses.Add("xrm-entity");
containerCssClasses.Add("xrm-editable-{0}".FormatWith(entity.LogicalName));
if (HasEditPermission(entity))
{
var metadataProvider = PortalCrmConfigurationManager.CreateDependencyProvider(PortalName).GetDependency<ICrmEntityEditingMetadataProvider>();
metadataProvider.AddEntityMetadata(PortalName, this, container, entity);
this.RegisterClientSideDependencies();
}
}
container.Attributes["class"] = string.Join(" ", containerCssClasses.ToArray());
}
protected override void PerformDataBindingOfCrmEntityProperty(Entity entity, string propertyName, string value)
{
PerformDataBindingOfCrmEntity(entity);
}
private HyperLink GetHyperLinkForWebLink(Entity weblink)
{
var hyperLink = new WebLinkHyperLink
{
WebLink = weblink, ShowImage = ShowImage, CurrentSiteMapNodeCssClass = CurrentSiteMapNodeCssClass, ParentOfCurrentSiteMapNodeCssClass = ParentOfCurrentSiteMapNodeCssClass, PortalName = PortalName
};
if (Editable)
{
hyperLink.CssClass = "xrm-weblink {0}".FormatWith(hyperLink.CssClass);
}
return hyperLink;
}
private bool TryGetWebLinkSetEntity(string webLinkSetName, out Entity webLinkSet)
{
webLinkSet = null;
if (string.IsNullOrEmpty(webLinkSetName))
{
return false;
}
var portal = PortalCrmConfigurationManager.CreatePortalContext(PortalName);
var context = portal.ServiceContext;
webLinkSet = context.GetLinkSetByName(portal.Website, WebLinkSetName);
var securityProvider = PortalCrmConfigurationManager.CreateCrmEntitySecurityProvider(PortalName);
return webLinkSet != null && securityProvider.TryAssert(context, webLinkSet, CrmEntityRight.Read);
}
private static void SetPositionalClassAttribute(HtmlControl control, int weblinkCount, int index)
{
var positionalCssClasses = new List<string>();
if (index == 0)
{
positionalCssClasses.Add("first");
}
if (index == (weblinkCount - 1))
{
positionalCssClasses.Add("last");
}
if (weblinkCount == 1)
{
positionalCssClasses.Add("only");
}
if (positionalCssClasses.Count > 0)
{
control.Attributes["class"] = string.Join(" ", positionalCssClasses.ToArray());
}
}
private static string GetPropertyName(OrganizationServiceContext context, Entity entity, string logicalName)
{
EntitySetInfo esi;
AttributeInfo ai;
if (OrganizationServiceContextInfo.TryGet(context, entity, out esi)
&& esi.Entity.AttributesByLogicalName.TryGetValue(logicalName, out ai))
{
return ai.Property.Name;
}
throw new InvalidOperationException("The '{0}' entity does not contain an attribute with the logical name '{1}'.".FormatWith(entity, logicalName));
}
}
}
| {
"content_hash": "498c6031755a5a7afea11de6edb412ee",
"timestamp": "",
"source": "github",
"line_count": 284,
"max_line_length": 199,
"avg_line_length": 26.764084507042252,
"alnum_prop": 0.7034600710432838,
"repo_name": "amervitz/xRM-Portals-Community-Edition",
"id": "83a81f1586563adb4f8e40d08ccea879493a5291",
"size": "7761",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Framework/Microsoft.Xrm.Portal/Web/UI/WebControls/WebLinks.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "1027"
},
{
"name": "C#",
"bytes": "8740413"
},
{
"name": "CSS",
"bytes": "129593"
},
{
"name": "HTML",
"bytes": "7187"
},
{
"name": "JavaScript",
"bytes": "685841"
},
{
"name": "Liquid",
"bytes": "44357"
},
{
"name": "PowerShell",
"bytes": "3120"
},
{
"name": "Smalltalk",
"bytes": "619208"
}
],
"symlink_target": ""
} |
package com.damonlei.vimdroid;
import android.content.Context;
import android.content.res.Resources;
import com.damonlei.utils.ResourceHelper;
/**
* @author damonlei
* @time 2017/4/12
* @email [email protected]
*/
public class Settings {
// 是否显示点击区域
public boolean displayClickableRegion;
// 每次滑动的距离,up/down/left/right
public int scrollPx;
// 是否平滑滑动
public boolean smoothScroll;
private Settings(Builder builder) {
displayClickableRegion = builder.displayClickableRegion;
scrollPx = builder.scrollPx;
smoothScroll = builder.smoothScroll;
}
public static final class Builder {
private boolean displayClickableRegion = false;
private int scrollPx;
private boolean smoothScroll = false;
private Context context;
public Builder(Context context) {
this.context = context;
scrollPx = ResourceHelper.fromDPToPix(this.context, 130);
}
public Builder displayClickableRegion(boolean val) {
displayClickableRegion = val;
return this;
}
public Builder scrollPx(int val) {
scrollPx = val;
return this;
}
public Builder smoothScroll(boolean val) {
smoothScroll = val;
return this;
}
public Settings build() {
return new Settings(this);
}
}
} | {
"content_hash": "c7f1cc853d315fc80d84a39766434a55",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 69,
"avg_line_length": 24.28813559322034,
"alnum_prop": 0.6266573621772505,
"repo_name": "DanxiongLei/Vimdroid",
"id": "f59af4c66555b6fa582998c12ed653d4762b0cd4",
"size": "1477",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vim-android/app/src/main/java/com/damonlei/vimdroid/Settings.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "146407"
},
{
"name": "JavaScript",
"bytes": "2919"
},
{
"name": "TypeScript",
"bytes": "21132"
}
],
"symlink_target": ""
} |
name:
position:
image_path:
twitter_handle:
---
| {
"content_hash": "9e957c286b55e485c50573d4a45d69aa",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 15,
"avg_line_length": 9.6,
"alnum_prop": 0.7083333333333334,
"repo_name": "jantede/concept-page",
"id": "41e3f18871eb5a326de1fbfd0d1b6669c8f10027",
"size": "52",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "_staff_members/_defaults.md",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9670"
},
{
"name": "HTML",
"bytes": "17473"
},
{
"name": "JavaScript",
"bytes": "2935"
},
{
"name": "Ruby",
"bytes": "1470"
}
],
"symlink_target": ""
} |
// bufferish.js
/* jshint eqnull:true */
var Buffer = exports.original = require("./original");
var hasBuffer = !!(Buffer && Buffer.isBuffer);
var hasArrayBuffer = ("undefined" !== typeof ArrayBuffer);
exports.isArray = Array.isArray || _is("Array");
exports.isArrayBuffer = hasArrayBuffer ? isArrayBuffer : _false;
exports.isBuffer = hasBuffer ? Buffer.isBuffer : _false;
exports.isView = hasArrayBuffer ? (ArrayBuffer.isView || isView) : _false;
var Static = require("./static");
exports.alloc = Static.alloc;
exports.concat = Static.concat;
exports.from = Static.from;
exports.prototype = require("./prototype");
exports.Array = require("./array");
if (hasBuffer) {
exports.Buffer = require("./buffer");
}
if (hasArrayBuffer) {
exports.Uint8Array = require("./uint8array");
}
var _isArrayBuffer = _is("ArrayBuffer");
function isArrayBuffer(value) {
return (value instanceof ArrayBuffer) || _isArrayBuffer(value);
}
function isView(value) {
return (value != null) && isArrayBuffer(value.buffer);
}
function _false() {
return false;
}
function _is(name) {
name = "[object " + name + "]";
return function(value) {
return (value != null) && {}.toString.call(value) === name;
};
}
| {
"content_hash": "b7c135d39c6eac7620a4c4fd41dcad78",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 74,
"avg_line_length": 24.24,
"alnum_prop": 0.6831683168316832,
"repo_name": "kawanet/bufferish",
"id": "002a55809abc021f5d88377720eb29c59f3ac20f",
"size": "1212",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "106"
},
{
"name": "JavaScript",
"bytes": "29690"
}
],
"symlink_target": ""
} |
var _storagearea = "local";
class StorageItem {
constructor(value,key) {
this.value = value;
this.key = key;
this.set(value);
}
set(value) {
this.value = value;
var out = {};
out[this.key] = this.value;
chrome.storage[_storagearea].set(out);
}
get() {
return this.value;
}
}
var storage = {
data: {},
add: function(key,value) {
this.data[key] = new StorageItem(value,key);
return this.data[key];
},
set: function(key,value) {
if (this.data[key] !== undefined) {
try {
this.data[key].set(value);
} catch(e) {
// console.warn(e);
this.data[key] = new StorageItem(value,key);
}
} else {
this.add(key,value);
}
},
get: function(key) {
if (this.data[key] instanceof StorageItem) {
return this.data[key].get();
} else {
return undefined;
}
},
remove: function(key) {
chrome.storage[_storagearea].remove(key);
},
refresh: function() {
chrome.storage[_storagearea].get(function(data) {
for (var a in data) {
storage.set(a,data[a]);
}
});
this.defaults();
},
onChanged: function(changes,area) {
if (area == _storagearea) {
for (var a in changes) {
if (changes[a].newValue != undefined) {
storage.set(a,changes[a].newValue);
} else {
delete storage.data[a];
}
}
for (var i=0;i<storage.changeListeners.length;i++) {
storage.changeListeners[i]();
}
}
},
debug: function() {
chrome.storage[_storagearea].get((d)=>{console.log(d)});
},
defaults: function() {
// if (this.get("visualizations") == undefined) {
// this.set("visualizations",{bars:true,line:true});
// } else {
// var value = this.get("visualizations");
// if (value["bars"] == undefined) {
// value["bars"] = true;
// this.set("visualizations",value);
// }
// if (value["line"] == undefined) {
// value["line"] = true;
// this.set("visualizations",value);
// }
// }
var values = ['visualizations.bars','visualizations.line'];
for (var i=0;i<values.length;i++) {
let value = values[i];
if (this.get(value) === undefined) {
this.set(value,true);
}
}
},
changeListeners: [],
addListener: function(listener) {
storage.changeListeners.push(listener);
}
}
chrome.storage.onChanged.addListener(storage.onChanged);
storage.refresh();
| {
"content_hash": "119097df726ca4aace0bda3add202324",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 63,
"avg_line_length": 24.99,
"alnum_prop": 0.5518207282913166,
"repo_name": "Douile/Chrome-Audio-Visualizer",
"id": "ead820e7ec92a3f4e08096ca8ce8d015a649e07c",
"size": "2499",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/storage.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1886"
},
{
"name": "HTML",
"bytes": "3795"
},
{
"name": "JavaScript",
"bytes": "32119"
}
],
"symlink_target": ""
} |
package org.eigenbase.rex;
import java.util.*;
import org.eigenbase.sql.*;
import org.eigenbase.sql.fun.*;
import org.eigenbase.sql.type.*;
import com.google.common.collect.ImmutableSet;
/**
* Utility class for various methods related to multisets.
*/
public class RexMultisetUtil {
//~ Static fields/initializers ---------------------------------------------
/**
* A set defining all implementable multiset calls
*/
private static final Set<SqlOperator> MULTISET_OPERATORS =
ImmutableSet.of(
SqlStdOperatorTable.CARDINALITY,
SqlStdOperatorTable.CAST,
SqlStdOperatorTable.ELEMENT,
SqlStdOperatorTable.ELEMENT_SLICE,
SqlStdOperatorTable.MULTISET_EXCEPT_ALL,
SqlStdOperatorTable.MULTISET_EXCEPT,
SqlStdOperatorTable.MULTISET_INTERSECT_ALL,
SqlStdOperatorTable.MULTISET_INTERSECT,
SqlStdOperatorTable.MULTISET_UNION_ALL,
SqlStdOperatorTable.MULTISET_UNION,
SqlStdOperatorTable.IS_A_SET,
SqlStdOperatorTable.MEMBER_OF,
SqlStdOperatorTable.SUBMULTISET_OF);
//~ Methods ----------------------------------------------------------------
private RexMultisetUtil() {
}
/**
* Returns true if any expression in a program contains a mixing between
* multiset and non-multiset calls.
*/
public static boolean containsMixing(RexProgram program) {
RexCallMultisetOperatorCounter counter =
new RexCallMultisetOperatorCounter();
for (RexNode expr : program.getExprList()) {
counter.reset();
expr.accept(counter);
if ((counter.totalCount != counter.multisetCount)
&& (0 != counter.multisetCount)) {
return true;
}
}
return false;
}
/**
* Returns true if a node contains a mixing between multiset and
* non-multiset calls.
*/
public static boolean containsMixing(RexNode node) {
RexCallMultisetOperatorCounter counter =
new RexCallMultisetOperatorCounter();
node.accept(counter);
return (counter.totalCount != counter.multisetCount)
&& (0 != counter.multisetCount);
}
/**
* Returns true if node contains a multiset operator, otherwise false. Use
* it with deep=false when checking if a RexCall is a multiset call.
*
* @param node Expression
* @param deep If true, returns whether expression contains a multiset. If
* false, returns whether expression <em>is</em> a multiset.
*/
public static boolean containsMultiset(final RexNode node, boolean deep) {
return null != findFirstMultiset(node, deep);
}
/**
* Returns whether a list of expressions contains a multiset.
*/
public static boolean containsMultiset(List<RexNode> nodes, boolean deep) {
for (RexNode node : nodes) {
if (containsMultiset(node, deep)) {
return true;
}
}
return false;
}
/**
* Returns whether a program contains a multiset.
*/
public static boolean containsMultiset(RexProgram program) {
return containsMultiset(program.getExprList(), true);
}
/**
* Returns true if call is call to <code>CAST</code> and the to/from cast
* types are of multiset types
*/
public static boolean isMultisetCast(RexCall call) {
if (!call.getOperator().equals(SqlStdOperatorTable.CAST)) {
return false;
}
return call.getType().getSqlTypeName() == SqlTypeName.MULTISET;
}
/**
* Returns a reference to the first found multiset call or null if none was
* found
*/
public static RexCall findFirstMultiset(final RexNode node, boolean deep) {
if (node instanceof RexFieldAccess) {
return findFirstMultiset(
((RexFieldAccess) node).getReferenceExpr(),
deep);
}
if (!(node instanceof RexCall)) {
return null;
}
final RexCall call = (RexCall) node;
RexCall firstOne = null;
for (SqlOperator op : MULTISET_OPERATORS) {
firstOne = RexUtil.findOperatorCall(op, call);
if (null != firstOne) {
if (firstOne.getOperator().equals(SqlStdOperatorTable.CAST)
&& !isMultisetCast(firstOne)) {
firstOne = null;
continue;
}
break;
}
}
if (!deep && (firstOne != call)) {
return null;
}
return firstOne;
}
//~ Inner Classes ----------------------------------------------------------
/**
* A RexShuttle that traverse all RexNode and counts total number of
* RexCalls traversed and number of multiset calls traversed.
*
* <p>totalCount >= multisetCount always holds true.
*/
private static class RexCallMultisetOperatorCounter
extends RexVisitorImpl<Void> {
int totalCount = 0;
int multisetCount = 0;
RexCallMultisetOperatorCounter() {
super(true);
}
void reset() {
totalCount = 0;
multisetCount = 0;
}
public Void visitCall(RexCall call) {
++totalCount;
if (MULTISET_OPERATORS.contains(call.getOperator())) {
if (!call.getOperator().equals(SqlStdOperatorTable.CAST)
|| isMultisetCast(call)) {
++multisetCount;
}
}
return super.visitCall(call);
}
}
}
// End RexMultisetUtil.java
| {
"content_hash": "ff85ef739981c5d6db7d227d5e9fdd7f",
"timestamp": "",
"source": "github",
"line_count": 184,
"max_line_length": 78,
"avg_line_length": 28.445652173913043,
"alnum_prop": 0.6335498662590753,
"repo_name": "nvoron23/incubator-calcite",
"id": "63f4449a1160c779d9dcae7a4830b443b4750ac7",
"size": "6031",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/src/main/java/org/eigenbase/rex/RexMultisetUtil.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.hisp.dhis.dataadmin.action.attribute;
import java.util.List;
import org.hisp.dhis.attribute.Attribute;
import org.hisp.dhis.attribute.AttributeService;
import com.opensymphony.xwork2.Action;
public class SaveAttributeSortOrderAction
implements Action
{
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
private AttributeService attributeService;
public void setAttributeService( AttributeService attributeService )
{
this.attributeService = attributeService;
}
// -------------------------------------------------------------------------
// Input & Output
// -------------------------------------------------------------------------
private List<Integer> attributes;
public void setAttributes( List<Integer> attributes )
{
this.attributes = attributes;
}
// -------------------------------------------------------------------------
// Action Implementation
// -------------------------------------------------------------------------
@Override
public String execute()
{
int sortOrder = 1;
for ( Integer id : attributes )
{
Attribute attribute = attributeService.getAttribute( id );
attribute.setSortOrder( sortOrder++ );
attributeService.updateAttribute( attribute );
}
return SUCCESS;
}
}
| {
"content_hash": "509c49790c514b9e6b314db252252895",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 80,
"avg_line_length": 27.649122807017545,
"alnum_prop": 0.4397208121827411,
"repo_name": "minagri-rwanda/DHIS2-Agriculture",
"id": "19e5d4e853bfdc4207d1793f17f0ffe7833f2ab3",
"size": "3158",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "dhis-web/dhis-web-maintenance/dhis-web-maintenance-dataadmin/src/main/java/org/hisp/dhis/dataadmin/action/attribute/SaveAttributeSortOrderAction.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "384517"
},
{
"name": "Game Maker Language",
"bytes": "20893"
},
{
"name": "HTML",
"bytes": "637522"
},
{
"name": "Java",
"bytes": "16273326"
},
{
"name": "JavaScript",
"bytes": "5566092"
},
{
"name": "Ruby",
"bytes": "1011"
},
{
"name": "Shell",
"bytes": "388"
},
{
"name": "XSLT",
"bytes": "8281"
}
],
"symlink_target": ""
} |
namespace SolrNet.Cloud {
public class SolrCloudReplica {
public SolrCloudReplica(bool isActive, bool isLeader, string name, string url) {
IsActive = isActive;
IsLeader = isLeader;
Name = name;
Url = url;
}
public bool IsActive { get; private set; }
public bool IsLeader { get; private set; }
public string Name { get; private set; }
public string Url { get; private set; }
}
} | {
"content_hash": "ad8b522cd171395a4c1340cebefd4752",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 88,
"avg_line_length": 27.944444444444443,
"alnum_prop": 0.5526838966202783,
"repo_name": "vladen/SolrNet",
"id": "e98ad5a40fe11c02275d63f7c5167e2252775c72",
"size": "505",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SolrNet.Cloud/SolrCloudReplica.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "5753"
},
{
"name": "ApacheConf",
"bytes": "1842"
},
{
"name": "Boo",
"bytes": "2837"
},
{
"name": "C#",
"bytes": "1691175"
},
{
"name": "CSS",
"bytes": "8717"
},
{
"name": "F#",
"bytes": "13133"
},
{
"name": "HTML",
"bytes": "111165"
},
{
"name": "JavaScript",
"bytes": "22061"
},
{
"name": "Shell",
"bytes": "2061"
},
{
"name": "XSLT",
"bytes": "58933"
}
],
"symlink_target": ""
} |
package state_test
import (
biagentclient "github.com/cloudfoundry/bosh-agent/agentclient"
mock_agentclient "github.com/cloudfoundry/bosh-init/agentclient/mocks"
"github.com/golang/mock/gomock"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
mock_blobstore "github.com/cloudfoundry/bosh-init/blobstore/mocks"
. "github.com/cloudfoundry/bosh-init/deployment/instance/state"
biindex "github.com/cloudfoundry/bosh-init/index"
boshpkg "github.com/cloudfoundry/bosh-init/release/pkg"
. "github.com/cloudfoundry/bosh-init/release/resource"
bistatepkg "github.com/cloudfoundry/bosh-init/state/pkg"
)
var _ = Describe("RemotePackageCompiler", func() {
var mockCtrl *gomock.Controller
BeforeEach(func() {
mockCtrl = gomock.NewController(GinkgoT())
})
AfterEach(func() {
mockCtrl.Finish()
})
var (
packageRepo bistatepkg.CompiledPackageRepo
mockBlobstore *mock_blobstore.MockBlobstore
mockAgentClient *mock_agentclient.MockAgentClient
archivePath = "fake-archive-path"
remotePackageCompiler bistatepkg.Compiler
expectBlobstoreAdd *gomock.Call
expectAgentCompile *gomock.Call
)
BeforeEach(func() {
mockBlobstore = mock_blobstore.NewMockBlobstore(mockCtrl)
mockAgentClient = mock_agentclient.NewMockAgentClient(mockCtrl)
index := biindex.NewInMemoryIndex()
packageRepo = bistatepkg.NewCompiledPackageRepo(index)
remotePackageCompiler = NewRemotePackageCompiler(mockBlobstore, mockAgentClient, packageRepo)
})
Describe("Compile", func() {
Context("when package is not compiled", func() {
var (
pkgDependency *boshpkg.Package
pkg *boshpkg.Package
compiledPackages map[bistatepkg.CompiledPackageRecord]*boshpkg.Package
)
BeforeEach(func() {
pkgDependency = boshpkg.NewPackage(NewResource(
"fake-package-name-dep", "fake-package-fingerprint-dep", nil), nil)
pkg = boshpkg.NewPackage(NewResourceWithBuiltArchive(
"fake-package-name", "fake-package-fingerprint", archivePath, "fake-source-package-sha1"), []string{"fake-package-name-dep"})
pkg.AttachDependencies([]*boshpkg.Package{pkgDependency})
depRecord1 := bistatepkg.CompiledPackageRecord{
BlobID: "fake-compiled-package-blob-id-dep",
BlobSHA1: "fake-compiled-package-sha1-dep",
}
compiledPackages = map[bistatepkg.CompiledPackageRecord]*boshpkg.Package{
depRecord1: pkgDependency,
}
})
JustBeforeEach(func() {
// add compiled packages to the repo
for record, dependency := range compiledPackages {
err := packageRepo.Save(dependency, record)
Expect(err).ToNot(HaveOccurred())
}
packageSource := biagentclient.BlobRef{
Name: "fake-package-name",
Version: "fake-package-fingerprint",
BlobstoreID: "fake-source-package-blob-id",
SHA1: "fake-source-package-sha1",
}
packageDependencies := []biagentclient.BlobRef{
{
Name: "fake-package-name-dep",
Version: "fake-package-fingerprint-dep",
BlobstoreID: "fake-compiled-package-blob-id-dep",
SHA1: "fake-compiled-package-sha1-dep",
},
}
compiledPackageRef := biagentclient.BlobRef{
Name: "fake-package-name",
Version: "fake-package-version",
BlobstoreID: "fake-compiled-package-blob-id",
SHA1: "fake-compiled-package-sha1",
}
expectBlobstoreAdd = mockBlobstore.EXPECT().Add(archivePath).Return("fake-source-package-blob-id", nil).AnyTimes()
expectAgentCompile = mockAgentClient.EXPECT().CompilePackage(packageSource, packageDependencies).Return(compiledPackageRef, nil).AnyTimes()
})
It("uploads the package archive to the blobstore and then compiles the package with the agent", func() {
gomock.InOrder(
expectBlobstoreAdd.Times(1),
expectAgentCompile.Times(1),
)
compiledPackageRecord, _, err := remotePackageCompiler.Compile(pkg)
Expect(err).ToNot(HaveOccurred())
Expect(compiledPackageRecord).To(Equal(bistatepkg.CompiledPackageRecord{
BlobID: "fake-compiled-package-blob-id",
BlobSHA1: "fake-compiled-package-sha1",
}))
})
It("saves the compiled package ref in the package repo", func() {
compiledPackageRecord, _, err := remotePackageCompiler.Compile(pkg)
Expect(err).ToNot(HaveOccurred())
record, found, err := packageRepo.Find(pkg)
Expect(err).ToNot(HaveOccurred())
Expect(found).To(BeTrue())
Expect(record).To(Equal(compiledPackageRecord))
})
Context("when the dependencies are not in the repo", func() {
BeforeEach(func() {
compiledPackages = map[bistatepkg.CompiledPackageRecord]*boshpkg.Package{}
})
It("returns an error", func() {
_, _, err := remotePackageCompiler.Compile(pkg)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("Remote compilation failure: Package 'fake-package-name/fake-package-fingerprint' requires package 'fake-package-name-dep/fake-package-fingerprint-dep', but it has not been compiled"))
})
})
})
Context("when package is compiled", func() {
var (
pkgDependency *boshpkg.CompiledPackage
pkg *boshpkg.CompiledPackage
)
BeforeEach(func() {
pkgDependency = boshpkg.NewCompiledPackageWithoutArchive(
"fake-package-name-dep", "fake-package-fingerprint-dep", "", "", nil)
pkg = boshpkg.NewCompiledPackageWithArchive(
"fake-package-name", "fake-package-fingerprint", "", archivePath, "fake-source-package-sha1", []string{"fake-package-name-dep"})
pkg.AttachDependencies([]*boshpkg.CompiledPackage{pkgDependency})
})
It("should skip compilation but still add blobstore package", func() {
err := packageRepo.Save(pkgDependency, bistatepkg.CompiledPackageRecord{
BlobID: "fake-compiled-package-blob-id-dep",
BlobSHA1: "fake-compiled-package-sha1-dep",
})
Expect(err).ToNot(HaveOccurred())
expectBlobstoreAdd = mockBlobstore.EXPECT().Add(archivePath).Return("fake-source-package-blob-id", nil).AnyTimes()
expectAgentCompile = mockAgentClient.EXPECT().CompilePackage(gomock.Any(), gomock.Any()).AnyTimes()
compiledPackageRecord, isAlreadyCompiled, err := remotePackageCompiler.Compile(pkg)
Expect(err).ToNot(HaveOccurred())
Expect(isAlreadyCompiled).To(Equal(true))
Expect(compiledPackageRecord).To(Equal(bistatepkg.CompiledPackageRecord{
BlobID: "fake-source-package-blob-id",
BlobSHA1: "fake-source-package-sha1",
}))
expectAgentCompile.Times(0)
})
})
})
})
| {
"content_hash": "3109972d73c6d72031f4e70d7807f1b7",
"timestamp": "",
"source": "github",
"line_count": 185,
"max_line_length": 229,
"avg_line_length": 35.22162162162162,
"alnum_prop": 0.711939840392879,
"repo_name": "forrestsill/bosh-init",
"id": "2fd20f7e22e6d0e08332fe49f782431f44045d5b",
"size": "6516",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "deployment/instance/state/remote_package_compiler_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "2758972"
},
{
"name": "Ruby",
"bytes": "974"
},
{
"name": "Shell",
"bytes": "18137"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
GRIN Taxonomy for Plants
#### Published in
von Goetzen, Durch Afrika von ost nach west 6. 1895
#### Original name
null
### Remarks
null | {
"content_hash": "518e8a3736a2f8c30d391663bb081982",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 51,
"avg_line_length": 12.692307692307692,
"alnum_prop": 0.7090909090909091,
"repo_name": "mdoering/backbone",
"id": "fa061899c859509463e798e1a2c595dcda7a0793",
"size": "216",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Malvaceae/Dombeya/Dombeya torrida/ Syn. Dombeya goetzenii/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import './strings.m.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import * as error_reporter from './error_reporter.js';
import {assertCast, MessagePipe} from './message_pipe.m.js';
import {DeleteFileMessage, FileContext, LoadFilesMessage, Message, NavigateMessage, NotifyCurrentFileMessage, OpenAllowedFileMessage, OpenAllowedFileResponse, OpenFilesWithPickerMessage, OverwriteFileMessage, OverwriteViaFilePickerResponse, RenameFileMessage, RenameResult, RequestSaveFileMessage, RequestSaveFileResponse, SaveAsMessage, SaveAsResponse} from './message_types.js';
import {mediaAppPageHandler} from './mojo_api_bootstrap.js';
const EMPTY_WRITE_ERROR_NAME = 'EmptyWriteError';
// Open file picker configurations. Should be kept in sync with launch handler
// configurations in media_web_app_info.cc.
const AUDIO_EXTENSIONS =
['.flac', '.m4a', '.mp3', '.oga', '.ogg', '.opus', '.wav', '.weba', '.m4a'];
const IMAGE_EXTENSIONS = [
'.jpg', '.png', '.webp', '.gif', '.avif', '.bmp', '.ico', '.svg',
'.jpeg', '.jpe', '.jfif', '.jif', '.jfi', '.pjpeg', '.pjp', '.arw',
'.cr2', '.dng', '.nef', '.nrw', '.orf', '.raf', '.rw2', '.svgz'
];
const VIDEO_EXTENSIONS = [
'.3gp', '.avi', '.m4v', '.mkv', '.mov', '.mp4', '.mpeg', '.mpeg4', '.mpg',
'.mpg4', '.ogv', '.ogx', '.ogm', '.webm'
];
const OPEN_ACCEPT_ARGS = {
'AUDIO': {
description: loadTimeData.getString('fileFilterAudio'),
accept: {'audio/*': AUDIO_EXTENSIONS}
},
'IMAGE': {
description: loadTimeData.getString('fileFilterImage'),
accept: {'image/*': IMAGE_EXTENSIONS}
},
'VIDEO': {
description: loadTimeData.getString('fileFilterVideo'),
accept: {'video/*': VIDEO_EXTENSIONS}
},
'PDF': {description: 'PDF', accept: {'application/pdf': '.pdf'}},
};
/**
* Sort order for files in the navigation ring.
* @enum
*/
const SortOrder = {
/**
* Lexicographic (with natural number ordering): advancing goes "down" the
* alphabet.
*/
A_FIRST: 1,
/**
* Reverse lexicographic (with natural number ordering): advancing goes "up"
* the alphabet.
*/
Z_FIRST: 2,
/** By modified time: pressing "right" goes to older files. */
NEWEST_FIRST: 3,
};
/**
* Wrapper around a file handle that allows the privileged context to arbitrate
* read and write access as well as file navigation. `token` uniquely identifies
* the file, `file` temporarily holds the object passed over postMessage, and
* `handle` allows it to be reopened upon navigation. If an error occurred on
* the last attempt to open `handle`, `lastError` holds the error name.
* @typedef {{
* token: number,
* file: ?File,
* handle: !FileSystemFileHandle,
* lastError: (string|undefined),
* inCurrentDirectory: (boolean|undefined),
* }}
*/
let FileDescriptor;
/**
* Array of entries available in the current directory.
*
* @type {!Array<!FileDescriptor>}
*/
const currentFiles = [];
/**
* A variable for storing the name of the app, taken from the <title>. We store
* it here since we mutate the title to show filename, but may want to restore
* it in some circumstances i.e. returning to zero state.
*/
let appTitle;
/**
* The current sort order.
* TODO(crbug/414789): Match the file manager order when launched that way.
* Note currently this is reassigned in tests.
* @type {!SortOrder}
*/
// eslint-disable-next-line prefer-const
let sortOrder = SortOrder.A_FIRST;
/**
* Index into `currentFiles` of the current file.
*
* @type {number}
*/
let entryIndex = -1;
/**
* Keeps track of the current launch (i.e. call to `launchWithDirectory`) .
* Since file loading can be deferred i.e. we can load the first focused file
* and start using the app then load other files in `loadOtherRelatedFiles()` we
* need to make sure `loadOtherRelatedFiles` gets aborted if it is out of date
* i.e. in interleaved launches.
*
* @type {number}
*/
let globalLaunchNumber = -1;
/**
* Reference to the directory handle that contains the first file in the most
* recent launch event.
* @type {?FileSystemDirectoryHandle}
*/
let currentDirectoryHandle = null;
/**
* Map of file tokens. Persists across new launch requests from the file
* manager when chrome://media-app has not been closed.
* @type {!Map<number, !FileSystemFileHandle>}
*/
const tokenMap = new Map();
/**
* A pipe through which we can send messages to the guest frame.
* Use an undefined `target` to find the <iframe> automatically.
* Do not rethrow errors, since handlers installed here are expected to
* throw exceptions that are handled on the other side of the pipe. And
* nothing `awaits` async callHandlerForMessageType_(), so they will always
* be reported as `unhandledrejection` and trigger a crash report.
*/
const guestMessagePipe =
new MessagePipe('chrome-untrusted://media-app', undefined, false);
/**
* Promise that resolves once the iframe is ready to receive messages. This is
* to allow initial file processing to run in parallel with the iframe load.
* @type {!Promise<undefined>}
*/
const iframeReady = new Promise(resolve => {
guestMessagePipe.registerHandler(Message.IFRAME_READY, resolve);
});
guestMessagePipe.registerHandler(Message.NOTIFY_CURRENT_FILE, message => {
const notifyMsg = /** @type {!NotifyCurrentFileMessage} */ (message);
const title =
/** @type {!HTMLTitleElement} */ (document.querySelector('title'));
appTitle = appTitle || title.text;
title.text = notifyMsg.name || appTitle;
let genericType = notifyMsg.type ? notifyMsg.type.split('/')[0] : 'file';
if (title.text === appTitle) {
genericType = 'app';
} else if (notifyMsg.type === 'application/pdf') {
genericType = 'pdf';
} else if (!['audio', 'image', 'video', 'file'].includes(genericType)) {
genericType = 'file';
}
const icon = /** @type {!HTMLLinkElement} */ (
document.querySelector('link[rel=icon]'));
icon.href = `system_assets/${genericType}_icon.svg`;
});
guestMessagePipe.registerHandler(Message.OPEN_FEEDBACK_DIALOG, () => {
let response = mediaAppPageHandler.openFeedbackDialog();
if (response === null) {
response = {errorMessage: 'Null response received'};
}
return response;
});
guestMessagePipe.registerHandler(Message.TOGGLE_BROWSER_FULLSCREEN_MODE, () => {
mediaAppPageHandler.toggleBrowserFullscreenMode();
});
guestMessagePipe.registerHandler(Message.OPEN_IN_SANDBOXED_VIEWER, message => {
window.open(
`./viewpdfhost.html?${new URLSearchParams(message)}`, '_blank',
'popup=1');
});
guestMessagePipe.registerHandler(Message.OVERWRITE_FILE, async (message) => {
const overwrite = /** @type {!OverwriteFileMessage} */ (message);
const originalHandle = fileHandleForToken(overwrite.token);
try {
await saveBlobToFile(originalHandle, overwrite.blob);
} catch (/** @type {!DOMException|!Error} */ e) {
if (e.name === EMPTY_WRITE_ERROR_NAME) {
throw e;
}
// TODO(b/160843424): Collect UMA.
console.warn('Showing a picker due to', e);
return pickFileForFailedOverwrite(originalHandle.name, e.name, overwrite);
}
});
/**
* Shows a file picker and redirects a failed OverwriteFileMessage to the chosen
* file. Updates app state and rebinds file tokens if the write is successful.
* @param {string} fileName
* @param {string} errorName
* @param {!OverwriteFileMessage} overwrite
* @return {!Promise<!OverwriteViaFilePickerResponse>}
*/
async function pickFileForFailedOverwrite(fileName, errorName, overwrite) {
const fileHandle = await pickWritableFile(
fileName, overwrite.blob.type, overwrite.token, []);
await saveBlobToFile(fileHandle, overwrite.blob);
// Success. Replace the old handle.
tokenMap.set(overwrite.token, fileHandle);
const entry = currentFiles.find(i => i.token === overwrite.token);
if (entry) {
entry.handle = fileHandle;
}
return {renamedTo: fileHandle.name, errorName};
}
guestMessagePipe.registerHandler(Message.DELETE_FILE, async (message) => {
const deleteMsg = /** @type {!DeleteFileMessage} */ (message);
const {handle, directory} =
assertFileAndDirectoryMutable(deleteMsg.token, 'Delete');
if (!(await isHandleInCurrentDirectory(handle))) {
// removeEntry() silently "succeeds" in this case, but that gives poor UX.
console.warn(`"${handle.name}" not found in the last opened folder.`);
const error = new Error('Ignoring delete request: file not found');
error.name = 'NotFoundError';
throw error;
}
await directory.removeEntry(handle.name);
// Remove the file that was deleted.
currentFiles.splice(entryIndex, 1);
// Attempts to load the file to the right which is at now at
// `currentFiles[entryIndex]`, where `entryIndex` was previously the index of
// the deleted file.
await advance(0);
});
/** Handler to rename the currently focused file. */
guestMessagePipe.registerHandler(Message.RENAME_FILE, async (message) => {
const renameMsg = /** @type {!RenameFileMessage} */ (message);
const {handle, directory} =
assertFileAndDirectoryMutable(renameMsg.token, 'Rename');
if (await filenameExistsInCurrentDirectory(renameMsg.newFilename)) {
return {renameResult: RenameResult.FILE_EXISTS};
}
const originalFile = await maybeGetFileFromFileHandle(handle);
let originalFileIndex =
currentFiles.findIndex(fd => fd.token === renameMsg.token);
if (!originalFile || originalFileIndex < 0) {
return {renameResult: RenameResult.FILE_NO_LONGER_IN_LAST_OPENED_DIRECTORY};
}
const renamedFileHandle =
await directory.getFileHandle(renameMsg.newFilename, {create: true});
// Copy file data over to the new file.
const writer = await renamedFileHandle.createWritable();
const sink = /** @type {!WritableStream<*>} */ (writer);
const source =
/** @type {{stream: function(): !ReadableStream}} */ (originalFile);
await source.stream().pipeTo(sink);
// Remove the old file since the new file has all the data & the new name.
// Note even though removing an entry that doesn't exist is considered
// success, we first check `handle` is the same as the handle for the file
// with that filename in the `currentDirectoryHandle`.
if (await isHandleInCurrentDirectory(handle)) {
await directory.removeEntry(originalFile.name);
}
// Replace the old file in our internal representation. There is no harm using
// the old file's token since the old file is removed.
tokenMap.set(renameMsg.token, renamedFileHandle);
// Remove the entry for `originalFile` in current files, replace it with a
// FileDescriptor for the renamed file.
// Ensure the file is still in `currentFiles` after all the above `awaits`. If
// missing it means either new files have loaded (or tried to), see
// b/164985809.
originalFileIndex =
currentFiles.findIndex(fd => fd.token === renameMsg.token);
if (originalFileIndex < 0) {
// Can't navigate to the renamed file so don't add it to `currentFiles`.
return {renameResult: RenameResult.SUCCESS};
}
currentFiles.splice(originalFileIndex, 1, {
token: renameMsg.token,
file: null,
handle: renamedFileHandle,
inCurrentDirectory: true
});
return {renameResult: RenameResult.SUCCESS};
});
guestMessagePipe.registerHandler(Message.NAVIGATE, async (message) => {
const navigate = /** @type {!NavigateMessage} */ (message);
await advance(navigate.direction, navigate.currentFileToken);
});
guestMessagePipe.registerHandler(Message.REQUEST_SAVE_FILE, async (message) => {
const {suggestedName, mimeType, startInToken, accept} =
/** @type {!RequestSaveFileMessage} */ (message);
const handle =
await pickWritableFile(suggestedName, mimeType, startInToken, accept);
/** @type {!RequestSaveFileResponse} */
const response = {
pickedFileContext: {
token: generateToken(handle),
file: assertCast(await handle.getFile()),
name: handle.name,
error: '',
canDelete: false,
canRename: false,
}
};
return response;
});
guestMessagePipe.registerHandler(Message.SAVE_AS, async (message) => {
const {blob, oldFileToken, pickedFileToken} =
/** @type {!SaveAsMessage} */ (message);
const oldFileDescriptor = currentFiles.find(fd => fd.token === oldFileToken);
/** @type {!FileDescriptor} */
const pickedFileDescriptor = {
// We silently take over the old file's file descriptor by taking its token,
// note we can be passed an undefined token if the file we are saving was
// dragged into the media app.
token: oldFileToken || tokenGenerator.next().value,
file: null,
handle: tokenMap.get(pickedFileToken)
};
const oldFileIndex = currentFiles.findIndex(fd => fd.token === oldFileToken);
tokenMap.set(pickedFileDescriptor.token, pickedFileDescriptor.handle);
// Give the old file a new token, if we couldn't find the old file we assume
// its been deleted (or pasted/dragged into the media app) and skip this
// step.
if (oldFileDescriptor) {
oldFileDescriptor.token = generateToken(oldFileDescriptor.handle);
}
try {
// Note `pickedFileHandle` could be the same as a `FileSystemFileHandle`
// that exists in `tokenMap`. Possibly even the `File` currently open. But
// that's OK. E.g. the next overwrite-file request will just invoke
// `saveBlobToFile` in the same way.
await saveBlobToFile(pickedFileDescriptor.handle, blob);
} catch (/** @type {!DOMException} */ e) {
// If something went wrong revert the token back to its original
// owner so future file actions function correctly.
if (oldFileDescriptor && oldFileToken) {
oldFileDescriptor.token = oldFileToken;
tokenMap.set(oldFileToken, oldFileDescriptor.handle);
}
throw e;
}
// Note: oldFileIndex may be `-1` here which causes the new file to be added
// to the start of the array, this is WAI.
currentFiles.splice(oldFileIndex + 1, 0, pickedFileDescriptor);
// Silently update entry index without triggering a reload of the media app.
entryIndex = oldFileIndex + 1;
/** @type {!SaveAsResponse} */
const response = {newFilename: pickedFileDescriptor.handle.name};
return response;
});
guestMessagePipe.registerHandler(Message.OPEN_FILE, async () => {
const [handle] = await window.showOpenFilePicker({multiple: false});
/** @type {!FileDescriptor} */
const fileDescriptor = {
token: generateToken(handle),
file: null,
handle: handle,
inCurrentDirectory: false
};
currentFiles.splice(entryIndex + 1, 0, fileDescriptor);
advance(1);
});
guestMessagePipe.registerHandler(Message.OPEN_FILES_WITH_PICKER, async (m) => {
const {startInToken, accept} = /** @type {!OpenFilesWithPickerMessage} */ (m);
const acceptTypes = accept.map(k => OPEN_ACCEPT_ARGS[k]).filter(a => !!a);
/** @type {!FilePickerOptions|DraftFilePickerOptions} */
const options = {multiple: true};
if (startInToken) {
options.startIn = fileHandleForToken(startInToken);
}
if (acceptTypes.length > 0) {
options.excludeAcceptAllOption = true;
options.types = acceptTypes;
}
const handles = await window.showOpenFilePicker(options);
/** @type {!Array<!FileDescriptor>} */
const newDescriptors = [];
for (const handle of handles) {
newDescriptors.push({
token: generateToken(handle),
file: null,
handle: handle,
inCurrentDirectory: false
});
}
if (newDescriptors.length === 0) {
// Be defensive against the file picker returning an empty array rather than
// throwing an abort exception. Or any filtering we may introduce.
return;
}
// Perform a full "relaunch": replace everything and set focus to index 0.
currentFiles.splice(0, currentFiles.length, ...newDescriptors);
entryIndex = 0;
await sendSnapshotToGuest([...currentFiles], ++globalLaunchNumber);
});
guestMessagePipe.registerHandler(Message.OPEN_ALLOWED_FILE, async (message) => {
const {fileToken} = /** @type {!OpenAllowedFileMessage} */ (message);
const handle = fileHandleForToken(fileToken);
/** @type {!OpenAllowedFileResponse} */
const response = {file: (await getFileFromHandle(handle)).file};
return response;
});
/**
* Shows a file picker to get a writable file.
* @param {string} suggestedName
* @param {string} mimeType
* @param {number} startInToken,
* @param {!Array<string>} accept
* @return {!Promise<!FileSystemFileHandle>}
*/
function pickWritableFile(suggestedName, mimeType, startInToken, accept) {
const JPG_EXTENSIONS =
['.jpg', '.jpeg', '.jpe', '.jfif', '.jif', '.jfi', '.pjpeg', '.pjp'];
const ACCEPT_ARGS = {
'JPG': {description: 'JPG', accept: {'image/jpeg': JPG_EXTENSIONS}},
'PNG': {description: 'PNG', accept: {'image/png': ['.png']}},
'WEBP': {description: 'WEBP', accept: {'image/webp': ['.webp']}},
'PDF': {description: 'PDF', accept: {'application/pdf': ['.pdf']}},
};
const acceptTypes = accept.map(k => ACCEPT_ARGS[k]).filter(a => !!a);
/** @type {!FilePickerOptions|DraftFilePickerOptions} */
const options = {
suggestedName,
};
if (startInToken) {
options.startIn = fileHandleForToken(startInToken);
}
if (acceptTypes.length > 0) {
options.excludeAcceptAllOption = true;
options.types = acceptTypes;
} else {
// Search for the mimeType, and add a single entry. If none is found, the
// file picker is left "unconfigured"; with just "all files".
for (const a of Object.values(ACCEPT_ARGS)) {
if (a.accept[mimeType]) {
options.excludeAcceptAllOption = true;
options.types = [a];
}
}
}
// This may throw an error, but we can handle and recover from it on the
// unprivileged side.
return window.showSaveFilePicker(options);
}
/**
* Generator instance for unguessable tokens.
* @suppress {reportUnknownTypes} Typing of yield is broken (b/142881197).
* @type {!Generator<number>}
*/
const tokenGenerator = (function*() {
// To use the regular number type, tokens must stay below
// Number.MAX_SAFE_INTEGER (2^53). So stick with ~33 bits. Note we can not
// request more than 64kBytes from crypto.getRandomValues() at a time.
const randomBuffer = new Uint32Array(1000);
while (true) {
assertCast(crypto).getRandomValues(randomBuffer);
for (let i = 0; i < randomBuffer.length; ++i) {
const token = randomBuffer[i];
// Disallow "0" as a token.
if (token && !tokenMap.has(token)) {
yield Number(token);
}
}
}
})();
/**
* Generate a file token, and persist the mapping to `handle`.
* @param {!FileSystemFileHandle} handle
* @return {number}
*/
function generateToken(handle) {
const token = tokenGenerator.next().value;
tokenMap.set(token, handle);
return token;
}
/**
* Return the mimetype of a file given it's filename. Returns null if the
* mimetype could not be determined or if the file does not have a extension.
* TODO(b/178986064): Remove this once we have a file system access metadata
* api.
* @param {string} filename
* @return {?string}
*/
function getMimeTypeFromFilename(filename) {
// This file extension to mime type map is adapted from
// https://source.chromium.org/chromium/chromium/src/+/main:net/base/mime_util.cc;l=147;drc=51373c4ea13372d7711c59d9929b0be5d468633e
const mapping = {
'avif': 'image/avif',
'crx': 'application/x-chrome-extension',
'css': 'text/css',
'flac': 'audio/flac',
'gif': 'image/gif',
'htm': 'text/html',
'html': 'text/html',
'jpeg': 'image/jpeg',
'jpg': 'image/jpeg',
'js': 'text/javascript',
'm4a': 'audio/x-m4a',
'm4v': 'video/mp4',
'mht': 'multipart/related',
'mhtml': 'multipart/related',
'mjs': 'text/javascript',
'mp3': 'audio/mpeg',
'mp4': 'video/mp4',
'oga': 'audio/ogg',
'ogg': 'audio/ogg',
'ogm': 'video/ogg',
'ogv': 'video/ogg',
'opus': 'audio/ogg',
'png': 'image/png',
'shtm': 'text/html',
'shtml': 'text/html',
'wasm': 'application/wasm',
'wav': 'audio/wav',
'webm': 'video/webm',
'webp': 'image/webp',
'xht': 'application/xhtml+xml',
'xhtm': 'application/xhtml+xml',
'xhtml': 'application/xhtml+xml',
'xml': 'text/xml',
'epub': 'application/epub+zip',
'woff': 'application/font-woff',
'gz': 'application/gzip',
'tgz': 'application/gzip',
'json': 'application/json',
'bin': 'application/octet-stream',
'exe': 'application/octet-stream',
'com': 'application/octet-stream',
'pdf': 'application/pdf',
'p7m': 'application/pkcs7-mime',
'p7c': 'application/pkcs7-mime',
'p7z': 'application/pkcs7-mime',
'p7s': 'application/pkcs7-signature',
'ps': 'application/postscript',
'eps': 'application/postscript',
'ai': 'application/postscript',
'rdf': 'application/rdf+xml',
'rss': 'application/rss+xml',
'apk': 'application/vnd.android.package-archive',
'xul': 'application/vnd.mozilla.xul+xml',
'xls': 'application/vnd.ms-excel',
'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'zip': 'application/zip',
'weba': 'audio/webm',
'bmp': 'image/bmp',
'jfif': 'image/jpeg',
'pjpeg': 'image/jpeg',
'pjp': 'image/jpeg',
'svg': 'image/svg+xml',
'svgz': 'image/svg+xml',
'tiff': 'image/tiff',
'tif': 'image/tiff',
'ico': 'image/vnd.microsoft.icon',
'eml': 'message/rfc822',
'ics': 'text/calendar',
'ehtml': 'text/html',
'txt': 'text/plain',
'text': 'text/plain',
'sh': 'text/x-sh',
'xsl': 'text/xml',
'xbl': 'text/xml',
'xslt': 'text/xml',
'mpeg': 'video/mpeg',
'mpg': 'video/mpeg',
// Add more video file types. These are not web-supported types, but are
// supported on ChromeOS, and have file handlers in media_web_app_info.cc.
'mkv': 'video/x-matroska',
'3gp': 'video/3gpp',
'mov': 'video/quicktime',
'avi': 'video/x-msvideo',
'mpeg4': 'video/mp4',
'mpg4': 'video/mp4',
};
const fileParts = filename.split('.');
if (fileParts.length < 2) {
return null;
}
const extension = fileParts[fileParts.length - 1].toLowerCase();
/** @type {(string|undefined)} */
const mimeType = mapping[extension];
return mimeType !== undefined ? mimeType : null;
}
/**
* Returns the `FileSystemFileHandle` for the given `token`. This is
* "guaranteed" to succeed: tokens are only generated once a file handle has
* been successfully opened at least once (and determined to be "related"). The
* handle doesn't expire, but file system operations may fail later on.
* One corner case, however, is when the initial file open fails and the token
* gets replaced by `-1`. File operations all need to fail in that case.
* @param {number} token
* @return {!FileSystemFileHandle}
*/
function fileHandleForToken(token) {
const handle = tokenMap.get(token);
if (!handle) {
throw new DOMException(`No handle for token(${token})`, 'NotFoundError');
}
return handle;
}
/**
* Saves the provided blob the provided fileHandle. Assumes the handle is
* writable.
* @param {!FileSystemFileHandle} handle
* @param {!Blob} data
* @return {!Promise<undefined>}
*/
async function saveBlobToFile(handle, data) {
if (data.size === 0) {
// Bugs or error states in the app could cause an unexpected write of zero
// bytes to a file, which could cause data loss. Reject it here.
const error = new Error('saveBlobToFile(): Refusing to write zero bytes.');
error.name = EMPTY_WRITE_ERROR_NAME;
throw error;
}
const writer = await handle.createWritable();
await writer.write(data);
await writer.truncate(data.size);
await writer.close();
}
/**
* Warns if a given exception is "uncommon". That is, one that the guest might
* not provide UX for and should be dumped to console to give additional
* context.
* @param {!DOMException} e
* @param {string} fileName
*/
function warnIfUncommon(e, fileName) {
// Errors we expect to be thrown in normal operation.
const commonErrors = ['NotFoundError', 'NotAllowedError', 'NotAFile'];
if (commonErrors.includes(e.name)) {
return;
}
console.warn(`Unexpected ${e.name} on ${fileName}: ${e.message}`);
}
/**
* If `fd.file` is null, re-opens the file handle in `fd`.
* @param {!FileDescriptor} fd
*/
async function refreshFile(fd) {
if (fd.file) {
return;
}
fd.lastError = '';
try {
fd.file = (await getFileFromHandle(fd.handle)).file;
} catch (/** @type {!DOMException} */ e) {
fd.lastError = e.name;
// A failure here is only a problem for the "current" file (and that needs
// to be handled in the unprivileged context), so ignore known errors.
warnIfUncommon(e, fd.handle.name);
}
}
/**
* Loads the current file list into the guest.
* @return {!Promise<undefined>}
*/
async function sendFilesToGuest() {
return sendSnapshotToGuest(
[...currentFiles], globalLaunchNumber); // Shallow copy.
}
/**
* Converts a file descriptor from `currentFiles` into a `FileContext` used by
* the LoadFilesMessage. Closure forgets that some fields may be missing without
* naming the type explicitly on the signature here.
* @param {!FileDescriptor} fd
* @return {!FileContext}
*/
function fileDescriptorToFileContext(fd) {
// TODO(b/163285659): Properly detect files that can't be renamed/deleted.
return {
token: fd.token,
file: fd.file,
name: fd.handle.name,
error: fd.lastError || '',
canDelete: fd.inCurrentDirectory || false,
canRename: fd.inCurrentDirectory || false,
};
}
/**
* Loads the provided file list into the guest.
* Note: code paths can defer loads i.e. `launchWithDirectory()` increment
* `globalLaunchNumber` to ensure their deferred load is still relevant when it
* finishes processing. Other code paths that call `sendSnapshotToGuest()` don't
* have to.
* @param {!Array<!FileDescriptor>} snapshot
* @param {number} localLaunchNumber
* @param {boolean=} extraFiles
* @return {!Promise<undefined>}
*/
async function sendSnapshotToGuest(
snapshot, localLaunchNumber, extraFiles = false) {
const focusIndex = entryIndex;
// Attempt to reopen the focus file only. In future we might also open
// "nearby" files for preloading. However, reopening *all* files on every
// navigation attempt to verify they can still be navigated to adds noticeable
// lag in large directories.
let targetIndex = -1;
if (focusIndex >= 0 && focusIndex < snapshot.length) {
targetIndex = focusIndex;
} else if (snapshot.length !== 0) {
targetIndex = 0;
}
if (targetIndex >= 0) {
const descriptor = snapshot[targetIndex];
await refreshFile(descriptor);
await refreshLoadRequiredAssociatedFiles(
snapshot, descriptor.handle.name, extraFiles);
if (extraFiles) {
snapshot.shift();
}
}
if (localLaunchNumber !== globalLaunchNumber) {
return;
}
/** @type {!LoadFilesMessage} */
const loadFilesMessage = {
currentFileIndex: focusIndex,
// Handle can't be passed through a message pipe.
files: snapshot.map(fileDescriptorToFileContext)
};
// Clear handles to the open files in the privileged context so they are
// refreshed on a navigation request. The refcount to the File will be alive
// in the postMessage object until the guest takes its own reference.
for (const fd of snapshot) {
fd.file = null;
}
await iframeReady;
if (extraFiles) {
await guestMessagePipe.sendMessage(
Message.LOAD_EXTRA_FILES, loadFilesMessage);
} else {
await guestMessagePipe.sendMessage(Message.LOAD_FILES, loadFilesMessage);
}
}
/**
* Throws an error if the file or directory handles don't exist or the token for
* the file to be mutated is incorrect.
* @param {number} editFileToken
* @param {string} operation
* @return {{handle: !FileSystemFileHandle, directory:
* !FileSystemDirectoryHandle}}
*/
function assertFileAndDirectoryMutable(editFileToken, operation) {
if (!currentDirectoryHandle) {
throw new Error(`${operation} failed. File without launch directory.`);
}
return {
handle: fileHandleForToken(editFileToken),
directory: currentDirectoryHandle
};
}
/**
* Returns whether `handle` is in `currentDirectoryHandle`. Prevents mutating a
* file that doesn't exist.
* @param {!FileSystemFileHandle} handle
* @return {!Promise<boolean>}
*/
async function isHandleInCurrentDirectory(handle) {
/** @type {?File} */
const file = await maybeGetFileFromFileHandle(handle);
// If we were unable to get a file from the handle it must not be in the
// current directory anymore.
if (!file) {
return false;
}
// It's unclear if getFile will always give us a NotFoundError if the file has
// been moved as it's not explicitly stated in the File System Access API
// spec. As such we perform an additional check here to make sure the file
// returned by the handle is in fact in the current directory.
// TODO(b/172628918): Remove this once we have more assurances getFile() does
// the right thing.
const currentFilename = file.name;
const fileHandle = await getFileHandleFromCurrentDirectory(currentFilename);
return fileHandle ? fileHandle.isSameEntry(handle) : false;
}
/**
* Returns if a`filename` exists in `currentDirectoryHandle`.
* @param {string} filename
* @return {!Promise<boolean>}
*/
async function filenameExistsInCurrentDirectory(filename) {
return (await getFileHandleFromCurrentDirectory(filename, true)) !== null;
}
/**
* Returns the `FileSystemFileHandle` for `filename` if it exists in the current
* directory, otherwise null.
* @param {string} filename
* @param {boolean=} suppressError
* @return {!Promise<!FileSystemHandle|null>}
*/
async function getFileHandleFromCurrentDirectory(
filename, suppressError = false) {
if (!currentDirectoryHandle) {
return null;
}
try {
return (
await currentDirectoryHandle.getFileHandle(filename, {create: false}));
} catch (/** @type {!DOMException|!Error} */ e) {
if (!suppressError) {
// Some filenames (e.g. "thumbs.db") can't be opened (or deleted) by
// filename. TypeError doesn't give a good error message in the app, so
// convert to a new Error.
if (e.name === 'TypeError' && e.message === 'Name is not allowed.') {
console.warn(e); // Warn so a crash report is not generated.
throw new DOMException(
'File has a reserved name and can not be opened',
'InvalidModificationError');
}
console.error(e);
}
return null;
}
}
/**
* Gets a file from a handle received via the fileHandling API. Only handles
* expected to be files should be passed to this function. Throws a DOMException
* if opening the file fails - usually because the handle is stale.
* @param {?FileSystemHandle} fileSystemHandle
* @return {!Promise<{file: !File, handle: !FileSystemFileHandle}>}
*/
async function getFileFromHandle(fileSystemHandle) {
if (!fileSystemHandle || fileSystemHandle.kind !== 'file') {
// Invent our own exception for this corner case. It might happen if a file
// is deleted and replaced with a directory with the same name.
throw new DOMException('Not a file.', 'NotAFile');
}
const handle = /** @type {!FileSystemFileHandle} */ (fileSystemHandle);
const file = await handle.getFile(); // Note: throws DOMException.
return {file, handle};
}
/**
* Calls getFile on `handle` and gracefully returns null if it encounters a
* NotFoundError, which can happen if the file is no longer in the current
* directory due to being moved or deleted.
* @param {!FileSystemFileHandle} handle
* @return {!Promise<?File>}
*/
async function maybeGetFileFromFileHandle(handle) {
/** @type {?File} */
let file;
try {
file = await handle.getFile();
} catch (/** @type {!DOMException} */ e) {
// NotFoundError can be thrown if `handle` is no longer in the directory we
// have access to.
if (e.name === 'NotFoundError') {
file = null;
} else {
// Any other error is unexpected.
throw e;
}
}
return file;
}
/**
* Returns whether `fileName` is a file potentially containing subtitles.
* @param {string} fileName
* @return {boolean}
*/
function isSubtitleFile(fileName) {
return /\.vtt$/.test(fileName.toLowerCase());
}
/**
* Returns whether `fileName` is a file likely to be a video.
* @param {string} fileName
* @return {boolean}
*/
function isVideoFile(fileName) {
return /^video\//.test(getMimeTypeFromFilename(fileName));
}
/**
* Returns whether `fileName` is a file likely to be an image.
* @param {string} fileName
* @return {boolean}
*/
function isImageFile(fileName) {
// Detect RAW images, which often don't have a mime type set.
return /\.(arw|cr2|dng|nef|nrw|orf|raf|rw2)$/.test(fileName.toLowerCase()) ||
/^image\//.test(getMimeTypeFromFilename(fileName));
}
/**
* Returns whether `fileName` is a file likely to be audio.
* @param {string} fileName
* @return {boolean}
*/
function isAudioFile(fileName) {
return /^audio\//.test(getMimeTypeFromFilename(fileName));
}
/**
* Returns whether fileName is the filename for a video or image, or a related
* file type (e.g. video subtitles).
* @param {string} fileName
* @return {boolean}
*/
function isVideoOrImage(fileName) {
return isImageFile(fileName) || isVideoFile(fileName) ||
isSubtitleFile(fileName);
}
/**
* Returns whether `siblingFile` is related to `focusFile`. That is, whether
* they should be traversable from one another. Usually this means they share a
* similar (non-empty) MIME type.
* @param {!File} focusFile The file selected by the user.
* @param {string} siblingFileName Filename for a file in the same directory as
* `focusFile`.
* @return {boolean}
*/
function isFileRelated(focusFile, siblingFileName) {
const siblingFileType = getMimeTypeFromFilename(siblingFileName);
return focusFile.name === siblingFileName ||
(!!focusFile.type && !!siblingFileType &&
focusFile.type === siblingFileType) ||
(isVideoOrImage(focusFile.name) && isVideoOrImage(siblingFileName));
}
/**
* Enum like return value of `processOtherFilesInDirectory()`.
* @enum {number}
*/
const ProcessOtherFilesResult = {
// Newer load in progress, can abort loading these files.
ABORT: -2,
// The focusFile is missing, treat this as a normal load.
FOCUS_FILE_MISSING: -1,
// The focusFile is present, load these files as extra files.
FOCUS_FILE_RELEVANT: 0,
};
/**
* Loads related files the working directory to initialize file iteration
* according to the type of the opened file. If `globalLaunchNumber` changes
* (i.e. another launch occurs), this will abort early and not change
* `currentFiles`.
* @param {!FileSystemDirectoryHandle} directory
* @param {?File} focusFile
* @param {number} localLaunchNumber
* @return {!Promise<!ProcessOtherFilesResult>}
*/
async function processOtherFilesInDirectory(
directory, focusFile, localLaunchNumber) {
if (!focusFile || !focusFile.name) {
return ProcessOtherFilesResult.ABORT;
}
/** @type {!Array<!FileDescriptor>} */
let relatedFiles = [];
// TODO(b/158149714): Clear out old tokens as well? Care needs to be taken to
// ensure any file currently open with unsaved changes can still be saved.
try {
for await (const /** !FileSystemHandle */ handle of directory.values()) {
if (localLaunchNumber !== globalLaunchNumber) {
// Abort, another more up to date launch in progress.
return ProcessOtherFilesResult.ABORT;
}
if (handle.kind !== 'file') {
continue;
}
const fileHandle = /** @type {!FileSystemFileHandle} */ (handle);
// Only allow traversal of related file types.
if (isFileRelated(focusFile, handle.name)) {
// Note: The focus file will be processed here again but will be skipped
// over when added to `currentFiles`.
relatedFiles.push({
token: generateToken(fileHandle),
// This will get populated by refreshFile before the file gets opened.
file: null,
handle: fileHandle,
inCurrentDirectory: true,
});
}
}
} catch (e) {
console.warn(e, '(failed to traverse directory)');
// It's unlikely traversal can "resume", but try to continue with anything
// obtained so far.
}
if (currentFiles.length > 1) {
// Related files identified as required for the initial load must be removed
// so they don't appear in the file list twice.
const atLoadCurrentFiles = currentFiles.slice(1);
relatedFiles = relatedFiles.filter(
f => !atLoadCurrentFiles.find(c => c.handle.name === f.handle.name));
}
if (localLaunchNumber !== globalLaunchNumber) {
return ProcessOtherFilesResult.ABORT;
}
await sortFiles(relatedFiles);
const name = focusFile.name;
const focusIndex = relatedFiles.findIndex(i => i.handle.name === name);
entryIndex = 0;
if (focusIndex === -1) {
// The focus file is no longer there i.e. might have been deleted, should be
// missing from `currentFiles` as well.
currentFiles.push(...relatedFiles);
return ProcessOtherFilesResult.FOCUS_FILE_MISSING;
} else {
// Rotate the sorted files so focusIndex becomes index 0 such that we have
// [focus file, ...files larger, ...files smaller].
currentFiles.push(...relatedFiles.slice(focusIndex + 1));
currentFiles.push(...relatedFiles.slice(0, focusIndex));
return ProcessOtherFilesResult.FOCUS_FILE_RELEVANT;
}
}
/**
* Sorts the given `files` by `sortOrder`.
* @param {!Array<!FileDescriptor>} files
* @private
*/
async function sortFiles(files) {
if (sortOrder === SortOrder.NEWEST_FIRST) {
// If we are sorting by modification time we need to have the actual File
// object available.
for (const descriptor of files) {
// TODO(b/166210455): Remove this call to getFile as it may be slow for
// android files see b/172529567. Leaving it in at the moment since sort
// order is not set to NEWEST_FIRST in any production release and there is
// no way to get modified time without calling getFile.
try {
descriptor.file = (await getFileFromHandle(descriptor.handle)).file;
} catch (/** @type {!DOMException} */ e) {
warnIfUncommon(e, descriptor.handle.name);
}
}
}
// Iteration order is not guaranteed using `directory.entries()`, so we
// sort it afterwards by modification time to ensure a consistent and logical
// order. More recent (i.e. higher timestamp) files should appear first. In
// the case where timestamps are equal, the files will be sorted
// lexicographically according to their names.
files.sort((a, b) => {
if (sortOrder === SortOrder.NEWEST_FIRST) {
// Sort null files last if they racily appear.
if (!a.file && !b.file) {
return 0;
} else if (!b.file) {
return -1;
} else if (!a.file) {
return 1;
} else if (a.file.lastModified === b.file.lastModified) {
return a.file.name.localeCompare(b.file.name);
}
return b.file.lastModified - a.file.lastModified;
}
// Else default to lexicographical sort.
// Match the Intl.Collator params used for sorting in the files app in
// file_manager/common/js/util.js.
const direction = sortOrder === SortOrder.A_FIRST ? 1 : -1;
return direction *
a.handle.name.localeCompare(
b.handle.name, [],
{usage: 'sort', numeric: true, sensitivity: 'base'});
});
}
/**
* Loads related files in the working directory and sends them to the guest. If
* the focus file (currentFiles[0]) is no longer relevant i.e. is has been
* deleted, we load files as usual.
* @param {!FileSystemDirectoryHandle} directory
* @param {?File} focusFile
* @param {?FileSystemFileHandle} focusHandle
* @param {number} localLaunchNumber
*/
async function loadOtherRelatedFiles(
directory, focusFile, focusHandle, localLaunchNumber) {
const processResult = await processOtherFilesInDirectory(
directory, focusFile, localLaunchNumber);
if (localLaunchNumber !== globalLaunchNumber ||
processResult === ProcessOtherFilesResult.ABORT) {
return;
}
const shallowCopy = [...currentFiles];
// If the focus file is no longer relevant, loads files as normal.
await sendSnapshotToGuest(
shallowCopy, localLaunchNumber,
processResult === ProcessOtherFilesResult.FOCUS_FILE_RELEVANT);
}
/**
* Sets state for the files opened in the current directory.
* @param {!FileSystemDirectoryHandle} directory
* @param {{file: !File, handle: !FileSystemFileHandle}} focusFile
*/
function setCurrentDirectory(directory, focusFile) {
// Load currentFiles into the guest.
currentFiles.length = 0;
currentFiles.push({
token: generateToken(focusFile.handle),
file: focusFile.file,
handle: focusFile.handle,
inCurrentDirectory: true,
});
currentDirectoryHandle = directory;
entryIndex = 0;
}
/**
* Returns a filename associated with `focusFileName` that may be required to
* properly load the file. The file might not exist.
* TODO(b/175099007): Support multiple associated files.
* @param {string} focusFileName
* @return {string}
*/
function requiredAssociatedFileName(focusFileName) {
// Subtitles must be identified for the initial load to be properly attached.
if (!isVideoFile(focusFileName)) {
return '';
}
// To match the video player app, just look for `.vtt` until alternative
// heuristics are added inside the app layer. See b/175099007.
return focusFileName.replace(/\.[^\.]+$/, '.vtt');
}
/**
* Adds file handles for associated files to the set of launch files.
* @param {!FileSystemDirectoryHandle} directory
* @param {string} focusFileName
*/
async function detectLoadRequiredAssociatedFiles(directory, focusFileName) {
const vttFileName = requiredAssociatedFileName(focusFileName);
if (!vttFileName) {
return;
}
try {
const vttFileHandle = await directory.getFileHandle(vttFileName);
currentFiles.push({
token: generateToken(vttFileHandle),
file: null, // Will be set by `refreshLoadRequiredAssociatedFiles()`.
handle: vttFileHandle,
inCurrentDirectory: true,
});
} catch (e) {
// Do nothing if not found or not permitted.
}
}
/**
* Refreshes the File object for all file handles associated with the focus
* file.
* @param {!Array<!FileDescriptor>} snapshot
* @param {string} focusFileName
* @param {boolean} forExtraFilesMessage
*/
async function refreshLoadRequiredAssociatedFiles(
snapshot, focusFileName, forExtraFilesMessage) {
const vttFileName = requiredAssociatedFileName(focusFileName);
if (!vttFileName) {
return;
}
const index = snapshot.findIndex(d => d.handle.name === vttFileName);
if (index >= 0) {
await refreshFile(snapshot[index]);
// In the extra files message, it's necessary to remove the vtt file from
// the snapshot to avoid it being added again in the receiver.
if (forExtraFilesMessage) {
snapshot.splice(index, 1);
}
}
}
/**
* Launch the media app with the files in the provided directory, using `handle`
* as the initial launch entry.
* @param {!FileSystemDirectoryHandle} directory
* @param {!FileSystemHandle} handle
*/
async function launchWithDirectory(directory, handle) {
const localLaunchNumber = ++globalLaunchNumber;
let asFile;
try {
asFile = await getFileFromHandle(handle);
} catch (/** @type {!DOMException} */ e) {
console.warn(`${handle.name}: ${e.message}`);
sendSnapshotToGuest(
[{token: -1, file: null, handle, error: e.name}], localLaunchNumber);
return;
}
// Load currentFiles into the guest.
setCurrentDirectory(directory, asFile);
await detectLoadRequiredAssociatedFiles(directory, handle.name);
await sendSnapshotToGuest([...currentFiles], localLaunchNumber);
// The app is operable with the first file now.
// Process other files in directory.
// TODO(https://github.com/WICG/file-system-access/issues/215): Don't process
// other files if there is only 1 file which is already loaded by
// `sendSnapshotToGuest()` above.
await loadOtherRelatedFiles(
directory, asFile.file, asFile.handle, localLaunchNumber);
}
/**
* Launch the media app with the selected files.
* @param {!FileSystemDirectoryHandle} directory
* @param {!Array<?FileSystemHandle>} handles
*/
async function launchWithMultipleSelection(directory, handles) {
currentFiles.length = 0;
for (const handle of handles) {
if (handle && handle.kind === 'file') {
const fileHandle = /** @type {!FileSystemFileHandle} */ (handle);
currentFiles.push({
token: generateToken(fileHandle),
file: null, // Just let sendSnapshotToGuest() "refresh" it.
handle: fileHandle,
// TODO(b/163285659): Enable delete/rename for multi-select files.
});
}
}
await sortFiles(currentFiles);
entryIndex = currentFiles.length > 0 ? 0 : -1;
currentDirectoryHandle = directory;
await sendFilesToGuest();
}
/**
* Advance to another file.
*
* @param {number} direction How far to advance (e.g. +/-1).
* @param {number=} currentFileToken The token of the file that
* direction is in reference to. If unprovided it's assumed that
* currentFiles[entryIndex] is the current file.
*/
async function advance(direction, currentFileToken) {
let currIndex = entryIndex;
if (currentFileToken) {
const fileIndex =
currentFiles.findIndex(fd => fd.token === currentFileToken);
currIndex = fileIndex === -1 ? currIndex : fileIndex;
}
if (currentFiles.length) {
entryIndex = (currIndex + direction) % currentFiles.length;
if (entryIndex < 0) {
entryIndex += currentFiles.length;
}
} else {
entryIndex = -1;
}
await sendFilesToGuest();
}
/**
* The launchQueue consumer. This returns a promise to help tests, but the file
* handling API will ignore it.
* @param {?LaunchParams} params
* @return {!Promise<undefined>}
*/
async function launchConsumer(params) {
// The MediaApp sets `include_launch_directory = true` in its SystemAppInfo
// struct compiled into Chrome. That means files[0] is guaranteed to be a
// directory, with remaining launch files following it. Validate that this is
// true and abort the launch if is is not.
if (!params || !params.files || params.files.length < 2) {
console.error('Invalid launch (missing files): ', params);
return;
}
if (assertCast(params.files[0]).kind !== 'directory') {
console.error('Invalid launch: files[0] is not a directory: ', params);
return;
}
const directory =
/** @type {!FileSystemDirectoryHandle} */ (params.files[0]);
// With a single file selected, that file is the focus file. Otherwise, there
// is no inherent focus file.
const maybeFocusEntry = assertCast(params.files[1]);
// With a single file selected, launch with all files in the directory as
// navigation candidates. Otherwise, launch with all selected files (except
// the launch directory itself) as navigation candidates. The only exception
// to this is audio files, which we explicitly don't load the directory for.
if (params.files.length === 2 && !isAudioFile(maybeFocusEntry.name)) {
try {
await launchWithDirectory(directory, maybeFocusEntry);
} catch (e) {
console.error(e, '(launchWithDirectory aborted)');
}
} else {
try {
await launchWithMultipleSelection(directory, params.files.slice(1));
} catch (e) {
console.error(e, '(launchWithMultipleSelection aborted)');
}
}
}
/**
* Wrapper for the launch consumer to ensure it doesn't return a Promise, nor
* propagate exceptions. Tests will want to target `launchConsumer` directly so
* that they can properly await launch results.
* @param {?LaunchParams} params
*/
function wrappedLaunchConsumer(params) {
launchConsumer(params).catch(e => {
console.error(e, '(launch aborted)');
});
}
/**
* Installs the handler for launch files, if window.launchQueue is available.
*/
function installLaunchHandler() {
if (!window.launchQueue) {
console.error('FileHandling API missing.');
return;
}
window.launchQueue.setConsumer(wrappedLaunchConsumer);
}
installLaunchHandler();
// Make sure the guest frame has focus.
/** @type {!Element} */
const guest = assertCast(
document.querySelector('iframe[src^="chrome-untrusted://media-app"]'));
guest.addEventListener('load', () => {
guest.focus();
});
export const TEST_ONLY = {
Message,
SortOrder,
advance,
currentDirectoryHandle,
currentFiles,
fileHandleForToken,
globalLaunchNumber,
guestMessagePipe,
launchConsumer,
launchWithDirectory,
loadOtherRelatedFiles,
pickWritableFile,
processOtherFilesInDirectory,
sendFilesToGuest,
setCurrentDirectory,
sortOrder,
tokenGenerator,
tokenMap,
mediaAppPageHandler,
error_reporter,
getGlobalLaunchNumber: () => globalLaunchNumber,
incrementLaunchNumber: () => ++globalLaunchNumber,
setCurrentDirectoryHandle: d => {
currentDirectoryHandle = d;
},
setSortOrder: s => {
sortOrder = s;
},
getEntryIndex: () => entryIndex,
setEntryIndex: i => {
entryIndex = i;
},
};
// Small, auxiliary file that adds hooks to support test cases relying on the
// "real" app context (e.g. for stack traces).
import './app_context_test_support.js';
// Expose `advance()` for MediaAppIntegrationTest.FileOpenCanTraverseDirectory.
window['advance'] = advance;
| {
"content_hash": "a8bcb37aa30b550d8250d7b1b9b3b179",
"timestamp": "",
"source": "github",
"line_count": 1450,
"max_line_length": 380,
"avg_line_length": 34.33931034482759,
"alnum_prop": 0.6852908097686375,
"repo_name": "scheib/chromium",
"id": "b0e0d8e2141444da649106684820604e87cfce04",
"size": "49792",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "ash/webui/media_app_ui/resources/js/launch.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
/*global define*/
define([
'Core/defaultValue',
'Core/PrimitiveType',
'Renderer/Buffer',
'Renderer/BufferUsage',
'Renderer/ClearCommand',
'Renderer/DrawCommand',
'Renderer/RenderState',
'Renderer/ShaderProgram',
'Renderer/VertexArray'
], function(
defaultValue,
PrimitiveType,
Buffer,
BufferUsage,
ClearCommand,
DrawCommand,
RenderState,
ShaderProgram,
VertexArray) {
"use strict";
function renderFragment(context, fs, depth, clear) {
var vs = 'attribute vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }';
var sp = ShaderProgram.fromCache({
context : context,
vertexShaderSource : vs,
fragmentShaderSource : fs
});
depth = defaultValue(depth, 0.0);
var va = new VertexArray({
context : context,
attributes : [{
index : sp.vertexAttributes.position.index,
vertexBuffer : Buffer.createVertexBuffer({
context : context,
typedArray : new Float32Array([0.0, 0.0, depth, 1.0]),
usage : BufferUsage.STATIC_DRAW
}),
componentsPerAttribute : 4
}]
});
var rs = RenderState.fromCache({
depthTest : {
enabled : true
}
});
clear = defaultValue(clear, true);
if (clear) {
ClearCommand.ALL.execute(context);
expect(context.readPixels()).toEqual([0, 0, 0, 0]);
}
var command = new DrawCommand({
primitiveType : PrimitiveType.POINTS,
shaderProgram : sp,
vertexArray : va,
renderState : rs
});
command.execute(context);
sp = sp.destroy();
va = va.destroy();
return context.readPixels();
}
return renderFragment;
});
| {
"content_hash": "10af0c299afe59505ad5ef99503e9db5",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 104,
"avg_line_length": 27.945205479452056,
"alnum_prop": 0.5147058823529411,
"repo_name": "epifanio/CesiumWidget",
"id": "350d1aace909a047134397818e9e9e7a1445885a",
"size": "2040",
"binary": false,
"copies": "3",
"ref": "refs/heads/geojson",
"path": "CesiumWidget/static/CesiumWidget/cesium/Specs/renderFragment.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "653304"
},
{
"name": "Erlang",
"bytes": "2146"
},
{
"name": "GLSL",
"bytes": "157245"
},
{
"name": "HTML",
"bytes": "1237480"
},
{
"name": "JavaScript",
"bytes": "46372196"
},
{
"name": "Python",
"bytes": "5972"
},
{
"name": "Shell",
"bytes": "291"
}
],
"symlink_target": ""
} |
package com.mobgen.halo.android.framework.api;
import com.mobgen.halo.android.framework.mock.FrameworkMock;
import com.mobgen.halo.android.testing.HaloRobolectricTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static com.mobgen.halo.android.framework.mock.instrumentation.HaloFrameworkInstrument.givenAStorageConfig;
import static org.assertj.core.api.Java6Assertions.assertThat;
public class HaloStorageApiTest extends HaloRobolectricTest {
private HaloFramework mFramework;
private HaloStorageApi mStorage;
@Before
public void initialize() {
mFramework = FrameworkMock.createSameThreadFramework("myTestEndpoint");
mStorage = mFramework.createStorage(givenAStorageConfig());
}
@After
public void tearDown() {
}
@Test
public void thatCanGetPreferences(){
assertThat(mStorage.prefs()).isNotNull();
}
@Test
public void thatCanGetcontext(){
assertThat(mStorage.context()).isNotNull();
}
@Test
public void thatGetFramework(){
assertThat(mStorage.framework()).isEqualTo(mFramework);
}
} | {
"content_hash": "7684d46d02594eb9a59966e127ab2942",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 113,
"avg_line_length": 25.886363636363637,
"alnum_prop": 0.7366110623353819,
"repo_name": "mobgen/halo-android",
"id": "0edf8a4718355628bf82b4a4f37a1729759a69f6",
"size": "1139",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "sdk/halo-framework/src/test/java/com/mobgen/halo/android/framework/api/HaloStorageApiTest.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "30963"
},
{
"name": "Java",
"bytes": "2807330"
},
{
"name": "Python",
"bytes": "5143"
},
{
"name": "Shell",
"bytes": "2147"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace ApiPlatform\Doctrine\Odm\Metadata\Resource;
use ApiPlatform\Doctrine\Odm\State\CollectionProvider;
use ApiPlatform\Doctrine\Odm\State\ItemProvider;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\CollectionOperationInterface;
use ApiPlatform\Metadata\DeleteOperationInterface;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\Persistence\ManagerRegistry;
final class DoctrineMongoDbOdmResourceCollectionMetadataFactory implements ResourceMetadataCollectionFactoryInterface
{
public function __construct(private readonly ManagerRegistry $managerRegistry, private readonly ResourceMetadataCollectionFactoryInterface $decorated)
{
}
/**
* {@inheritDoc}
*/
public function create(string $resourceClass): ResourceMetadataCollection
{
$resourceMetadataCollection = $this->decorated->create($resourceClass);
/** @var ApiResource $resourceMetadata */
foreach ($resourceMetadataCollection as $i => $resourceMetadata) {
$operations = $resourceMetadata->getOperations();
if ($operations) {
/** @var Operation $operation */
foreach ($resourceMetadata->getOperations() as $operationName => $operation) {
if (!$this->managerRegistry->getManagerForClass($operation->getClass()) instanceof DocumentManager) {
continue;
}
$operations->add($operationName, $this->addDefaults($operation));
}
$resourceMetadata = $resourceMetadata->withOperations($operations);
}
$graphQlOperations = $resourceMetadata->getGraphQlOperations();
if ($graphQlOperations) {
foreach ($graphQlOperations as $operationName => $graphQlOperation) {
if (!$this->managerRegistry->getManagerForClass($graphQlOperation->getClass()) instanceof DocumentManager) {
continue;
}
$graphQlOperations[$operationName] = $this->addDefaults($graphQlOperation);
}
$resourceMetadata = $resourceMetadata->withGraphQlOperations($graphQlOperations);
}
$resourceMetadataCollection[$i] = $resourceMetadata;
}
return $resourceMetadataCollection;
}
private function addDefaults(Operation $operation): Operation
{
if (null === $operation->getProvider()) {
$operation = $operation->withProvider($this->getProvider($operation));
}
if (null === $operation->getProcessor()) {
$operation = $operation->withProcessor($this->getProcessor($operation));
}
return $operation;
}
private function getProvider(Operation $operation): string
{
if ($operation instanceof CollectionOperationInterface) {
return CollectionProvider::class;
}
return ItemProvider::class;
}
private function getProcessor(Operation $operation): string
{
if ($operation instanceof DeleteOperationInterface) {
return 'api_platform.doctrine_mongodb.odm.state.remove_processor';
}
return 'api_platform.doctrine_mongodb.odm.state.persist_processor';
}
}
| {
"content_hash": "a74b9235f8171be9a7c1e83aceb58ac3",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 154,
"avg_line_length": 35.23,
"alnum_prop": 0.6625035481124042,
"repo_name": "api-platform/core",
"id": "929f4d88e1b3ef222f6034e6c040df831e77a7aa",
"size": "3754",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "src/Doctrine/Odm/Metadata/Resource/DoctrineMongoDbOdmResourceCollectionMetadataFactory.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "15644"
},
{
"name": "Gherkin",
"bytes": "834758"
},
{
"name": "HTML",
"bytes": "2715"
},
{
"name": "JavaScript",
"bytes": "23790"
},
{
"name": "PHP",
"bytes": "4429809"
},
{
"name": "Shell",
"bytes": "4182"
},
{
"name": "Twig",
"bytes": "35787"
}
],
"symlink_target": ""
} |
<?php
namespace App\Models\Traits;
use InvalidArgumentException;
trait UserTrait
{
/**
* Checks if the user has a role by its name.
*
* @param string|array $name Role name or array of role names.
* @param bool $requireAll All roles in the array are required.
*
* @return bool
*/
public function hasRole($name, $requireAll = false)
{
if (is_array($name)) {
foreach ($name as $roleName) {
$hasRole = $this->hasRole($roleName);
if ($hasRole && !$requireAll) {
return true;
} elseif (!$hasRole && $requireAll) {
return false;
}
}
// If we've made it this far and $requireAll is FALSE, then NONE of the roles were found
// If we've made it this far and $requireAll is TRUE, then ALL of the roles were found.
// Return the value of $requireAll;
return $requireAll;
} elseif(is_string($name)) {
// foreach ($this->cachedRoles() as $role) {
// if ($role->name == $name) {
// return true;
// }
// }
return $this->roles->contains('name', $name);
}
return !! $name->intersect($this->roles)->count();
// return false;
}
/**
* Check if user has a permission by its name.
*
* @param string|array $permission Permission string or array of permissions.
* @param bool $requireAll All permissions in the array are required.
*
* @return bool
*/
public function can($permission, $requireAll = false)
{
if (is_array($permission)) {
foreach ($permission as $permName) {
$hasPerm = $this->can($permName);
if ($hasPerm && !$requireAll) {
return true;
} elseif (!$hasPerm && $requireAll) {
return false;
}
}
// If we've made it this far and $requireAll is FALSE, then NONE of the perms were found
// If we've made it this far and $requireAll is TRUE, then ALL of the perms were found.
// Return the value of $requireAll;
return $requireAll;
} elseif(is_string($permission)) {
foreach ($this->roles as $role) {
// Validate against the Permission table
// foreach ($role->cachedPermissions() as $perm) {
// if (str_is( $permission, $perm->name) ) {
// return true;
// }
// }
return $role->permissions->contains('name', $permission);
}
}
// return !! $role->intersect($this->roles)->count();
return false;
}
/**
* Alias to eloquent many-to-many relation's attach() method.
*
* @param mixed $role
*/
public function attachRole($role)
{
if(is_object($role)) {
$role = $role->getKey();
}
if(is_array($role)) {
$role = $role['id'];
}
$this->roles()->attach($role);
}
/**
* Alias to eloquent many-to-many relation's detach() method.
*
* @param mixed $role
*/
public function detachRole($role)
{
if (is_object($role)) {
$role = $role->getKey();
}
if (is_array($role)) {
$role = $role['id'];
}
$this->roles()->detach($role);
}
/**
* Attach multiple roles to a user
*
* @param mixed $roles
*/
public function attachRoles($roles)
{
foreach ($roles as $role) {
$this->attachRole($role);
}
}
/**
* Detach multiple roles from a user
*
* @param mixed $roles
*/
public function detachRoles($roles=null)
{
if (!$roles) $roles = $this->roles()->get();
foreach ($roles as $role) {
$this->detachRole($role);
}
}
} | {
"content_hash": "687a3de15b152f55c200ca759acfc1cb",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 100,
"avg_line_length": 27.46,
"alnum_prop": 0.4816703083272639,
"repo_name": "jaumesala/opendata-maps",
"id": "6cbe7f7f1e5d27be0e03153bd0397dd867fdaee8",
"size": "4119",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/Models/Traits/UserTrait.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "553"
},
{
"name": "CSS",
"bytes": "56292"
},
{
"name": "HTML",
"bytes": "212158"
},
{
"name": "JavaScript",
"bytes": "37143"
},
{
"name": "PHP",
"bytes": "223365"
}
],
"symlink_target": ""
} |
@interface GVUserDefaults (TJSGlobalProperties)
// 当前登录名
@property (nonatomic, copy) NSString *loginName;
// token
@property (nonatomic, copy) NSString *token;
@end
| {
"content_hash": "880a879f903c6a90efa07f98c6a34d86",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 48,
"avg_line_length": 15.454545454545455,
"alnum_prop": 0.7470588235294118,
"repo_name": "BaoSeed/TianFuYun",
"id": "c2347867c548600b2f87e0f1930e42a7f87a8895",
"size": "368",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ios/TianJiCloud/Service/GVUserDefaults/GVUserDefaults+TJSGlobalProperties.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "3694"
},
{
"name": "CSS",
"bytes": "75311"
},
{
"name": "HTML",
"bytes": "310734"
},
{
"name": "JavaScript",
"bytes": "7725"
},
{
"name": "Objective-C",
"bytes": "4846839"
},
{
"name": "Ruby",
"bytes": "1408"
},
{
"name": "Shell",
"bytes": "24921"
}
],
"symlink_target": ""
} |
<!--
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.
-->
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<link rel="stylesheet" type="text/css" href="../stylesheets/style.css">
<title>CvsTagDiff Task</title>
</head>
<body>
<h2><a name="cvstagdiff">CvsTagDiff</a></h2>
<h3>Description</h3>
<p>Generates an XML-formatted report file of the changes between two tags or dates recorded in a
<a href="http://www.nongnu.org/cvs/" target="_top">CVS</a> repository. </p>
<p><b>Important:</b> This task needs "<code>cvs</code>" on the path. If it isn't, you will get
an error (such as error <code>2</code> on windows). If <code><cvs></code> doesn't work, try to execute <code>cvs.exe</code>
from the command line in the target directory in which you are working.
Also note that this task assumes that the cvs exceutable is compatible
with the Unix version from cvshome.org, this is not completely true
for certain other cvs clients - like CVSNT for example - and some
operation may fail when using such an incompatible client.
</p>
<h3>Parameters</h3>
<table border="1" cellpadding="2" cellspacing="0">
<tr>
<td valign="top"><b>Attribute</b></td>
<td valign="top"><b>Description</b></td>
<td align="center" valign="top"><b>Required</b></td>
</tr>
<tr>
<td valign="top">startTag</td>
<td valign="top">The earliest tag from which diffs are to be
included in the report.</td>
<td align="center" valign="top" rowspan="2">exactly one of the two.</td>
</tr>
<tr>
<td valign="top">startDate</td>
<td valign="top">The earliest date from which diffs are to be
included in the report.<br>
accepts all formats accepted by the cvs command for -D date_spec arguments</td>
</tr>
<tr>
<td valign="top">endTag</td>
<td valign="top">The latest tag from which diffs are to be
included in the report.</td>
<td align="center" valign="top" rowspan="2">exactly one of the two.</td>
</tr>
<tr>
<td valign="top">endDate</td>
<td valign="top">The latest date from which diffs are to be
included in the report.<br>
accepts all formats accepted by the cvs command for -D date_spec arguments</td>
</tr>
<tr>
<td valign="top">destfile</td>
<td valign="top">The file in which to write the diff report.</td>
<td align="center" valign="top">Yes</td>
</tr>
<tr>
<td valign="top">ignoreRemoved</td>
<td valign="top">When set to true, the report will not include any
removed files. <em>Since Apache Ant 1.8.0</em></td>
<td align="center" valign="top">No, defaults to false.</td>
</table>
<h3>Parameters inherited from the <code>cvs</code> task</h3>
<table border="1" cellpadding="2" cellspacing="0">
<tr>
<td valign="top"><b>Attribute</b></td>
<td valign="top"><b>Description</b></td>
<td align="center" valign="top"><b>Required</b></td>
</tr>
<tr>
<td valign="top">compression</td>
<td valign="top"><code>true</code>, <code>false</code>, or the number 1-9 (corresponding to possible values for CVS <code>-z#</code> argument). Any other value is treated as false</td>
<td align="center" valign="top">No. Defaults to no compression. if passed <code>true</code>, level 3 compression is assumed.</td>
</tr>
<tr>
<td valign="top">cvsRoot</td>
<td valign="top">the CVSROOT variable.</td>
<td align="center" valign="top">No</td>
</tr>
<tr>
<td valign="top">cvsRsh</td>
<td valign="top">the CVS_RSH variable.</td>
<td align="center" valign="top">No</td>
</tr>
<tr>
<td valign="top">package</td>
<td valign="top">the package/module to analyze.<br>
Since Ant 1.6
multiple packages separated by spaces are possible.
aliases corresponding to different modules are also possible
Use a nested <module> element if you want to specify a module with
spaces in its name.</td>
<td align="center" valign="top">No</td>
</tr>
<td align="center" valign="top">Yes</td>
</tr>
<tr>
<td valign="top">quiet</td>
<td valign="top">suppress informational messages.</td>
<td align="center" valign="top">No, default "false"</td>
</tr>
<tr>
<td valign="top">port</td>
<td valign="top">Port used by CVS to communicate with the server.</td>
<td align="center" valign="top">No, default port 2401.</td>
</tr>
<tr>
<td valign="top">passfile</td>
<td valign="top">Password file to read passwords from.</td>
<td align="center" valign="top">No, default file <code>~/.cvspass</code>.</td>
</tr>
<tr>
<td valign="top">failonerror</td>
<td valign="top">Stop the buildprocess if the command exits with a
returncode other than 0. Defaults to false</td>
<td align="center" valign="top">No</td>
</tr>
</table>
<h3>Parameters specified as nested elements</h3>
<h4>module</h4>
<p>Specifies a package/module to work on, unlike the package attribute
modules specified using this attribute can contain spaces in their
name.</p>
<table border="1" cellpadding="2" cellspacing="0">
<tr>
<td valign="top"><b>Attribute</b></td>
<td valign="top"><b>Description</b></td>
<td align="center" valign="top"><b>Required</b></td>
</tr>
<tr>
<td valign="top">name</td>
<td valign="top">The module's/package's name.</td>
<td align="center" valign="top">Yes.</td>
</tr>
</table>
<h3>Examples</h3>
<pre> <cvstagdiff cvsRoot=":pserver:[email protected]:/home/cvspublic"
destfile="tagdiff.xml"
package="ant"
startTag="ANT_14"
endTag="ANT_141"
/></pre>
<p>Generates a tagdiff report for all the changes that have been made
in the <code>ant</code> module between the tags <code>ANT_14</code> and <code>ANT_141</code>.
It writes these changes into the file <code>tagdiff.xml</code>.</p>
<pre> <cvstagdiff
destfile="tagdiff.xml"
package="ant"
startDate="2002-01-01"
endDate="2002-31-01"
/></pre>
<p>Generates a tagdiff report for all the changes that have been made
in the <code>ant</code> module in january 2002. In this example <code>cvsRoot</code>
has not been set. The current <code>cvsRoot</code> will be used (assuming the build is started
from a folder stored in <code>cvs</code>.
It writes these changes into the file <code>tagdiff.xml</code>.</p>
<pre> <cvstagdiff
destfile="tagdiff.xml"
package="ant jakarta-gump"
startDate="2003-01-01"
endDate="2003-31-01"
/></pre>
<p>Generates a tagdiff report for all the changes that have been made
in the <code>ant</code> and <code>jakarta-gump</code> modules in january 2003.
In this example <code>cvsRoot</code>
has not been set. The current <code>cvsRoot</code> will be used (assuming the build is started
from a folder stored in <code>cvs</code>.
It writes these changes into the file <code>tagdiff.xml</code>.</p>
<h4>Generate Report</h4>
<p>Ant includes a basic XSLT stylesheet that you can use to generate
a HTML report based on the xml output. The following example illustrates
how to generate a HTML report from the XML report.</p>
<pre>
<style in="tagdiff.xml"
out="tagdiff.html"
style="${ant.home}/etc/tagdiff.xsl">
<param name="title" expression="Ant Diff"/>
<param name="module" expression="ant"/>
<param name="cvsweb" expression="http://cvs.apache.org/viewcvs/"/>
</style>
</pre>
<h4>Output</h4>
<p>
The cvsroot and package attributes of the tagdiff element are new in ant 1.6.<br>
Notes on entry attributes :
<table border="1">
<tr><th>Attribute</th><th>Comment</th></tr>
<tr><td>name</td><td>when reporting on one package, the package name is removed from the output</td></tr>
<tr><td>revision</td><td>supplied for files which exist at the end of the reporting period</td></tr>
<tr><td>prevrevision</td><td>supplied for files which exist at the beginning of the reporting period.<br>
Old CVS servers do not supply it for deleted files. CVS 1.12.2 supplies it.</td></tr>
</table>
</p>
<pre>
<?xml version="1.0" encoding="UTF-8"?>
<tagdiff startTag="ANT_14" endTag="ANT_141"
cvsroot=":pserver:[email protected]:/home/cvspublic" package="ant">
<entry>
<file>
<name>src/main/org/apache/tools/ant/DirectoryScanner.java</name>
<revision>1.15.2.1</revision>
<prevrevision>1.15</prevrevision>
</file>
</entry>
</tagdiff>
</pre>
</body>
</html>
| {
"content_hash": "ee01edd36da2a415a3d4ba0269f336ec",
"timestamp": "",
"source": "github",
"line_count": 241,
"max_line_length": 188,
"avg_line_length": 40.75103734439834,
"alnum_prop": 0.6499338152937583,
"repo_name": "mastersmind/BB10-WebWorks-Community-Samples",
"id": "625f43dfa94537223c73290f0154e0d3bd333c5c",
"size": "9821",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "Ant-Build-Script/tools/apache-ant-1.8.2/docs/manual/Tasks/cvstagdiff.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="@layout/include_frag_bottom" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_marginBottom="@dimen/content_margin_bottom"
android:background="@color/grey_line"
android:orientation="vertical">
<!--<include layout="@layout/header_physical" />-->
<LinearLayout style="@style/input_layout_out">
<TextView
style="@style/input_txt_title"
android:text="血压" />
<LinearLayout style="@style/input_layout_in">
<TextView
android:id="@+id/et_physical2_1_1"
style="@style/input_txt"
android:textSize="16sp" />
<TextView
style="@style/input_txt_dost"
android:layout_weight="0.2"
android:text="/" />
<TextView
android:id="@+id/et_physical2_1_2"
style="@style/input_txt"
android:textSize="16sp" />
<TextView
style="@style/input_txt_dost"
android:layout_weight="1.8"
android:text="mmHg" />
</LinearLayout>
<TextView
style="@style/input_txt_title"
android:text="心率" />
<LinearLayout style="@style/input_layout_in">
<TextView
android:id="@+id/et_physical2_2"
style="@style/input_txt" />
<TextView
style="@style/input_txt_dost"
android:text="次/分" />
</LinearLayout>
<TextView
style="@style/input_txt_title"
android:text="节律" />
<LinearLayout style="@style/input_layout_in_nodimen">
<com.shwootide.metabolictreat.widget.nicespinner.NiceSpinner
android:id="@+id/ns_physical2_3"
style="@style/input_spinner_full"
app:niceEntries="@array/DMjielv" />
</LinearLayout>
</LinearLayout>
<View style="@style/LineGreyHorizontal" />
<LinearLayout style="@style/input_layout_out">
<TextView
style="@style/input_txt_title"
android:text="甲状腺大小" />
<LinearLayout style="@style/input_layout_in">
<com.shwootide.metabolictreat.widget.nicespinner.NiceSpinner
android:id="@+id/ns_physical2_4"
style="@style/input_spinner_full"
app:niceEntries="@array/DMdaxiao" />
</LinearLayout>
<TextView
style="@style/input_txt_title"
android:text="质地" />
<LinearLayout style="@style/input_layout_in_null">
<com.shwootide.metabolictreat.widget.ChangeButton
android:id="@+id/cb_physical2_5"
style="@style/ChangeButton"
app:offText="软"
app:onText="硬" />
</LinearLayout>
<TextView
style="@style/input_txt_title"
android:text="甲状腺压痛" />
<LinearLayout style="@style/input_layout_in_null_nodimen">
<com.shwootide.metabolictreat.widget.ChangeButton
android:id="@+id/cb_physical2_6"
style="@style/ChangeButton"
app:offText="无"
app:onText="有" />
</LinearLayout>
</LinearLayout>
<View style="@style/LineGreyHorizontal" />
<LinearLayout style="@style/input_layout_out">
<TextView
style="@style/input_txt_title"
android:text="突眼" />
<LinearLayout style="@style/input_layout_in">
<com.shwootide.metabolictreat.widget.nicespinner.NiceSpinner
android:id="@+id/ns_physical2_7"
style="@style/input_spinner_full"
app:niceEntries="@array/DMxgzy" />
</LinearLayout>
<TextView
style="@style/input_txt_title"
android:text="双手细震" />
<LinearLayout style="@style/input_layout_in_null">
<com.shwootide.metabolictreat.widget.ChangeButton
android:id="@+id/cb_physical2_8"
style="@style/ChangeButton"
app:offText="无"
app:onText="有" />
</LinearLayout>
<TextView
style="@style/input_txt_title"
android:text="血管杂音" />
<LinearLayout style="@style/input_layout_in_nodimen">
<com.shwootide.metabolictreat.widget.nicespinner.NiceSpinner
android:id="@+id/ns_physical2_9"
style="@style/input_spinner_full"
app:niceEntries="@array/DMxgzy" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout> | {
"content_hash": "d6b0f8975bf84a758c7bf60f447e9754",
"timestamp": "",
"source": "github",
"line_count": 161,
"max_line_length": 76,
"avg_line_length": 33.95031055900621,
"alnum_prop": 0.504390779363337,
"repo_name": "gmyboy/MetabolicTreat",
"id": "f414cdf080bbbaa6bd5d48cca7158050e52c46b0",
"size": "5538",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/frag_physical2.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1341519"
}
],
"symlink_target": ""
} |
package is.hello.buruberi.bluetooth.stacks.android;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresPermission;
import android.support.annotation.VisibleForTesting;
import android.support.v4.content.LocalBroadcastManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import is.hello.buruberi.bluetooth.errors.BondException;
import is.hello.buruberi.bluetooth.errors.ConnectionStateException;
import is.hello.buruberi.bluetooth.errors.GattException;
import is.hello.buruberi.bluetooth.errors.LostConnectionException;
import is.hello.buruberi.bluetooth.errors.OperationTimeoutException;
import is.hello.buruberi.bluetooth.errors.ServiceDiscoveryException;
import is.hello.buruberi.bluetooth.stacks.BluetoothStack;
import is.hello.buruberi.bluetooth.stacks.GattPeripheral;
import is.hello.buruberi.bluetooth.stacks.GattService;
import is.hello.buruberi.bluetooth.stacks.OperationTimeout;
import is.hello.buruberi.bluetooth.stacks.android.GattDispatcher.ServicesDiscoveredListener;
import is.hello.buruberi.bluetooth.stacks.util.AdvertisingData;
import is.hello.buruberi.bluetooth.stacks.util.LoggerFacade;
import is.hello.buruberi.util.Operation;
import is.hello.buruberi.util.Rx;
import is.hello.buruberi.util.SerialQueue;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Func1;
public class NativeGattPeripheral implements GattPeripheral,
GattDispatcher.CharacteristicChangeListener {
/**
* How long to delay response after a successful service discovery.
* <p>
* Settled on 5 seconds after experimenting with Jackson. Idea for delay from
* <a href="https://code.google.com/p/android/issues/detail?id=58381">here</a>.
*/
private static final int SERVICES_DELAY_S = 5;
private final @NonNull NativeBluetoothStack stack;
private final @NonNull LoggerFacade logger;
private final SerialQueue serialQueue;
/*package*/ final @NonNull BluetoothDevice bluetoothDevice;
private final int scannedRssi;
private final @NonNull AdvertisingData advertisingData;
/*package*/ final GattDispatcher gattDispatcher;
private final DisconnectForwarder disconnectForwarder;
private final List<Runnable> disconnectListeners = new ArrayList<>();
/*package*/ @Nullable BluetoothGatt gatt;
@VisibleForTesting @NonNull Map<UUID, NativeGattService> services = Collections.emptyMap();
private @Nullable BroadcastReceiver bluetoothStateReceiver;
/*package*/ NativeGattPeripheral(@NonNull NativeBluetoothStack stack,
@NonNull BluetoothDevice bluetoothDevice,
int scannedRssi,
@NonNull AdvertisingData advertisingData) {
this.stack = stack;
this.logger = stack.getLogger();
this.serialQueue = new SerialQueue();
this.bluetoothDevice = bluetoothDevice;
this.scannedRssi = scannedRssi;
this.advertisingData = advertisingData;
this.gattDispatcher = new GattDispatcher(logger, this);
this.disconnectForwarder = new DisconnectForwarder();
gattDispatcher.addConnectionListener(disconnectForwarder);
}
//region Attributes
@NonNull
@Override
public OperationTimeout createOperationTimeout(@NonNull String name,
long duration,
@NonNull TimeUnit timeUnit) {
return new SchedulerOperationTimeout(name, duration, timeUnit, logger);
}
@Override
public int getScanTimeRssi() {
return scannedRssi;
}
@Override
public String getAddress() {
return bluetoothDevice.getAddress();
}
@Override
public String getName() {
return bluetoothDevice.getName();
}
@NonNull
@Override
public AdvertisingData getAdvertisingData() {
return advertisingData;
}
@Override
@NonNull
public BluetoothStack getStack() {
return stack;
}
@Override
public int compareTo(@NonNull GattPeripheral other) {
final int myRssi = getScanTimeRssi();
final int otherRssi = other.getScanTimeRssi();
return (myRssi < otherRssi) ? -1 : ((myRssi > otherRssi) ? 1 : 0);
}
@Nullable
@Override
public Parcelable saveState() {
return stack.saveState(this);
}
//endregion
//region Connectivity
/*package*/ <T> Runnable addTimeoutDisconnectListener(final @NonNull Subscriber<T> subscriber,
final @NonNull OperationTimeout timeout) {
final Runnable onDisconnect = new Runnable() {
@Override
public void run() {
logger.info(GattPeripheral.LOG_TAG,
"onDisconnectListener(" + subscriber.hashCode() + ")");
timeout.unschedule();
subscriber.onError(new LostConnectionException());
}
};
disconnectListeners.add(onDisconnect);
return onDisconnect;
}
/*package*/ void removeDisconnectListener(@NonNull Runnable disconnectListener) {
disconnectListeners.remove(disconnectListener);
}
private void handleGattDisconnect(@Nullable BluetoothGatt gatt) {
if (gatt != null) {
logger.info(LOG_TAG, "Closing gatt layer");
gatt.close();
if (gatt == this.gatt) {
logger.info(GattPeripheral.LOG_TAG, "dispatchDisconnect()");
gattDispatcher.clearListeners();
for (final Runnable onDisconnect : disconnectListeners) {
onDisconnect.run();
}
disconnectListeners.clear();
for (final NativeGattService service : services.values()) {
service.dispatchDisconnect();
}
this.gatt = null;
this.services = Collections.emptyMap();
stopObservingBluetoothState();
}
}
}
@VisibleForTesting
int getTransportFromConnectFlags(@ConnectFlags final int flags) {
if ((flags & CONNECT_FLAG_TRANSPORT_AUTO) == CONNECT_FLAG_TRANSPORT_AUTO) {
return BluetoothDeviceCompat.TRANSPORT_AUTO;
} else if ((flags & CONNECT_FLAG_TRANSPORT_BREDR) == CONNECT_FLAG_TRANSPORT_BREDR) {
return BluetoothDeviceCompat.TRANSPORT_BREDR;
} else if ((flags & CONNECT_FLAG_TRANSPORT_LE) == CONNECT_FLAG_TRANSPORT_LE) {
return BluetoothDeviceCompat.TRANSPORT_LE;
} else {
logger.warn(LOG_TAG, "ConnectFlags missing transport mask " +
Integer.toHexString(flags));
return BluetoothDeviceCompat.TRANSPORT_AUTO;
}
}
private void startObservingBluetoothState() {
this.bluetoothStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
logger.info(LOG_TAG, "User disabled bluetooth radio, abandoning connection");
if (!stack.getAdapter().isEnabled() && gatt != null) {
gatt.disconnect();
}
}
};
final IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
stack.applicationContext.registerReceiver(bluetoothStateReceiver, filter);
}
private void stopObservingBluetoothState() {
if (bluetoothStateReceiver != null) {
stack.applicationContext.unregisterReceiver(bluetoothStateReceiver);
this.bluetoothStateReceiver = null;
}
}
@NonNull
@Override
@RequiresPermission(Manifest.permission.BLUETOOTH)
public Observable<GattPeripheral> connect(@ConnectFlags final int flags,
@NonNull final OperationTimeout timeout) {
return createObservable(new Observable.OnSubscribe<GattPeripheral>() {
@Override
public void call(final Subscriber<? super GattPeripheral> subscriber) {
if (getConnectionStatus() == STATUS_CONNECTED) {
logger.warn(LOG_TAG, "Redundant call to connect(), ignoring.");
subscriber.onNext(NativeGattPeripheral.this);
subscriber.onCompleted();
return;
} else if (getConnectionStatus() == STATUS_CONNECTING ||
getConnectionStatus() == STATUS_DISCONNECTING) {
subscriber.onError(new ConnectionStateException("Peripheral is changing connection status."));
return;
}
final boolean autoConnect = ((flags & CONNECT_FLAG_WAIT_AVAILABLE) == CONNECT_FLAG_WAIT_AVAILABLE);
final int transport = getTransportFromConnectFlags(flags);
final GattDispatcher.ConnectionListener listener = new GattDispatcher.ConnectionListener() {
boolean hasRetried = false;
@Override
boolean onConnected(@NonNull final BluetoothGatt gatt, int status) {
timeout.unschedule();
logger.info(LOG_TAG, "Connected " + NativeGattPeripheral.this.toString());
startObservingBluetoothState();
disconnectForwarder.setEnabled(true);
subscriber.onNext(NativeGattPeripheral.this);
subscriber.onCompleted();
final Intent connectedIntent = new Intent(ACTION_CONNECTED)
.putExtra(EXTRA_NAME, getName())
.putExtra(EXTRA_ADDRESS, getAddress());
LocalBroadcastManager.getInstance(stack.applicationContext)
.sendBroadcast(connectedIntent);
return false;
}
@Override
boolean onError(@NonNull BluetoothGatt gatt, int status, int state) {
// The first connection attempt made after a user has power cycled their radio,
// or the connection to a device is unexpectedly lost, will seemingly fail 100%
// of the time. The error code varies by manufacturer. Retrying silently resolves
// the issue.
if (GattException.isRecoverableConnectError(status) && !hasRetried) {
logger.warn(LOG_TAG, "First connection attempt failed due to stack error, retrying.");
this.hasRetried = true;
gatt.close();
NativeGattPeripheral.this.gatt =
BluetoothDeviceCompat.connectGatt(bluetoothDevice,
stack.applicationContext,
autoConnect,
gattDispatcher,
transport);
if (NativeGattPeripheral.this.gatt != null) {
timeout.reschedule();
} else {
timeout.unschedule();
disconnectForwarder.setEnabled(true);
subscriber.onError(new GattException(GattException.GATT_INTERNAL_ERROR,
Operation.CONNECT));
}
return true;
} else {
timeout.unschedule();
logger.error(LOG_TAG,
"Could not connect. " + GattException.statusToString(status),
null);
disconnectForwarder.setEnabled(true);
subscriber.onError(new GattException(status,
Operation.CONNECT));
return false;
}
}
};
gattDispatcher.addConnectionListener(listener);
timeout.setTimeoutAction(new Action0() {
@Override
public void call() {
timeout.unschedule();
gattDispatcher.removeConnectionListener(listener);
stopObservingBluetoothState();
disconnectForwarder.setEnabled(true);
subscriber.onError(new OperationTimeoutException(Operation.CONNECT));
}
}, stack.getScheduler());
logger.info(LOG_TAG, "Connecting " + NativeGattPeripheral.this.toString());
if (gatt != null) {
if (gatt.connect()) {
disconnectForwarder.setEnabled(false);
timeout.schedule();
} else {
gattDispatcher.removeConnectionListener(listener);
subscriber.onError(new GattException(GattException.GATT_INTERNAL_ERROR,
Operation.CONNECT));
}
} else {
NativeGattPeripheral.this.gatt =
BluetoothDeviceCompat.connectGatt(bluetoothDevice,
stack.applicationContext,
autoConnect,
gattDispatcher,
transport);
if (gatt != null) {
disconnectForwarder.setEnabled(false);
timeout.schedule();
} else {
gattDispatcher.removeConnectionListener(listener);
subscriber.onError(new GattException(GattException.GATT_INTERNAL_ERROR,
Operation.CONNECT));
}
}
}
});
}
@NonNull
@Override
@RequiresPermission(Manifest.permission.BLUETOOTH)
public Observable<GattPeripheral> disconnect() {
return createObservable(new Observable.OnSubscribe<GattPeripheral>() {
@Override
public void call(final Subscriber<? super GattPeripheral> subscriber) {
final int connectionStatus = getConnectionStatus();
if (connectionStatus == STATUS_DISCONNECTED ||
connectionStatus == STATUS_DISCONNECTING || gatt == null) {
subscriber.onNext(NativeGattPeripheral.this);
subscriber.onCompleted();
return;
} else if (connectionStatus == STATUS_CONNECTING) {
subscriber.onError(new ConnectionStateException("Peripheral is connecting"));
return;
}
final GattDispatcher.ConnectionListener listener = new GattDispatcher.ConnectionListener() {
@Override
boolean onDisconnected(@NonNull BluetoothGatt gatt, int status) {
logger.info(LOG_TAG, "Disconnected " + NativeGattPeripheral.this.toString());
stopObservingBluetoothState();
subscriber.onNext(NativeGattPeripheral.this);
subscriber.onCompleted();
return false;
}
@Override
boolean onError(@NonNull BluetoothGatt gatt, int status, int state) {
logger.info(LOG_TAG, "Could not disconnect " +
NativeGattPeripheral.this.toString() + "; " +
GattException.statusToString(status));
subscriber.onError(new GattException(status, Operation.DISCONNECT));
return false;
}
};
gattDispatcher.addConnectionListener(listener);
logger.info(LOG_TAG, "Disconnecting " + NativeGattPeripheral.this.toString());
gatt.disconnect();
}
});
}
@Override
@RequiresPermission(Manifest.permission.BLUETOOTH)
public @ConnectivityStatus int getConnectionStatus() {
if (gatt != null) {
final @ConnectivityStatus int status =
stack.bluetoothManager.getConnectionState(bluetoothDevice,
BluetoothProfile.GATT);
return status;
} else {
return STATUS_DISCONNECTED;
}
}
//endregion
//region Internal
/*package*/ <T> Observable<T> createObservable(@NonNull Observable.OnSubscribe<T> onSubscribe) {
return Rx.serialize(stack.newConfiguredObservable(onSubscribe), serialQueue);
}
/*package*/ <T> void setupTimeout(@NonNull final Operation operation,
@NonNull final OperationTimeout timeout,
@NonNull final Subscriber<T> subscriber,
@Nullable final Runnable disconnectListener) {
timeout.setTimeoutAction(new Action0() {
@Override
public void call() {
switch (operation) {
case DISCOVER_SERVICES:
gattDispatcher.servicesDiscovered = null;
break;
case ENABLE_NOTIFICATION:
gattDispatcher.descriptorWrite = null;
break;
case DISABLE_NOTIFICATION:
gattDispatcher.descriptorWrite = null;
break;
case WRITE_COMMAND:
gattDispatcher.characteristicWrite = null;
break;
}
if (disconnectListener != null) {
removeDisconnectListener(disconnectListener);
}
disconnect().subscribe(new Subscriber<GattPeripheral>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
subscriber.onError(new OperationTimeoutException(operation, e));
}
@Override
public void onNext(GattPeripheral gattPeripheral) {
subscriber.onError(new OperationTimeoutException(operation));
}
});
timeout.unschedule();
}
}, stack.getScheduler());
}
//endregion
//region Bonding
@RequiresPermission(Manifest.permission.BLUETOOTH)
private Observable<Intent> createBondReceiver() {
return Rx.fromBroadcast(stack.applicationContext,
new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED))
.subscribeOn(stack.getScheduler())
.filter(new Func1<Intent, Boolean>() {
@Override
public Boolean call(Intent intent) {
final BluetoothDevice bondedDevice =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
return (bondedDevice != null &&
bondedDevice.getAddress().equals(bluetoothDevice.getAddress()));
}
});
}
@NonNull
@Override
@RequiresPermission(allOf = {
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
})
public Observable<GattPeripheral> createBond() {
return createObservable(new Observable.OnSubscribe<GattPeripheral>() {
@Override
public void call(final Subscriber<? super GattPeripheral> subscriber) {
if (getBondStatus() == BOND_BONDED) {
logger.info(GattPeripheral.LOG_TAG, "Device already bonded, skipping.");
subscriber.onNext(NativeGattPeripheral.this);
subscriber.onCompleted();
return;
}
final Subscription subscription = createBondReceiver().subscribe(new Subscriber<Intent>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
subscriber.onError(e);
}
@Override
public void onNext(Intent intent) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,
BluetoothDevice.ERROR);
final int previousState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE,
BluetoothDevice.ERROR);
logger.info(GattPeripheral.LOG_TAG, "Bond status changed from " +
BondException.getBondStateString(previousState) +
" to " + BondException.getBondStateString(state));
if (state == BluetoothDevice.BOND_BONDED) {
logger.info(LOG_TAG, "Bonding succeeded.");
subscriber.onNext(NativeGattPeripheral.this);
subscriber.onCompleted();
unsubscribe();
} else if (state == BluetoothDevice.ERROR || state == BOND_NONE &&
previousState == BOND_CHANGING) {
final int reason = intent.getIntExtra(BondException.EXTRA_REASON,
BondException.REASON_UNKNOWN_FAILURE);
logger.error(LOG_TAG, "Bonding failed for reason " +
BondException.getReasonString(reason), null);
subscriber.onError(new BondException(reason));
unsubscribe();
}
}
});
if (!BluetoothDeviceCompat.createBond(bluetoothDevice)) {
subscription.unsubscribe();
subscriber.onError(new BondException(BondException.REASON_ANDROID_API_CHANGED));
}
}
});
}
@NonNull
@Override
@RequiresPermission(allOf = {
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
})
public Observable<GattPeripheral> removeBond(final @NonNull OperationTimeout timeout) {
return createObservable(new Observable.OnSubscribe<GattPeripheral>() {
@Override
public void call(final Subscriber<? super GattPeripheral> subscriber) {
if (getBondStatus() != BOND_BONDED) {
logger.info(GattPeripheral.LOG_TAG, "Device not bonded, skipping.");
subscriber.onNext(NativeGattPeripheral.this);
subscriber.onCompleted();
return;
}
final Subscription subscription = createBondReceiver().subscribe(new Subscriber<Intent>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
subscriber.onError(e);
}
@Override
public void onNext(Intent intent) {
timeout.reschedule();
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,
BluetoothDevice.ERROR);
final int previousState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE,
BluetoothDevice.ERROR);
logger.info(GattPeripheral.LOG_TAG, "Bond status changed from " +
BondException.getBondStateString(previousState) +
" to " + BondException.getBondStateString(state));
if (state == BluetoothDevice.BOND_NONE) {
logger.info(LOG_TAG, "Removing bond succeeded.");
timeout.unschedule();
subscriber.onNext(NativeGattPeripheral.this);
subscriber.onCompleted();
unsubscribe();
} else if (state == BluetoothDevice.ERROR) {
timeout.unschedule();
final int reason = intent.getIntExtra(BondException.EXTRA_REASON,
BondException.REASON_UNKNOWN_FAILURE);
logger.error(LOG_TAG, "Removing bond failed for reason " +
BondException.getReasonString(reason), null);
subscriber.onError(new BondException(reason));
unsubscribe();
}
}
});
timeout.setTimeoutAction(new Action0() {
@Override
public void call() {
subscription.unsubscribe();
// This can happen in Lollipop
if (getBondStatus() == BOND_NONE) {
subscriber.onNext(NativeGattPeripheral.this);
subscriber.onCompleted();
} else {
subscriber.onError(new OperationTimeoutException(Operation.REMOVE_BOND));
}
}
}, stack.getScheduler());
if (!BluetoothDeviceCompat.removeBond(bluetoothDevice)) {
subscription.unsubscribe();
subscriber.onError(new BondException(BondException.REASON_ANDROID_API_CHANGED));
} else {
timeout.schedule();
}
}
});
}
@Override
@RequiresPermission(Manifest.permission.BLUETOOTH)
public @BondStatus int getBondStatus() {
@BondStatus int bondStatus = bluetoothDevice.getBondState();
return bondStatus;
}
//endregion
//region Discovering Services
@NonNull
@Override
@RequiresPermission(Manifest.permission.BLUETOOTH)
public Observable<Map<UUID, ? extends GattService>> discoverServices(final @NonNull OperationTimeout timeout) {
final ConnectedOnSubscribe<Map<UUID, ? extends GattService>> onSubscribe =
new ConnectedOnSubscribe<Map<UUID, ? extends GattService>>(this) {
@Override
public void onSubscribe(@NonNull BluetoothGatt gatt,
@NonNull final Subscriber<? super Map<UUID, ? extends GattService>> subscriber) {
final Runnable onDisconnect = addTimeoutDisconnectListener(subscriber, timeout);
setupTimeout(Operation.DISCOVER_SERVICES,
timeout, subscriber, onDisconnect);
gattDispatcher.servicesDiscovered = new ServicesDiscoveredListener() {
@Override
public void onServicesDiscovered(@NonNull BluetoothGatt gatt, int status) {
timeout.unschedule();
removeDisconnectListener(onDisconnect);
if (status == BluetoothGatt.GATT_SUCCESS) {
NativeGattPeripheral.this.services =
NativeGattService.wrap(gatt.getServices(),
NativeGattPeripheral.this);
subscriber.onNext(services);
subscriber.onCompleted();
gattDispatcher.servicesDiscovered = null;
} else {
logger.error(LOG_TAG, "Could not discover services. " +
GattException.statusToString(status), null);
NativeGattPeripheral.this.services = Collections.emptyMap();
subscriber.onError(new GattException(status,
Operation.DISCOVER_SERVICES));
gattDispatcher.servicesDiscovered = null;
}
}
};
if (gatt.discoverServices()) {
timeout.schedule();
} else {
gattDispatcher.servicesDiscovered = null;
removeDisconnectListener(onDisconnect);
subscriber.onError(new ServiceDiscoveryException());
}
}
};
// See <https://code.google.com/p/android/issues/detail?id=58381>
return createObservable(onSubscribe).delay(SERVICES_DELAY_S,
TimeUnit.SECONDS,
stack.getScheduler());
}
@NonNull
@Override
@RequiresPermission(Manifest.permission.BLUETOOTH)
public Observable<GattService> discoverService(final @NonNull UUID serviceIdentifier, @NonNull OperationTimeout timeout) {
return discoverServices(timeout).flatMap(new Func1<Map<UUID, ? extends GattService>, Observable<? extends GattService>>() {
@Override
public Observable<? extends GattService> call(Map<UUID, ? extends GattService> services) {
final GattService service = services.get(serviceIdentifier);
if (service != null) {
return Observable.just(service);
} else {
return Observable.error(new ServiceDiscoveryException());
}
}
});
}
//endregion
//region Packet Dispatching
@Override
public void onCharacteristicChanged(@NonNull BluetoothGatt gatt,
@NonNull BluetoothGattCharacteristic characteristic) {
if (gatt == this.gatt) {
final UUID serviceId = characteristic.getService().getUuid();
final NativeGattService gattService = services.get(serviceId);
gattService.dispatchNotify(characteristic.getUuid(),
characteristic.getValue());
}
}
//endregion
@Override
public String toString() {
return "{NativeGattPeripheral " +
"name=" + getName() +
", address=" + getAddress() +
", connectionStatus=" + getConnectionStatus() +
", bondStatus=" + getBondStatus() +
", scannedRssi=" + getScanTimeRssi() +
'}';
}
private class DisconnectForwarder extends GattDispatcher.ConnectionListener {
private boolean enabled = true;
/*package*/ void setEnabled(boolean enabled) {
this.enabled = enabled;
}
private void broadcast() {
handleGattDisconnect(gatt);
if (enabled) {
final Intent disconnectIntent = new Intent(ACTION_DISCONNECTED)
.putExtra(EXTRA_NAME, getName())
.putExtra(EXTRA_ADDRESS, getAddress());
LocalBroadcastManager.getInstance(stack.applicationContext)
.sendBroadcast(disconnectIntent);
}
}
@Override
/*package*/ boolean onConnected(@NonNull BluetoothGatt gatt, int status) {
// Do nothing, prevent this listener from being removed.
return true;
}
@Override
/*package*/ boolean onConnecting(@NonNull BluetoothGatt gatt, int status) {
// Do nothing, prevent this listener from being removed.
return true;
}
@Override
/*package*/ boolean onDisconnecting(@NonNull BluetoothGatt gatt, int status) {
// Do nothing, prevent this listener from being removed.
return true;
}
@Override
/*package*/ boolean onDisconnected(@NonNull BluetoothGatt gatt, int status) {
broadcast();
return true;
}
@Override
/*package*/ boolean onError(@NonNull BluetoothGatt gatt, int status, int state) {
if (state == STATUS_DISCONNECTED) {
broadcast();
}
return true;
}
}
/*package*/ static abstract class ConnectedOnSubscribe<T> implements Observable.OnSubscribe<T> {
private final NativeGattPeripheral peripheral;
/*package*/ ConnectedOnSubscribe(@NonNull NativeGattPeripheral peripheral) {
this.peripheral = peripheral;
}
@Override
public final void call(@NonNull Subscriber<? super T> subscriber) {
if (peripheral.getConnectionStatus() != STATUS_CONNECTED || peripheral.gatt == null) {
subscriber.onError(new ConnectionStateException());
} else {
onSubscribe(peripheral.gatt, subscriber);
}
}
public abstract void onSubscribe(@NonNull BluetoothGatt gatt,
@NonNull Subscriber<? super T> subscriber);
}
}
| {
"content_hash": "36634d3566cd71f5640ea46b207c0310",
"timestamp": "",
"source": "github",
"line_count": 859,
"max_line_length": 131,
"avg_line_length": 41.12107101280559,
"alnum_prop": 0.5367607507856071,
"repo_name": "hello/android-buruberi",
"id": "4493852a77803d5040283c8ec68f406263208392",
"size": "35914",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "buruberi-core/src/main/java/is/hello/buruberi/bluetooth/stacks/android/NativeGattPeripheral.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "443267"
}
],
"symlink_target": ""
} |
<?php
/**
* FeedBackForm форма обратной связи для публичной части сайта
*
* @category YupeController
* @package yupe.modules.feedback.models
* @author YupeTeam <[email protected]>
* @license BSD http://ru.wikipedia.org/wiki/%D0%9B%D0%B8%D1%86%D0%B5%D0%BD%D0%B7%D0%B8%D1%8F_BSD
* @link http://yupe.ru
*
**/
class FeedBackForm extends CFormModel
{
public $name;
public $email;
public $phone;
public $theme;
public $text;
public $type;
public $verifyCode;
public function rules()
{
$module = Yii::app()->getModule('feedback');
return array(
array('name, email, theme, text', 'required'),
array('type', 'numerical', 'integerOnly' => true),
array('name, email, phone', 'length', 'max' => 150),
array('theme', 'length', 'max' => 250),
array('email', 'email'),
array('verifyCode', 'yupe\components\validators\YRequiredValidator', 'allowEmpty' => !$module->showCaptcha || Yii::app()->user->isAuthenticated()),
array('verifyCode', 'captcha', 'allowEmpty' => !$module->showCaptcha || Yii::app()->user->isAuthenticated()),
);
}
public function attributeLabels()
{
return array(
'name' => Yii::t('FeedbackModule.feedback', 'Your name'),
'email' => Yii::t('FeedbackModule.feedback', 'Email'),
'phone' => Yii::t('FeedbackModule.feedback', 'Phone'),
'theme' => Yii::t('FeedbackModule.feedback', 'Topic'),
'text' => Yii::t('FeedbackModule.feedback', 'Text'),
'verifyCode' => Yii::t('FeedbackModule.feedback', 'Check code'),
'type' => Yii::t('FeedbackModule.feedback', 'Type'),
);
}
} | {
"content_hash": "462878ac61da14820f02988d90813302",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 159,
"avg_line_length": 35.52,
"alnum_prop": 0.5630630630630631,
"repo_name": "kashapovfi/education",
"id": "fe143ec84e69976459ef8d095957b2b382c3c959",
"size": "1816",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "protected/modules/feedback/models/FeedBackForm.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "1493582"
},
{
"name": "JavaScript",
"bytes": "5808632"
},
{
"name": "PHP",
"bytes": "3858054"
},
{
"name": "Ruby",
"bytes": "1384"
},
{
"name": "Shell",
"bytes": "2326"
}
],
"symlink_target": ""
} |
package org.apache.camel.model.dataformat;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.camel.CamelContext;
import org.apache.camel.model.DataFormatDefinition;
import org.apache.camel.spi.DataFormat;
import org.apache.camel.spi.Metadata;
/**
* xml-rpc data format
*/
@Metadata(label = "dataformat,transformation")
@XmlRootElement(name = "xmlrpc")
@XmlAccessorType(XmlAccessType.FIELD)
public class XmlRpcDataFormat extends DataFormatDefinition {
@XmlAttribute
private Boolean request;
public XmlRpcDataFormat() {
super("xmlrpc");
}
@Override
protected void configureDataFormat(DataFormat dataFormat, CamelContext camelContext) {
if (request != null) {
setProperty(camelContext, dataFormat, "request", request);
}
}
public Boolean getRequest() {
return request;
}
/**
* Whether to unmarshal request or response
* <p/>
* Is by default false
*/
public void setRequest(Boolean request) {
this.request = request;
}
}
| {
"content_hash": "76d246df84fbf35aa940f5cfb9f29646",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 90,
"avg_line_length": 25.375,
"alnum_prop": 0.7036124794745484,
"repo_name": "ramonmaruko/camel",
"id": "3bd1c4eea1878c9b9d1f60a993a6882d8311e00e",
"size": "2021",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "camel-core/src/main/java/org/apache/camel/model/dataformat/XmlRpcDataFormat.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "18641"
},
{
"name": "Eagle",
"bytes": "2898"
},
{
"name": "Elm",
"bytes": "5970"
},
{
"name": "Groovy",
"bytes": "23444"
},
{
"name": "HTML",
"bytes": "191526"
},
{
"name": "Java",
"bytes": "44730910"
},
{
"name": "JavaScript",
"bytes": "88124"
},
{
"name": "Protocol Buffer",
"bytes": "578"
},
{
"name": "Python",
"bytes": "36"
},
{
"name": "Ruby",
"bytes": "13262"
},
{
"name": "Scala",
"bytes": "303651"
},
{
"name": "Shell",
"bytes": "12930"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "XQuery",
"bytes": "1483"
},
{
"name": "XSLT",
"bytes": "284036"
}
],
"symlink_target": ""
} |
def application(environ, start_response):
environ['wsgi.errors'].write('Error in application.')
environ['wsgi.errors'].flush()
start_response('200', [('Content-Length', '0')])
return []
| {
"content_hash": "8753f0bb304bc74e2c4e53a9e23ad23f",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 57,
"avg_line_length": 33.833333333333336,
"alnum_prop": 0.6502463054187192,
"repo_name": "nginx/unit",
"id": "148bce9e4716f4628448bcdb8b00417d1cca8403",
"size": "203",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/python/errors_write/wsgi.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2948852"
},
{
"name": "C++",
"bytes": "49444"
},
{
"name": "Dockerfile",
"bytes": "3409"
},
{
"name": "Go",
"bytes": "19213"
},
{
"name": "HTML",
"bytes": "847"
},
{
"name": "Java",
"bytes": "780057"
},
{
"name": "JavaScript",
"bytes": "87653"
},
{
"name": "Makefile",
"bytes": "32267"
},
{
"name": "PHP",
"bytes": "7022"
},
{
"name": "Perl",
"bytes": "9359"
},
{
"name": "Python",
"bytes": "706893"
},
{
"name": "Raku",
"bytes": "1497"
},
{
"name": "Roff",
"bytes": "6774"
},
{
"name": "Ruby",
"bytes": "9880"
},
{
"name": "Shell",
"bytes": "14683"
}
],
"symlink_target": ""
} |
/* === Silver Circle Down Arrow ==*/
.duiDomButtonSilverCircleDownArrow {
background-image: url(compat/duiDomButtonSilverCircleDownArrow.png);
background-repeat: no-repeat;
}
.duiDomButtonSilverCircleDownArrow > div {
display: none;
}
| {
"content_hash": "8f2ff8d1724c270f78f2f9cf92a29422",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 69,
"avg_line_length": 29.75,
"alnum_prop": 0.7773109243697479,
"repo_name": "asudoh/delite",
"id": "412aec1a8c4a85cf094814d8eeebe38ae9fdd731",
"size": "238",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mobile/themes/common/domButtons/DomButtonSilverCircleDownArrow-compat.css",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
import React from 'react';
import FormInput from '../common/form-input';
import Button from '../common/button';
import Displayinator from '../displayinator';
export default class Submitly extends React.Component {
constructor() {
super();
this.state = {
displayText:""
};
this.handleInputChange = this.handleInputChange.bind(this);
this.handleDisplayText = this.handleDisplayText.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleDisplayText () {
let coolText = this.state.firstName + " " +
this.state.lastName +
" loves to program in " +
this.state.language;
this.setState({displayText:coolText})
}
render() {
return (
<div>
<FormInput
label="First Name: "
name="firstName"
type="text"
value={this.state.firstName}
onChange = {this.handleInputChange}
/>
<FormInput
label="Last Name: "
name="lastName"
type="text"
value={this.state.lastName}
onChange = {this.handleInputChange}
/>
<FormInput
label="Favorite Language: "
name="language"
type="text"
value={this.state.language}
onChange = {this.handleInputChange}
/>
<Button
text="Submit"
onClick={this.handleDisplayText}
/>
<Displayinator text={this.state.displayText} />
</div>
)
}
} | {
"content_hash": "c13da38ae718699c390c067928235c2e",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 81,
"avg_line_length": 30.83076923076923,
"alnum_prop": 0.4755489021956088,
"repo_name": "jeffboulay/react-submitly",
"id": "83a5c07a446df8bf21de50e9c37f754eb989e913",
"size": "2004",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/submitly/index.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "63"
},
{
"name": "HTML",
"bytes": "1590"
},
{
"name": "JavaScript",
"bytes": "7167"
}
],
"symlink_target": ""
} |
AblePolecat module for accessing Google APIs via OAuth 2.0
Module requires AblePolecat core class library 0.7.2 or higher (https://github.com/kkuhrman/AblePolecat).
Module requires Google API PHP client (https://github.com/google/google-api-php-client).
| {
"content_hash": "737e96e8ea77276505c9ed93f230028d",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 105,
"avg_line_length": 51.2,
"alnum_prop": 0.796875,
"repo_name": "kkuhrman/AblePolecat-GoogleApis",
"id": "80e20d11221e0c60994c9517b199a2f19c05b47e",
"size": "282",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
NS_ASSUME_NONNULL_BEGIN
@interface BFOrderItem (CoreDataProperties)
@property (nullable, nonatomic, retain) NSNumber *quantity;
@property (nullable, nonatomic, retain) NSNumber *price;
@property (nullable, nonatomic, retain) NSString *priceFormatted;
@property (nullable, nonatomic, retain) NSNumber *orderItemID;
@property (nullable, nonatomic, retain) BFOrder *inOrder;
@property (nullable, nonatomic, retain) BFProductVariant *productVariant;
@end
NS_ASSUME_NONNULL_END
| {
"content_hash": "ba0ef173fab09f78e355443011953d44",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 73,
"avg_line_length": 34.07142857142857,
"alnum_prop": 0.7945492662473794,
"repo_name": "openshopio/openshop.io-ios",
"id": "e2b3a876881f7e56563b6635b1893b735acffa28",
"size": "650",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "OpenShop/BFOrderItem+CoreDataProperties.h",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "1441554"
},
{
"name": "Ruby",
"bytes": "6970"
},
{
"name": "Shell",
"bytes": "81"
},
{
"name": "Swift",
"bytes": "22367"
}
],
"symlink_target": ""
} |
FROM balenalib/beaglebone-green-gateway-debian:buster-run
ENV NODE_VERSION 15.6.0
ENV YARN_VERSION 1.22.4
RUN buildDeps='curl libatomic1' \
&& set -x \
&& for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --batch --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --batch --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --batch --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends \
&& rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& echo "234871415c54174f91764f332a72631519a6af7b1a87797ad7c729855182f9cd node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@node" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Buster \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.6.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {
"content_hash": "2f84a4088bd2f40e1057112db3c7dd50",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 691,
"avg_line_length": 65.17777777777778,
"alnum_prop": 0.7050801227412206,
"repo_name": "nghiant2710/base-images",
"id": "80dfd867b129dc1b909cf286d3d1b18eb30168c8",
"size": "2954",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/node/beaglebone-green-gateway/debian/buster/15.6.0/run/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "144558581"
},
{
"name": "JavaScript",
"bytes": "16316"
},
{
"name": "Shell",
"bytes": "368690"
}
],
"symlink_target": ""
} |
import json
import mock
import webob.exc
from wafflehaus.iweb.keystone.user_filter import blacklist
from wafflehaus import tests
class TestUserFilter(tests.TestCase):
def setUp(self):
self.app = mock.Mock()
self.conf1 = {'enabled': 'true', 'blacklist': 'admin nova'}
self.body_v2 = json.dumps({'auth': {
"tenantName": "demo",
"passwordCredentials": {"username": "%(username)s",
"password": "s3cr3t"}}})
self.body_v3 = json.dumps({"auth": {
"scope": {
"project": {
"domain": {"id": "default"},
"name": "demo"}},
"identity": {
"password": {
"user": {
"domain": {"id": "default"},
"password": "s3cr3t",
"name": "%(username)s"}},
"methods": ["password"]}}})
def create_filter(self, conf):
return blacklist.filter_factory(conf)(self.app)
def create_request(self, url, body):
req = webob.request.Request.blank(url, method='POST')
req.body = body
return req
def test_blacklist_deny_blacklisted_user_v2(self):
filter = self.create_filter(self.conf1)
body = self.body_v2 % {'username': 'admin'}
req = self.create_request('/v2.0/tokens', body=body)
resp = filter.__call__(req)
self.assertTrue(isinstance(resp, webob.exc.HTTPException))
def test_blacklist_deny_blacklisted_user_v3(self):
filter = self.create_filter(self.conf1)
body = self.body_v3 % {'username': 'admin'}
req = self.create_request('/v3/auth/tokens', body=body)
resp = filter.__call__(req)
self.assertTrue(isinstance(resp, webob.exc.HTTPException))
def test_blacklist_allow_not_blacklisted_user_v2(self):
filter = self.create_filter(self.conf1)
body = self.body_v2 % {'username': 'demo'}
req = self.create_request('/v2.0/tokens', body=body)
resp = filter.__call__(req)
self.assertEqual(self.app, resp)
def test_blacklist_allow_not_blacklisted_user_v3(self):
filter = self.create_filter(self.conf1)
body = self.body_v3 % {'username': 'demo'}
req = self.create_request('/v3/auth/tokens', body=body)
resp = filter.__call__(req)
self.assertEqual(self.app, resp)
def test_blacklist_disabled_v2(self):
conf = {'enabled': 'false', 'blacklist': 'admin nova'}
filter = self.create_filter(conf)
body = self.body_v2 % {'username': 'admin'}
req = self.create_request('/v2.0/tokens', body=body)
resp = filter.__call__(req)
self.assertEqual(self.app, resp)
def test_blacklist_no_blacklist_v2(self):
conf = {'enabled': 'true', 'blacklist': ''}
filter = self.create_filter(conf)
body = self.body_v2 % {'username': 'admin'}
req = self.create_request('/v2.0/tokens', body=body)
resp = filter.__call__(req)
self.assertEqual(self.app, resp)
def test_blacklist_unknown_auth(self):
filter = self.create_filter(self.conf1)
body = json.dumps({'auth': {}})
req = self.create_request('/v2.0/tokens', body=body)
resp = filter.__call__(req)
self.assertEqual(self.app, resp)
def test_blacklist_unknown_auth_v3(self):
filter = self.create_filter(self.conf1)
body = json.dumps({'auth': {'identity': {}}})
req = self.create_request('/v3/auth/tokens', body=body)
resp = filter.__call__(req)
self.assertEqual(self.app, resp)
def test_blacklist_junk_body(self):
"""Ignore junk body."""
filter = self.create_filter(self.conf1)
req = self.create_request('/v2.0/tokens', body='junk')
resp = filter.__call__(req)
self.assertEqual(self.app, resp)
| {
"content_hash": "af5be79eec635145c7e7cbb86de2fcb3",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 67,
"avg_line_length": 32.59504132231405,
"alnum_prop": 0.5636409736308317,
"repo_name": "mgagne/wafflehaus.iweb",
"id": "0d086d33dbd113df8c755bef2d816fe148b91bf3",
"size": "3944",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/test_keystone_user_filter.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "16926"
}
],
"symlink_target": ""
} |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>de.fesere.hypermedia</groupId>
<artifactId>collection-json-parser</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>collection-json-parser</name>
<url>https://github.com/felipesere/collection-json-parser</url>
<licenses>
<license>
<name>The MIT License</name>
<url>https://raw.github.com/felipesere/collection-json-parser/master/LICENSE</url>
<distribution>repo</distribution>
</license>
</licenses>
<scm>
<connection>scm:git:[email protected]:felipesere/collection-json-parser.git</connection>
<url>scm:git:[email protected]:felipesere/collection-json-parser.git</url>
<developerConnection>scm:git:[email protected]:felipesere/collection-json-parser.git</developerConnection>
</scm>
<developers>
<developer>
<name>Felipe Seré</name>
</developer>
</developers>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- github server corresponds to entry in ~/.m2/settings.xml -->
<github.global.server>github</github.global.server>
</properties>
<distributionManagement>
<repository>
<id>internal.repo</id>
<name>Temporary Staging Repository</name>
<url>file://${project.build.directory}/mvn-repo</url>
</repository>
</distributionManagement>
<dependencies>
<!-- JSON -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.6.4.201312101107</version>
<executions>
<!--
Prepares the property pointing to the JaCoCo runtime agent which
is passed as VM argument when Maven the Surefire plugin is executed.
-->
<execution>
<id>pre-unit-test</id>
<goals>
<goal>prepare-agent</goal>
</goals>
<configuration>
<!-- Sets the path to the file which contains the execution data. -->
<destFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</destFile>
<!--
Sets the name of the property containing the settings
for JaCoCo runtime agent.
-->
<propertyName>surefireArgLine</propertyName>
</configuration>
</execution>
<!--
Ensures that the code coverage report for unit tests is created after
unit tests have been run.
-->
<execution>
<id>post-unit-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<!-- Sets the path to the file which contains the execution data. -->
<dataFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</dataFile>
<!-- Sets the output directory for the code coverage report. -->
<outputDirectory>${project.reporting.outputDirectory}/jacoco</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<!-- Sets the VM argument line used when unit tests are run. -->
<argLine>${surefireArgLine}</argLine>
<!-- Skips unit tests if the value of skip.unit.tests property is true -->
<skipTests>${skip.unit.tests}</skipTests>
<!-- Excludes integration tests when unit tests are run. -->
<excludes>
<exclude>**/IT*.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.eluder.coveralls</groupId>
<artifactId>coveralls-maven-plugin</artifactId>
<version>2.1.0</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.1</version>
<configuration>
<altDeploymentRepository>internal.repo::default::file://${project.build.directory}/mvn-repo</altDeploymentRepository>
</configuration>
</plugin>
<plugin>
<groupId>com.github.github</groupId>
<artifactId>site-maven-plugin</artifactId>
<version>0.9</version>
<configuration>
<message>Maven artifacts for ${project.version}</message> <!-- git commit message -->
<noJekyll>true</noJekyll> <!-- disable webpage processing -->
<outputDirectory>${project.build.directory}/mvn-repo</outputDirectory> <!-- matches distribution management repository url above -->
<branch>refs/heads/mvn-repo</branch> <!-- remote branch name -->
<includes><include>**/*</include></includes>
<repositoryName>collection-json-parser</repositoryName> <!-- github repo name -->
<repositoryOwner>felipesere</repositoryOwner> <!-- github username -->
</configuration>
<executions>
<!-- run site-maven-plugin's 'site' target as part of the build's normal 'deploy' phase -->
<execution>
<goals>
<goal>site</goal>
</goals>
<phase>deploy</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "8d60b7b66aed2b2a58667d049a38239b",
"timestamp": "",
"source": "github",
"line_count": 229,
"max_line_length": 152,
"avg_line_length": 40.23580786026201,
"alnum_prop": 0.5005426524853483,
"repo_name": "felipesere/collection-json-parser",
"id": "87d9516785fd2a2b6fa32c7011fd2fd72ceafbe3",
"size": "9215",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pom.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "107327"
}
],
"symlink_target": ""
} |
require 'durable_decorator/util'
module DurableDecorator
Util.class_eval do
def logger
Rails.logger
end
end
end
| {
"content_hash": "d2ee55105463984620418e942664b9a8",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 32,
"avg_line_length": 14.666666666666666,
"alnum_prop": 0.7045454545454546,
"repo_name": "jumph4x/durable_decorator_rails",
"id": "8cf2b64445ea1f5d61ba8500d0385bc41b373b63",
"size": "132",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/durable_decorator_rails/durable_decorator_ext.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "42"
},
{
"name": "Ruby",
"bytes": "8905"
}
],
"symlink_target": ""
} |
package main
import (
"encoding/json"
"errors"
"io"
"net/http"
"os"
"path/filepath"
"time"
"github.com/googollee/go-socket.io"
"github.com/tiltfactor/toto/domain"
"github.com/tiltfactor/toto/utils"
"github.com/BurntSushi/toml"
"github.com/jesusrmoreno/sad-squid"
logrus "github.com/Sirupsen/logrus"
"github.com/codegangsta/cli"
)
var log *logrus.Logger
func init() {
log = logrus.New()
log.Formatter = &logrus.TextFormatter{
FullTimestamp: true,
}
log.Level = logrus.DebugLevel
}
// Version ...
var Version = "1.3.3"
// Events that are exposed to the client
const (
connection = "connection"
disconnection = "disconnection"
playerDisconnect = "player-disconnect"
groupAssignment = "group-assignment"
roomMessage = "room-message"
joinGame = "join-game"
makeMove = "make-move"
moveMade = "move-made"
inQueue = "in-queue"
serverError = "server-error"
clientError = "client-error"
)
// Response is the structure of all our responses.
type Response struct {
Timestamp int64 `json:"timeStamp"`
Kind string `json:"kind"`
Data interface{} `json:"data"`
}
// GameJoinRequest is the request that the client should sent to get a room.
type GameJoinRequest struct {
GameID string `json:"gameId"`
}
// Control serves to store the metadata for different games
type Control struct {
// These must be thread safe so we use the ConcurrentMap types
TurnMap *utils.ConcurrentStringIntMap
// Maps the player id to the room
RoomMap *utils.ConcurrentStringMap
}
// QueuePlayers adds players to the game's lobby to wait for a partner.
// Players are queued on a first come first serve basis.
func QueuePlayers(g domain.Game, p domain.Player) bool {
pq := g.Lobby
if !pq.Contains(p.Comm.Id()) {
pq.AddToQueue(p)
return true
}
return false
}
// GroupPlayers attempts to creates groups of players of the size defined in the
// game files. It also sets the player turns.
// It returns the name of the room and true if it succeeded or
// an empty string and false if it did not.
func GroupPlayers(g domain.Game, gi *Control) (string, []domain.Player) {
log.Debug("Attempting to group players for game", g.UUID)
pq := g.Lobby
max := g.MaxPlayers
min := g.MinPlayers
if max == 0 {
max = min
}
available := pq.Size()
for needed := max; needed >= min; needed-- {
if available >= max {
team := []domain.Player{}
roomName := squid.GenerateSimpleID()
for i := 0; i < needed; i++ {
p := pq.PopFromQueue()
team = append(team, p)
// Place the player in the created room.
p.Comm.Join(roomName)
playerID := p.Comm.Id()
gi.RoomMap.Set(playerID, roomName)
// We generate a turn key composed of the room name and player id to store
// the turn. turns are assigned based off of how they are popped from the
// queue.
tk := TurnKey(playerID, roomName)
gi.TurnMap.Set(tk, i)
}
return roomName, team
}
}
return "", nil
}
// Cross origin server is used to add cross-origin request capabilities to the
// socket server. It wraps the socketio.Server
type crossOriginServer struct {
Server *socketio.Server
}
// ServeHTTP is implemented to add the needed header for CORS in socketio.
// This must be named ServeHTTP and take the
// (http.ResponseWriter, r *http.Request) to satisfy the http.Handler interface
func (s crossOriginServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Credentials", "true")
origin := r.Header.Get("Origin")
w.Header().Set("Access-Control-Allow-Origin", origin)
s.Server.ServeHTTP(w, r)
}
// HandlePlayerJoin is called when a player makes a request to join a game
// it checks the validity of the passed game id and places players in the queue
// for that game if the game id is valid, it then attempts to group players.
// Because the queue and group logic is called each time a player connects
// we eliminate the need for a loop to check if there are enough players.
// Also because the Queue is protected by a mutex we don't need to worry about
// players getting assigned to multiple rooms.
func HandlePlayerJoin(so socketio.Socket, r GameJoinRequest,
games domain.GameMap, info Control) {
gameID := r.GameID
if gameID == "" {
log.Debug("No game included from", so.Id())
so.Emit(clientError, ErrorResponse(clientError, "Must include GameID"))
}
log.Debug(so.Id(), "attempting to join game", gameID)
// If the player attempts to connect to a game we first have to make
// sure that they are joining a game that is registered with our server.
if g, exists := games[gameID]; exists {
// First queue the player
newPlayer := domain.Player{
Comm: so,
}
if didQueue := QueuePlayers(g, newPlayer); didQueue {
// Create the response we're going to send
r := WrapResponse(inQueue, struct {
Msg string `json:"message"`
PlayersInQueue int `json:"playersInQueue"`
}{
Msg: "You are in the queue for game: " + g.Title,
PlayersInQueue: g.Lobby.Size(),
})
so.Emit(inQueue, r)
if rn, group := GroupPlayers(g, &info); group != nil && rn != "" {
// Tell each member what their room name is as well as their turn
for i, p := range group {
data := map[string]interface{}{}
data["roomName"] = rn
data["turnNumber"] = i
r := WrapResponse(groupAssignment, data)
p.Comm.Emit(groupAssignment, r)
}
}
} else {
// Create the response we're going to send
data := map[string]interface{}{}
data["message"] = "Already in queue"
r := WrapResponse(clientError, data)
so.Emit(clientError, r)
}
} else {
log.Debug("Invalid GameId from", so.Id())
so.Emit(clientError, ErrorResponse(clientError, "Invalid GameID"))
}
}
// StartServer loads the games from the games directory (exits on error)
// Creates the socket io server and wraps it to accept all origins
// Initializes our Control structure to store metadata
// and finally starts up the socket io server.
func StartServer(c *cli.Context) {
games, err := ReadGameFiles("./games")
if err != nil {
log.Fatal(err)
}
for key, game := range games {
log.Println("Loaded:", key, "from", game.FileName)
}
server, err := socketio.NewServer(nil)
s := crossOriginServer{
Server: server,
}
if err != nil {
log.Fatal(err)
}
info := Control{
RoomMap: utils.NewConcurrentStringMap(),
TurnMap: utils.NewConcurrentStringIntMap(),
}
server.On(connection, func(so socketio.Socket) {
log.Debug("Connection from", so.Id())
// Makes it so that the player joins a room with his/her unique id.
so.Join(so.Id())
so.On(joinGame, func(r GameJoinRequest) {
HandlePlayerJoin(so, r, games, info)
})
so.On(disconnection, func() {
// This is really really bad unfuture proof, slow code.
// Please Refactor me
for key := range games {
g := games[key]
g.Lobby.Remove(so.Id())
}
r, foundRoom := info.RoomMap.Get(so.Id())
tk := TurnKey(so.Id(), r)
t, foundTurn := info.TurnMap.Get(tk)
// Broadcast to the room that the player disconnected.
if foundRoom && foundTurn {
m := map[string]interface{}{}
m["player"] = t
server.BroadcastTo(r, playerDisconnect, WrapResponse(playerDisconnect, m))
}
// Remove the player from the room and turn maps when they disconnect.
info.RoomMap.Del(so.Id())
info.TurnMap.Del(tk)
})
so.On(makeMove, func(move json.RawMessage) {
room, exists := info.RoomMap.Get(so.Id())
log.Println(string(move))
if exists {
m := map[string]interface{}{}
if err := json.Unmarshal(move, &m); err != nil {
log.Debug("Invalid JSON from", so.Id(), string(move))
so.Emit(clientError, ErrorResponse(clientError, "Invalid JSON"))
}
turn, exists := info.TurnMap.Get(room + ":" + so.Id())
if !exists {
log.Debug("No turn assigned", so.Id())
so.Emit(serverError, ErrorResponse(serverError, "No turn assigned"))
}
// Overwrites who's turn it is using the turn map assigned at join.
m["madeBy"] = turn
m["madeById"] = so.Id()
r := WrapResponse(moveMade, m)
log.Println(r)
server.BroadcastTo(room, moveMade, r)
} else {
log.Debug("No room assigned for", so.Id())
so.Emit(serverError, ErrorResponse(serverError, "Not in any Room"))
}
})
})
port := c.String("port")
http.Handle("/socket.io/", s)
http.Handle("/", http.FileServer(http.Dir("./asset")))
log.Println("Serving at localhost:" + port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
// WrapResponse wraps the data we want to send in our response struct and adds
// the Timestamp and kind of response.
func WrapResponse(kind string, data interface{}) Response {
return Response{
Timestamp: time.Now().UnixNano(),
Kind: kind,
Data: data,
}
}
// ErrorResponse is a method for creating errors more quickly.
// It takes the error string and then calls WrapResponse internally to wrap the
// data
func ErrorResponse(kind, err string) Response {
d := map[string]interface{}{}
d["error"] = err
return WrapResponse(kind, d)
}
// ReadGameFiles reads the provided directory for files that conform to the
// game struct definition, these must be json files, and loads them into our
// game map.
func ReadGameFiles(gameDir string) (domain.GameMap, error) {
files, err := filepath.Glob(gameDir + "/*.toml")
if len(files) == 0 {
return nil, errors.New("Unable to find games. Does games directory exist?")
}
gm := domain.GameMap{}
if err != nil {
return nil, err
}
for _, f := range files {
raw, err := os.Open(f)
defer raw.Close()
if err != nil {
return nil, err
}
r := io.Reader(raw)
dummy := domain.Game{}
if meta, err := toml.DecodeReader(r, &dummy); err != nil {
log.Error(meta)
return nil, errors.New("Invalid configuration in file: " + f)
}
if dummy.MinPlayers == 0 {
return nil, errors.New("Invalid configuration in file: must provide minPlayers" + f)
}
g := domain.Game{
MinPlayers: dummy.MinPlayers,
MaxPlayers: dummy.MaxPlayers,
Title: dummy.Title,
UUID: dummy.UUID,
Lobby: domain.NewLobby(),
}
g.FileName = f
if _, exists := gm[g.UUID]; exists {
return nil, errors.New("uniqueKey conflict between: " + f + " and " +
gm[g.UUID].FileName)
}
gm[g.UUID] = g
}
return gm, nil
}
// TurnKey returns the generated key for storing turns
func TurnKey(playerID, roomName string) string {
return roomName + ":" + playerID
}
func main() {
app := cli.NewApp()
app.Name = "Toto"
app.Usage = "a server for creating quick prototype websocket based games."
app.Action = StartServer
app.Version = Version
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "port, p",
Value: "3000",
Usage: "The port to run the server on",
},
}
app.Run(os.Args)
}
| {
"content_hash": "9753fb6c2b07c7a2c7c085209c9d866c",
"timestamp": "",
"source": "github",
"line_count": 366,
"max_line_length": 87,
"avg_line_length": 29.505464480874316,
"alnum_prop": 0.6732104824520789,
"repo_name": "tiltfactor/toto",
"id": "a9049318663e0b56b0ecc580082441ed81b8350f",
"size": "10799",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "main.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "17396"
},
{
"name": "HTML",
"bytes": "1517"
}
],
"symlink_target": ""
} |
namespace BundleTransformer.Csso.Internal
{
/// <summary>
/// CSS optimization options
/// </summary>
internal sealed class OptimizationOptions
{
/// <summary>
/// Gets or sets a flag for whether to enable structure minification
/// </summary>
public bool Restructure
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to enable unsafe merge of <code>@media</code> rules
/// </summary>
public bool ForceMediaMerge
{
get;
set;
}
/// <summary>
/// Gets or sets a comments mode
/// </summary>
public CommentsMode Comments
{
get;
set;
}
/// <summary>
/// Constructs a instance of the CSS optimization options
/// </summary>
public OptimizationOptions()
{
Restructure = true;
ForceMediaMerge = false;
Comments = CommentsMode.Exclamation;
}
}
} | {
"content_hash": "881568a6841aeb24b43fd69d6ae35535",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 89,
"avg_line_length": 19.17391304347826,
"alnum_prop": 0.6077097505668935,
"repo_name": "Taritsyn/BundleTransformer",
"id": "85544504b71b01f71b583de56f7b207a10baafbd",
"size": "884",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/BundleTransformer.Csso/Internal/OptimizationOptions.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "1007432"
},
{
"name": "JavaScript",
"bytes": "8033603"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System.Linq;
using System.Text;
public abstract class Race
{
//private int length;
//private string route;
//private int prizePool;
//private List<Car> participants;
public Race(int length, string route, int prizePool)
{
this.Length = length;
this.Route = route;
this.PrizePool = prizePool;
this.Participants = new Dictionary<int, Car>();
this.Winners = new List<Car>();
}
public int Length { get; set; }
public string Route { get; set; }
public int PrizePool { get; set; }
public Dictionary<int,Car> Participants { get; set; }
public List<Car> Winners { get; set; }
public abstract int GetPerformance(int id);
public Dictionary<int,Car> GetWinners()
{
var winners = this.Participants
.OrderByDescending(n => this.GetPerformance(n.Key))
.Take(3)
.ToDictionary(n => n.Key, m => m.Value);
return winners;
}
public List<int> GetPrizes()
{
var result = new List<int>();
result.Add((this.PrizePool * 50) / 100);
result.Add((this.PrizePool * 30) / 100);
result.Add((this.PrizePool * 20) / 100);
return result;
}
public string StartRace()
{
var winners = GetWinners();
var prizes = GetPrizes();
StringBuilder sb = new StringBuilder();
sb.AppendLine($"{Route} - {Length}");
for (int i = 0; i < winners.Count; i++)
{
var car = winners.ElementAt(i);
sb.AppendLine($"{i + 1}. {car.Value.Brand} {car.Value.Model} {this.GetPerformance(car.Key)}PP - ${prizes[i]}");
}
return sb.ToString().Trim();
}
}
| {
"content_hash": "642b95100b62419ff71f99f4954817a2",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 123,
"avg_line_length": 28.14516129032258,
"alnum_prop": 0.5765042979942694,
"repo_name": "Plotso/SoftUni",
"id": "749fc3f03086e2f8cb6ab57a59f2a30c1daa471f",
"size": "1747",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CSharpOOP Basics-Exams/NFS/NFS/Entities/Races/Race.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "598508"
}
],
"symlink_target": ""
} |
This repository contains the Bot related code for a generalized tracking software as well as the backend logic to fill the bot with executive life.

| {
"content_hash": "e9fd51e2e35ae592b13b5b374dcb7e9a",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 147,
"avg_line_length": 79.66666666666667,
"alnum_prop": 0.803347280334728,
"repo_name": "codePrincess/funkyBot",
"id": "68b41ad4f9c1bdb14d5817930f896c2a11722a48",
"size": "265",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "103"
},
{
"name": "C#",
"bytes": "40003"
},
{
"name": "HTML",
"bytes": "455"
},
{
"name": "PowerShell",
"bytes": "3332"
},
{
"name": "Ruby",
"bytes": "3384"
},
{
"name": "Shell",
"bytes": "5947"
}
],
"symlink_target": ""
} |
const std::string CLIENT_NAME("Satoshi");
// Client version number
#define CLIENT_VERSION_SUFFIX "-beta-gravity"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "$Format:%h$"
# define GIT_COMMIT_DATE "$Format:%cD$"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
| {
"content_hash": "647144a44bb4764980467481c78d5c5a",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 155,
"avg_line_length": 40.32727272727273,
"alnum_prop": 0.7051397655545536,
"repo_name": "nakamotoSAMtoshi/sCoin",
"id": "8f29139d26fbe8e1807ff2adde775faf6624ed1d",
"size": "2638",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/version.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "102799"
},
{
"name": "C++",
"bytes": "2515148"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "IDL",
"bytes": "14684"
},
{
"name": "Objective-C",
"bytes": "5864"
},
{
"name": "Python",
"bytes": "69706"
},
{
"name": "Shell",
"bytes": "9702"
},
{
"name": "TypeScript",
"bytes": "5236293"
}
],
"symlink_target": ""
} |
import { notEmpty } from './notEmpty';
import { tooManyArguments } from './tooManyArguments';
import { exists } from './exists';
export default {
rules: {
notEmpty,
tooManyArguments,
exists
},
configs: {
recommended: {
plugins: ['require-path-exists'],
rules: {
'require-path-exists/notEmpty': 2,
'require-path-exists/tooManyArguments': 2,
'require-path-exists/exists': [ 2, { extensions: ['', '.js', '.json', '.node'] }]
}
}
}
};
| {
"content_hash": "14eb5b06e7c46fe812688199e13a5f76",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 90,
"avg_line_length": 23.952380952380953,
"alnum_prop": 0.5745526838966203,
"repo_name": "BohdanTkachenko/eslint-plugin-require-path-exists",
"id": "03df09d23d3f2f37bf74802a8a2010e5f6b2c61c",
"size": "503",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "4887"
},
{
"name": "Makefile",
"bytes": "214"
}
],
"symlink_target": ""
} |
//
// Copyright (C) OpenSim Ltd.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//
#ifndef __INET_MEDIUMVISUALIZERBASE_H
#define __INET_MEDIUMVISUALIZERBASE_H
#include "inet/physicallayer/contract/packetlevel/IRadioMedium.h"
#include "inet/visualizer/base/VisualizerBase.h"
#include "inet/visualizer/util/ColorSet.h"
#include "inet/visualizer/util/Displacement.h"
#include "inet/visualizer/util/InterfaceFilter.h"
#include "inet/visualizer/util/NetworkNodeFilter.h"
#include "inet/visualizer/util/PacketFilter.h"
namespace inet {
namespace visualizer {
using namespace inet::physicallayer;
class INET_API MediumVisualizerBase : public VisualizerBase, public cListener
{
protected:
enum SignalShape
{
SIGNAL_SHAPE_RING,
SIGNAL_SHAPE_SPHERE,
SIGNAL_SHAPE_BOTH,
};
protected:
/** @name Parameters */
//@{
IRadioMedium *radioMedium = nullptr;
NetworkNodeFilter networkNodeFilter;
InterfaceFilter interfaceFilter;
PacketFilter packetFilter;
bool displaySignals = false;
ColorSet signalColorSet;
double signalPropagationAnimationSpeed = NaN;
double signalPropagationAnimationTime = NaN;
double signalPropagationAdditionalTime = NaN;
double signalTransmissionAnimationSpeed = NaN;
double signalTransmissionAnimationTime = NaN;
double signalAnimationSpeedChangeTime = NaN;
bool displayTransmissions = false;
bool displayReceptions = false;
Displacement transmissionDisplacementHint;
Displacement receptionDisplacementHint;
double transmissionDisplacementPriority;
double receptionDisplacementPriority;
bool displayInterferenceRanges = false;
cFigure::Color interferenceRangeLineColor;
cFigure::LineStyle interferenceRangeLineStyle;
double interferenceRangeLineWidth = NaN;
bool displayCommunicationRanges = false;
cFigure::Color communicationRangeLineColor;
cFigure::LineStyle communicationRangeLineStyle;
double communicationRangeLineWidth = NaN;
//@}
/** @name State */
//@{
double defaultSignalPropagationAnimationSpeed = NaN;
double defaultSignalTransmissionAnimationSpeed = NaN;
//@}
protected:
virtual void initialize(int stage) override;
virtual void handleParameterChange(const char *name) override;
virtual bool isSignalPropagationInProgress(const ITransmission *transmission) const;
virtual bool isSignalTransmissionInProgress(const ITransmission *transmission) const;
virtual bool matchesTransmission(const ITransmission *transmission) const;
virtual void radioAdded(const IRadio *radio) = 0;
virtual void radioRemoved(const IRadio *radio) = 0;
virtual void transmissionAdded(const ITransmission *transmission) = 0;
virtual void transmissionRemoved(const ITransmission *transmission) = 0;
virtual void transmissionStarted(const ITransmission *transmission) = 0;
virtual void transmissionEnded(const ITransmission *transmission) = 0;
virtual void receptionStarted(const IReception *reception) = 0;
virtual void receptionEnded(const IReception *reception) = 0;
public:
virtual ~MediumVisualizerBase();
virtual void receiveSignal(cComponent *source, simsignal_t signal, cObject *object, cObject *details) override;
};
} // namespace visualizer
} // namespace inet
#endif // ifndef __INET_MEDIUMVISUALIZERBASE_H
| {
"content_hash": "f33ec0d21d929e47bd5b48a40e3ba7b5",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 115,
"avg_line_length": 35.336283185840706,
"alnum_prop": 0.7613323315802655,
"repo_name": "LarryNguyen/ECSimpp",
"id": "e4f4a7b1d6d4da21c66be6299d04fed190a1ab23",
"size": "3993",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "INET_EC/visualizer/base/MediumVisualizerBase.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "61045"
},
{
"name": "C++",
"bytes": "18067164"
},
{
"name": "Lex",
"bytes": "13424"
},
{
"name": "Makefile",
"bytes": "6640"
},
{
"name": "Objective-C",
"bytes": "4651"
},
{
"name": "Shell",
"bytes": "173"
},
{
"name": "Yacc",
"bytes": "67181"
}
],
"symlink_target": ""
} |
<h2 data-i18n="power.battery"></h2>
<div id="battery-msg" data-i18n="listing.loading" class="col-lg-12 text-center"></div>
<div id="battery-view" class="row hide">
<div class="col-md-5">
<table class="table table-striped">
<tr>
<th data-i18n="power.manufacture_date"></th>
<td id="battery-manufacture_date"></td>
</tr>
<tr>
<th data-i18n="power.design_capacity"></th>
<td id="battery-design_capacity"></td>
</tr>
<tr>
<th data-i18n="power.max_capacity"></th>
<td id="battery-max_capacity"></td>
</tr>
<tr>
<th data-i18n="power.max_percent"></th>
<td id="battery-max_percent"></td>
</tr>
<tr>
<th data-i18n="power.current_capacity"></th>
<td id="battery-current_capacity"></td>
</tr>
<tr>
<th data-i18n="power.current_percent"></th>
<td id="battery-current_percent"></td>
</tr>
<tr>
<th data-i18n="power.cycle_count"></th>
<td id="battery-cycle_count"></td>
</tr>
<tr>
<th data-i18n="power.designcyclecount"></th>
<td id="battery-designcyclecount"></td>
</tr>
<tr>
<th data-i18n="power.condition"></th>
<td id="battery-condition"></td>
</tr>
<tr>
<th data-i18n="power.temperature"></th>
<td id="battery-temperature"></td>
</tr>
<tr>
<th data-i18n="power.externalconnected"></th>
<td id="battery-externalconnected"></td>
</tr>
<tr>
<th data-i18n="power.ischarging"></th>
<td id="battery-ischarging"></td>
</tr>
<tr>
<th data-i18n="power.fullycharged"></th>
<td id="battery-fullycharged"></td>
</tr>
<tr>
<th data-i18n="power.avgtimetofull"></th>
<td id="battery-avgtimetofull"></td>
</tr>
<tr>
<th data-i18n="power.avgtimetoempty"></th>
<td id="battery-avgtimetoempty"></td>
</tr>
<tr>
<th data-i18n="power.timeremaining"></th>
<td id="battery-timeremaining"></td>
</tr>
<tr>
<th data-i18n="power.instanttimetoempty"></th>
<td id="battery-instanttimetoempty"></td>
</tr>
<tr>
<th id="battery-watt-label"></th>
<td id="battery-watts"></td>
</tr>
<tr>
<th data-i18n="power.amperage"></th>
<td id="battery-amperage"></td>
</tr>
<tr>
<th data-i18n="power.voltage"></th>
<td id="battery-voltage"></td>
</tr>
<tr>
<th data-i18n="power.cellvoltage"></th>
<td id="battery-cellvoltage"></td>
</tr>
<tr>
<th data-i18n="power.permanentfailurestatus"></th>
<td id="battery-permanentfailurestatus"></td>
</tr>
<tr>
<th data-i18n="power.manufacturer"></th>
<td id="battery-manufacturer"></td>
</tr>
<tr>
<th data-i18n="power.batteryserialnumber"></th>
<td id="battery-batteryserialnumber"></td>
</tr>
<tr>
<th data-i18n="power.packreserve"></th>
<td id="battery-packreserve"></td>
</tr>
</table>
</div>
<div class="col-md-4">
<table class="table table-striped">
<tr>
<th data-i18n="power.adapter_wattage"></th>
<td id="battery-wattage"></td>
</tr>
<tr>
<th data-i18n="power.adapter_id"></th>
<td id="battery-adapter_id"></td>
</tr>
<tr>
<th data-i18n="power.family_code"></th>
<td id="battery-family_code"></td>
</tr>
<tr>
<th data-i18n="power.adapter_serial_number"></th>
<td id="battery-adapter_serial_number"></td>
</tr>
</table>
</div>
</div>
<script>
$(document).on('appReady', function(e, lang) {
// Get power data
$.getJSON( appUrl + '/module/power/get_data/' + serialNumber, function( data ) {
if( data.condition == ''){
$('#battery-msg').text(i18n.t('no_data'));
}
else{
// Hide
$('#battery-msg').text('');
$('#battery-view').removeClass('hide');
// Add strings
$('#battery-adapter_id').text(data.adapter_id);
$('#battery-family_code').text(data.family_code);
$('#battery-adapter_serial_number').text(data.adapter_serial_number);
// Format wattage
if (data.wattage != "-9876543" && (data.wattage)) {
$('#battery-wattage').html(data.wattage+" "+i18n.t('power.watts'));
} else {
$('#battery-wattage').html('');
}
// Format timeremaining
if(data.timeremaining == "-9876543" || data.timeremaining == -9876543 || data.manufacture_date == '1980-00-00' || data.fullycharged == 'Yes') {
$('#battery-timeremaining').text('');
} else {
$('#battery-timeremaining').html('<span title="'+data.timeremaining+' '+i18n.t('power.minutes')+'">'+moment.duration(+data.timeremaining, "minutes").humanize());
}
// Format instanttimetoempty
if(data.instanttimetoempty == "-9876543" || data.instanttimetoempty == -9876543) {
$('#battery-instanttimetoempty').text('');
} else {
$('#battery-instanttimetoempty').html('<span title="'+data.instanttimetoempty+' '+i18n.t('power.minutes')+'">'+moment.duration(+data.instanttimetoempty, "minutes").humanize());
}
// Format avgtimetofull
if(data.avgtimetofull == "-9876543" || data.avgtimetofull == -9876543) {
$('#battery-avgtimetofull').text('');
} else {
$('#battery-avgtimetofull').html('<span title="'+data.avgtimetofull+' '+i18n.t('power.minutes')+'">'+moment.duration(+data.avgtimetofull, "minutes").humanize());
}
// Format avgtimetoempty
if(data.avgtimetoempty == "-9876543" || data.avgtimetoempty == -9876543) {
$('#battery-avgtimetoempty').text('');
} else {
$('#battery-avgtimetoempty').html('<span title="'+data.avgtimetoempty+' '+i18n.t('power.minutes')+'">'+moment.duration(+data.avgtimetoempty, "minutes").humanize());
}
// Format ischarging
if(data.ischarging === "Yes") {
$('#battery-ischarging').text(i18n.t('yes'));
} else if(data.ischarging === "No") {
$('#battery-ischarging').text(i18n.t('no'));
} else{
$('#battery-ischarging').text("");
}
// Format fullycharged
if(data.fullycharged === "Yes") {
$('#battery-fullycharged').text(i18n.t('yes'));
} else if(data.fullycharged === "No") {
$('#battery-fullycharged').text(i18n.t('no'));
} else{
$('#battery-fullycharged').text("");
}
// Format permanentfailurestatus
if (data.permanentfailurestatus != "-9876543" && (data.permanentfailurestatus)) {
$('#battery-permanentfailurestatus').text("");
} else if(data.permanentfailurestatus === "1" || data.permanentfailurestatus === 1) {
$('#battery-permanentfailurestatus').addClass('danger').html(i18n.t('yes'));
} else if(data.permanentfailurestatus === "0" || data.permanentfailurestatus === 0) {
$('#battery-permanentfailurestatus').html(i18n.t('no'));
} else{
$('#battery-permanentfailurestatus').text('');
}
// Format externalconnected
if(data.externalconnected === "Yes") {
$('#battery-externalconnected').text(i18n.t('yes'));
} else if(data.externalconnected === "No") {
$('#battery-externalconnected').text(i18n.t('no'));
} else{
$('#battery-externalconnected').text("");
}
// Format batteryserialnumber
if (data.batteryserialnumber != "-9876543" && (data.batteryserialnumber)) {
$('#battery-batteryserialnumber').html(data.batteryserialnumber);
} else {
$('#battery-batteryserialnumber').html('');
}
// Format packreserve
if (data.packreserve != "-9876543" && (data.packreserve)) {
$('#battery-packreserve').html(data.packreserve+" mAh");
} else {
$('#battery-packreserve').html('');
}
// Format manufacturer
if (data.manufacturer != "-9876543" && (data.manufacturer)) {
$('#battery-manufacturer').html(data.manufacturer);
} else {
$('#battery-manufacturer').html('');
}
// Format cell voltage
if (data.cellvoltage != "." && (data.cellvoltage)) {
$('#battery-cellvoltage').html(data.cellvoltage+"v");
} else {
$('#battery-cellvoltage').html('');
}
// Format voltage
if (data.voltage != "-9876540" && (data.voltage)) {
$('#battery-voltage').html(data.voltage+" "+i18n.t('power.volts'));
} else {
$('#battery-voltage').html('');
}
// Format amperage
if (data.amperage != "-9876540" && (data.amperage)) {
$('#battery-amperage').html(data.amperage+" "+i18n.t('power.amps'));
} else {
$('#battery-amperage').html('');
}
// Calculate charge/discharge watts
// null amperage and voltage is -9876540
if (data.amperage != "-9876540" && (data.amperage) && data.voltage != "-9876540" && (data.voltage)) {
$('#battery-watts').html((data.amperage*data.voltage).toFixed(2)+" "+i18n.t('power.watts'));
if (data.amperage >= 0) {
$('#battery-watt-label').html(i18n.t('power.charging_watt'));
} else {
$('#battery-watt-label').html(i18n.t('power.discharging_watt'));
}
} else if (data.amperage == "0" || data.amperage == 0 ) {
$('#battery-watts').html('');
$('#battery-watt-label').html(i18n.t('power.watts'));
} else {
$('#battery-watts').html('');
$('#battery-watts-label').html(i18n.t('power.watts'));
}
// Format cycle count
if (data.cycle_count != "-9876543" && (data.cycle_count)) {
$('#battery-cycle_count').html(data.cycle_count);
} else {
$('#battery-cycle_count').html('');
}
// Format designcyclecount
if (data.designcyclecount != "-9876543" && (data.designcyclecount)) {
$('#battery-designcyclecount').html(data.designcyclecount);
} else {
$('#battery-designcyclecount').html('');
}
// Format designed capacity
if (data.design_capacity != "-9876543" && (data.design_capacity)) {
$('#battery-design_capacity').html(data.design_capacity+' mAh');
} else {
$('#battery-design_capacity').html('');
}
// Format current capacity
if (data.current_capacity != "-9876543" && (data.current_capacity)) {
$('#battery-current_capacity').html(data.current_capacity+' mAh');
} else {
$('#battery-current_capacity').html('');
}
// Format max capacity
if (data.max_capacity != "-9876543" && (data.max_capacity)) {
$('#battery-max_capacity').html(data.max_capacity+' mAh');
} else {
$('#battery-max_capacity').html('');
}
// Format Manufacture date
if(data.manufacture_date === '1980-00-00'){
$('#battery-manufacture_date').addClass('danger').html(i18n.t('power.widget.now'));
} else {
if(data.manufacture_date){
a = moment(data.manufacture_date)
b = a.diff(moment(), 'years', true)
if(a.diff(moment(), 'years', true) < -4)
{
$('#battery-manufacture_date').addClass('danger')
}
if(Math.round(b) == 4)
{
}
$('#battery-manufacture_date').html('<span title="'+data.manufacture_date+'">'+moment(data.manufacture_date).fromNow());
}
}
// Format battery condition
data.condition = data.condition == 'Normal' ? '<span class="label label-success">'+i18n.t('power.widget.normal')+'</span>' :
data.condition = data.condition == 'Replace Soon' ? '<span class="label label-warning">'+i18n.t('power.widget.service')+'</span>' :
data.condition = data.condition == 'ReplaceSoon' ? '<span class="label label-warning">'+i18n.t('power.widget.service')+'</span>' :
data.condition = data.condition == 'Service Battery' ? '<span class="label label-warning">'+i18n.t('power.widget.check')+'</span>' :
data.condition = data.condition == 'ServiceBattery' ? '<span class="label label-warning">'+i18n.t('power.widget.check')+'</span>' :
data.condition = data.condition == 'Check Battery' ? '<span class="label label-warning">'+i18n.t('power.widget.now')+'</span>' :
data.condition = data.condition == 'CheckBattery' ? '<span class="label label-warning">'+i18n.t('power.widget.now')+'</span>' :
data.condition = data.condition == 'Replace Now' ? '<span class="label label-danger">'+i18n.t('power.widget.now')+'</span>' :
data.condition = data.condition == 'ReplaceNow' ? '<span class="label label-danger">'+i18n.t('power.widget.now')+'</span>' :
data.condition = data.condition == '' ? '<span class="label label-danger">'+i18n.t('power.widget.nobattery')+'</span>' :
(data.condition === 'No Battery' ? '<span class="label label-danger">'+i18n.t('power.widget.nobattery')+'</span>' : '')
$('#battery-condition').html(data.condition)
// Format battery health
if (data.max_percent != "-9876543" && (data.max_percent)) {
var cls = data.max_percent > 89 ? 'success' : (data.max_percent > 79 ? 'warning' : 'danger');
$('#battery-max_percent').html('<div class="progress"><div class="progress-bar progress-bar-'+cls+'" style="width: '+data.max_percent+'%;">'+data.max_percent+'%</div></div>');
} else {
$('#battery-max_percent').html('');
}
// Format battery charge
if (data.current_percent != "-9876543" && (data.current_percent)) {
var cls = data.current_percent > 89 ? 'success' : (data.current_percent > 79 ? 'warning' : 'danger');
$('#battery-current_percent').html('<div class="progress"><div class="progress-bar progress-bar-'+cls+'" style="width: '+data.current_percent+'%;">'+data.current_percent+'%</div></div>');
} else {
$('#battery-current_percent').html('');
}
// Format temperature
if (data.temperature != "-9876543" && (data.temperature) && data.temperature !== 0) {
if (data.temp_format === "F"){
var outtemp_c = (data.temperature / 100)+"°C";
var outtemp_f = (((data.temperature * 9/5) + 3200) / 100).toFixed(2)+"°F";
$('#battery-temperature').html('<span title="'+outtemp_c+'">'+outtemp_f+'</span>')
} else {
var outtemp_c = (data.temperature / 100)+"°C";
var outtemp_f = (((data.temperature * 9/5) + 3200) / 100).toFixed(2)+"°F";
$('#battery-temperature').html('<span title="'+outtemp_f+'">'+outtemp_c+'</span>')
}
} else {
$('#battery-temperature').text("");
}
}
});
});
</script>
| {
"content_hash": "b232144c803c6ab2d3d006b4935e47c3",
"timestamp": "",
"source": "github",
"line_count": 386,
"max_line_length": 199,
"avg_line_length": 39.1580310880829,
"alnum_prop": 0.5452861395964274,
"repo_name": "childrss/munkireport-php",
"id": "3df5eba6963f62412b2ad4910458d77de3ee5d17",
"size": "15119",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/modules/power/views/battery_tab.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2283"
},
{
"name": "CSS",
"bytes": "11338"
},
{
"name": "HTML",
"bytes": "709"
},
{
"name": "Hack",
"bytes": "16917"
},
{
"name": "JavaScript",
"bytes": "97308"
},
{
"name": "Makefile",
"bytes": "467"
},
{
"name": "PHP",
"bytes": "1656522"
},
{
"name": "Python",
"bytes": "113543"
},
{
"name": "Shell",
"bytes": "84151"
}
],
"symlink_target": ""
} |
package org.jsondoc.core.pojo;
import java.util.Map;
import java.util.Set;
import org.jsondoc.core.pojo.flow.ApiFlowDoc;
import org.jsondoc.core.pojo.global.ApiGlobalDoc;
public class JSONDoc {
private String version;
private String basePath;
// The key is the group these apis belongs to. It can be empty.
private Map<String, Set<ApiDoc>> apis;
// The key is the group these objects belongs to. It can be empty.
private Map<String, Set<ApiObjectDoc>> objects;
// The key is the group these flows belongs to. It can be empty.
private Map<String, Set<ApiFlowDoc>> flows;
private ApiGlobalDoc global;
private boolean playgroundEnabled;
private MethodDisplay displayMethodAs;
public enum MethodDisplay {
URI, SUMMARY, METHOD;
}
public JSONDoc(String version, String basePath) {
super();
this.version = version;
this.basePath = basePath;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Map<String, Set<ApiObjectDoc>> getObjects() {
return objects;
}
public Map<String, Set<ApiDoc>> getApis() {
return apis;
}
public void setApis(Map<String, Set<ApiDoc>> apis) {
this.apis = apis;
}
public void setObjects(Map<String, Set<ApiObjectDoc>> objects) {
this.objects = objects;
}
public String getBasePath() {
return basePath;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public Map<String, Set<ApiFlowDoc>> getFlows() {
return flows;
}
public void setFlows(Map<String, Set<ApiFlowDoc>> flows) {
this.flows = flows;
}
public boolean isPlaygroundEnabled() {
return playgroundEnabled;
}
public void setPlaygroundEnabled(boolean playgroundEnabled) {
this.playgroundEnabled = playgroundEnabled;
}
public MethodDisplay getDisplayMethodAs() {
return displayMethodAs;
}
public void setDisplayMethodAs(MethodDisplay displayMethodAs) {
this.displayMethodAs = displayMethodAs;
}
public ApiGlobalDoc getGlobal() {
return global;
}
public void setGlobal(ApiGlobalDoc global) {
this.global = global;
}
@Override
public String toString() {
return "JSONDoc [version=" + version + ", basePath=" + basePath + ", apis=" + apis + ", objects=" + objects + ", flows=" + flows + ", global=" + global + ", playgroundEnabled=" + playgroundEnabled + ", displayMethodAs=" + displayMethodAs + "]";
}
}
| {
"content_hash": "0ef82b00961672ee6aebdff6eae9d9ef",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 246,
"avg_line_length": 23.584158415841586,
"alnum_prop": 0.7212426532325776,
"repo_name": "fabiomaffioletti/jsondoc",
"id": "8cb3031be999da04f071acc8e7880bb51a777535",
"size": "2382",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jsondoc-core/src/main/java/org/jsondoc/core/pojo/JSONDoc.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3106"
},
{
"name": "HTML",
"bytes": "78611"
},
{
"name": "Java",
"bytes": "332602"
},
{
"name": "JavaScript",
"bytes": "50085"
},
{
"name": "Shell",
"bytes": "819"
}
],
"symlink_target": ""
} |
UI.Dialog = function(options)
{
this.options = Alpha.mergeObjects({
id: '',
className: '',
titlebar: true,
title: '',
position: 'center',
onClose: 'destroy',
modal: false,
closeOnEscape: true
}, options || {});
this.bounds = {};
UI.Window.prototype.createContainer.call(this);
this.container.className = 'dialog ' + this.options.className;
if (this.options.titlebar) {
this.createTitlebar();
}
UI.Window.prototype.createContent.call(this);
if (this.options.modal)
{
this.overlay = new UI.Overlay();
this.overlay.display();
}
}
UI.Dialog.prototype = new UI.Window();
UI.Dialog.prototype.createTitlebar = function()
{
this.title = document.createElement('span');
this.title.className = 'title';
this.title.innerHTML = this.options.title;
var close = document.createElement('a');
close.innerHTML = '<span>X</span>';
close.addEventListener('click', this.onClose.bind(this), false);
this.titlebar = document.createElement('div');
this.titlebar.className = 'titlebar';
this.titlebar.appendChild(this.title);
this.titlebar.appendChild(close);
this.container.insertBefore(this.titlebar, this.container.firstChild);
}
UI.Dialog.prototype.setPosition = function()
{
var position = {top: false, right: false, bottom: false, left: false};
if (this.options.position.forEach)
{
this.options.position.forEach(function(pos) {
position[pos] = true;
});
}
else {
position[this.options.position] = true;
}
this.container.setStyle({position: 'absolute'});
var style = {};
if (position.top) {
style.top = 0;
}
else if (position.bottom) {
style.bottom = 0;
}
else
{
style.top = parseInt(Math.max(0, (window.innerHeight || document.documentElement.clientHeight) - this.container.offsetHeight) / 2
+ (document.documentElement ? document.documentElement.scrollTop : window.pageYOffset)) + 'px';
}
if (position.left) {
style.left = 0;
}
else if (position.right) {
style.right = 0;
}
else
{
style.left = parseInt(Math.max(0, (window.innerWidth || document.documentElement.clientWidth) - this.container.offsetWidth) / 2
+ (document.documentElement ? document.documentElement.scrollLeft : window.pageXOffset)) + 'px';
}
UI.Window.prototype.setPosition.call(this, style);
}
UI.Dialog.prototype.display = function()
{
if (this.options.modal) {
this.overlay.display();
}
UI.Window.prototype.display.call(this);
}
UI.Dialog.prototype.destroy = function()
{
if (this.options.modal) {
this.overlay.destroy();
}
delete this.title;
delete this.titlebar;
UI.Window.prototype.destroy.call(this);
}
UI.Dialog.prototype.setTitle = function(title) {
this.title.innerHTML = title;
}
| {
"content_hash": "dd32654efa7565bab661bdd5cbeaad35",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 133,
"avg_line_length": 24.333333333333332,
"alnum_prop": 0.6561292588689849,
"repo_name": "ysbaddaden/alpha",
"id": "0165b6602b7134454c4e95904b69655e101d2ce7",
"size": "3075",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/ui/dialog.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "200643"
},
{
"name": "Python",
"bytes": "9093"
},
{
"name": "Ruby",
"bytes": "733"
}
],
"symlink_target": ""
} |
/* author: James Lyons
Aug 2012
use e.g. http://practicalcryptography.com/ciphers/mechanical-era/enigma/ to generate messages
this code is from http://www.practicalcryptography.com/cryptanalysis/breaking-machine-ciphers/cryptanalysis-enigma-part-2/
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "typex_perms.h"
#include "NBestList.h"
#include "scoreText.h"
TypexKey *break_typex(char* ctext);
float entropy_score(char *text);
// cipher text variable must be all capitals, with no spacing or punctuation, use e.g. http://practicalcryptography.com/ciphers/mechanical-era/enigma/
// to generate messages. This version can break messages with plugs, but both the original plaintext and corresponding ciphertext are required.
// This program determines the key used. 'otext' is the original plaintext, 'ctext' is the ciphertext
char ctext[] = "VDGTQAGBWMMIFJBKVZAPJUZCZQXN";
/******************************************************************
main - cracks the typex ciphertext stored in ctext, prints the result.
*******************************************************************/
int main(int argc, char *argv[]){
char *ptext = malloc(sizeof(char)*(strlen(ctext)+1));
/*char *ptext1 = malloc(sizeof(char)*(strlen(ctext)+1));
TypexKey *ref = malloc(sizeof(TypexKey));
initTypexKey(ref);
//ref = break_typex(ctext);
//printf("final key: \n");
//printTypexKey(ref);
typex(ref,ctext,ptext);
//initTypexKey(ref);
//typex(ref,ptext,ptext1);
printf("decryption: %s\n",ptext);
free(ptext);
free(ref);*/
TypexKey *ref;
ref = break_typex(ctext);
printf("final key: \n");
printTypexKey(ref);
typex(ref,ctext,ptext);
printf("decryption: %s\n",ptext);
free(ptext);
free(ref);
}
// All possible permutations of 5 rotors, there are 60 total
extern char perms[][5];
extern int NPERMS;
NBestList *base = NULL;
/******************************************************************
Given a piece of ciphertext 'ctext', return the typex decryption key
******************************************************************/
TypexKey *break_typex(char* ctext){
int i,j;
char *ptext = malloc(sizeof(char)*(strlen(ctext)+1));
TypexKey key;
TypexKey *bestkey = malloc(sizeof(TypexKey));
TypexKey store;
char ind1,ind2,ind3=0,ind4=0,ind5=0;
float bestscore,score;
initTypexKey(bestkey);
printf("searching for rotors: ");
for(i=0;i<NPERMS;i++){
for(ind1=0;ind1<26;ind1++){
for(ind2=0;ind2<26;ind2++){
for(ind3=0;ind3<26;ind3++){
for(ind4=0;ind4<26;ind4++){
for(ind5=0;ind5<26;ind5++){
key = *bestkey;
key.rotors[0] = perms[i][0];
key.rotors[1] = perms[i][1];
key.rotors[2] = perms[i][2];
key.rotors[3] = perms[i][3];
key.rotors[4] = perms[i][4];
key.indicator[0] = ind1;
key.indicator[1] = ind2;
key.indicator[2] = ind3;
key.indicator[3] = ind4;
key.indicator[4] = ind5;
store = key; typex(&store,ctext,ptext);
score = -scoreTextQgram(ptext,strlen(ptext));
base = nbest_add(base,&key,score);
}
}
}
}
}
printf("%d\n",i); fflush(stdout);
}
// we have the optimal indicators and rotors, search for the optimal ringsettings
store = base->key;
*bestkey = store;
free(ptext);
freeList(base);
return bestkey;
}
| {
"content_hash": "9cb72ad49ce49db06488814c7b4a10f1",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 150,
"avg_line_length": 35.88461538461539,
"alnum_prop": 0.5498392282958199,
"repo_name": "jameslyons/c_cryptanalysis",
"id": "1d3fe5b798e8ef2f24506345585d6f7386f0ae17",
"size": "3732",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "typex/break_typex.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "387994"
},
{
"name": "Python",
"bytes": "1362"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.7 (i3geoweather)" project-jdk-type="Python SDK" />
</project> | {
"content_hash": "f6514517d81e3543039c1b16af8a5472",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 128,
"avg_line_length": 50,
"alnum_prop": 0.71,
"repo_name": "joergdietrich/i3geoweather",
"id": "418da0717b03082c3e0ba9402eff7112bc6189ff",
"size": "200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/misc.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "19106"
}
],
"symlink_target": ""
} |
#pragma once
#include "Pockets.h"
#include "Types.h"
namespace pockets
{
typedef std::shared_ptr<class Locus2d> Locus2dRef;
/**
A nestable position and orientation in 2d space.
Will inherit transformations from a parent Locus, parents know nothing about
children. Inteded for use in an vector-like container for fast iteration, with
explicit evaluation of the transformation matrix.
*/
class Locus2d
{
public:
ci::vec2 getLoc() const { return mLoc; }
void setLoc( const ci::vec2 &loc ){ mLoc = loc; setDirty(); }
//! get local rotation
float getRotation() const { return mRotation; }
//! get final rotation after all parent transformations
float getAccumulatedRotation() const { return mParent ? mParent->getAccumulatedRotation() + mRotation : mRotation; }
//! set rotation to \a radians
void setRotation( float radians ){ mRotation = radians; setDirty(); }
//! increment rotation by \a radians
void rotate( float radians ){ mRotation += radians; setDirty(); }
//! returns the point around which rotation occurs, in local coordinates
ci::vec2 getRegistrationPoint() const { return mRegistrationPoint; }
//! set the point around which rotation occurs, in local coordinates
void setRegistrationPoint( const ci::vec2 &loc ){ mRegistrationPoint = loc; setDirty(); }
//! returns transformation matrix multiplied by parent (if any)
inline ci::mat4 getTransform() { calculateTransform(); return mParent ? mParent->getTransform() * mTransform : mTransform; }
inline ci::mat4 getTransform() const { return mParent ? mParent->getTransform() * mTransform : mTransform; }
//! returns this locus' local transformation matrix, with no parent transforms
inline ci::mat4 getLocalTransform() { calculateTransform(); return mTransform; }
inline ci::mat4 getLocalTransform() const { return mTransform; }
//! set a locus as a parent for this one; we then inherit transformations
void setParent( Locus2dRef parent ){ mParent = parent; }
//! stop having a parent locus
void unsetParent(){ mParent.reset(); }
//! calculates the local transformation matrix if it has changed
void calculateTransform();
//! we've made changes and will need updating
void setDirty(){ mDirty = true; }
//! conversion to mat4 for OpenGL transformation; just pass the Locus to gl::multModelView();
operator ci::mat4() const { return ci::mat4(getTransform()); }
Vertex2d transform( const Vertex2d &vertex ) const;
private:
ci::mat4 mTransform;
ci::vec2 mLoc = ci::vec2( 0 );
ci::vec2 mRegistrationPoint = ci::vec2( 0 );
float mRotation = 0.0f;
Locus2dRef mParent = nullptr;
bool mDirty = true;
};
} // pockets::
| {
"content_hash": "8050bd6451acd0f039a651d3a104fd7b",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 134,
"avg_line_length": 50.75,
"alnum_prop": 0.632512315270936,
"repo_name": "sansumbrella/Pockets",
"id": "a536af8f808ea282cf0c0c07a32889b9c53baf47",
"size": "4402",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/archive/blob/Locus.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "3388"
},
{
"name": "C++",
"bytes": "837554"
},
{
"name": "GLSL",
"bytes": "182"
},
{
"name": "Groff",
"bytes": "6242"
},
{
"name": "Lua",
"bytes": "738"
},
{
"name": "Makefile",
"bytes": "507"
},
{
"name": "Shell",
"bytes": "252"
}
],
"symlink_target": ""
} |
require 'google/apis/calendar_v3/service.rb'
require 'google/apis/calendar_v3/classes.rb'
require 'google/apis/calendar_v3/representations.rb'
require 'google/apis/calendar_v3/gem_version.rb'
module Google
module Apis
# Calendar API
#
# Manipulates events and other calendar data.
#
# @see https://developers.google.com/google-apps/calendar/firstapp
module CalendarV3
# Version of the Calendar API this client connects to.
# This is NOT the gem version.
VERSION = 'V3'
# See, edit, share, and permanently delete all the calendars you can access using Google Calendar
AUTH_CALENDAR = 'https://www.googleapis.com/auth/calendar'
# View and edit events on all your calendars
AUTH_CALENDAR_EVENTS = 'https://www.googleapis.com/auth/calendar.events'
# View events on all your calendars
AUTH_CALENDAR_EVENTS_READONLY = 'https://www.googleapis.com/auth/calendar.events.readonly'
# See and download any calendar you can access using your Google Calendar
AUTH_CALENDAR_READONLY = 'https://www.googleapis.com/auth/calendar.readonly'
# View your Calendar settings
AUTH_CALENDAR_SETTINGS_READONLY = 'https://www.googleapis.com/auth/calendar.settings.readonly'
end
end
end
| {
"content_hash": "4695c4dc6b5e4f12ee6add570103ccca",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 103,
"avg_line_length": 37.5,
"alnum_prop": 0.7176470588235294,
"repo_name": "googleapis/google-api-ruby-client",
"id": "0a440360150ec62392c6dd2fafd8cbc61b59c4ff",
"size": "1851",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "generated/google-apis-calendar_v3/lib/google/apis/calendar_v3.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ruby",
"bytes": "198322756"
},
{
"name": "Shell",
"bytes": "19549"
}
],
"symlink_target": ""
} |
package signer
import "time"
type Option func(*Signer)
func WithDataKey(key string) Option {
return func(s *Signer) {
s.claimsKey = key
}
}
func WithExpiration(exp time.Duration) Option {
return func(s *Signer) {
s.exp = exp
}
}
func WithSubject(sub string) Option {
return func(s *Signer) {
s.sub = optionalString{valid: true, value: sub}
}
}
func WithIssuer(iss string) Option {
return func(s *Signer) {
s.iss = optionalString{valid: true, value: iss}
}
}
| {
"content_hash": "26d4a941e1b3ca956bb1c29267160bd6",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 49,
"avg_line_length": 16.551724137931036,
"alnum_prop": 0.6854166666666667,
"repo_name": "GeorgeMac/hola",
"id": "4545a20e0b518beb17ced72e7c40f336662391be",
"size": "480",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/signer/options.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "21839"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN" "http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
<tiles-definitions>
<definition name="page" extends="base">
<put-attribute name="title" value="page.title" />
<put-attribute name="header" value="/WEB-INF/layouts/header.jsp" />
<put-attribute name="script" value="page" />
</definition>
<definition name="base" template="/WEB-INF/layouts/container.jsp">
<put-attribute name="footer" value="/WEB-INF/layouts/footer.jsp" />
</definition>
</tiles-definitions>
| {
"content_hash": "6d74edac87257ef0de0832f420f0ace1",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 152,
"avg_line_length": 40.75,
"alnum_prop": 0.6687116564417178,
"repo_name": "jegbjerg/webapp-base",
"id": "7ab8772a69ce5b426bd8f1157a34fa63c40bba65",
"size": "652",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/webapp/WEB-INF/layouts/tiles.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "35485"
},
{
"name": "JavaScript",
"bytes": "783"
}
],
"symlink_target": ""
} |
Neutral meson analysis in $pp$ at 13 TeV
=========================================
Main code to analyse LHC16 proton-proton data. The code should support both AOD and ESD format of input data.
## Usage
This analysis task shoul alwaysd be used with [phos tender](https://github.com/alisw/AliPhysics/tree/master/PWGGA/PHOSTasksPHOS_PbPb/AddAODPHOSTender.C). This is important as tender handles calibrations, geometry etc. Just add the following lines in your analysis code:
```c++
// In your run.C macro
gROOT->LoadMacro("$ALICE_PHYSICS/PWGGA/PHOSTasks/PHOS_PbPb/AddAODPHOSTender.C");
AliPHOSTenderTask * tenderPHOS = AddAODPHOSTender("PHOSTenderTask", "PHOStender", tenderOption, 1, isMC);
AliPHOSTenderSupply * PHOSSupply = tenderPHOS->GetPHOSTenderSupply();
PHOSSupply->ForceUsingBadMap("/path/to/badmap/BadMap_LHC16.root");
if(isMC)
{
// Use custom Zero Suppression threshold if needed
Double_t zs_threshold = 0.020;
PHOSSupply->ApplyZeroSuppression(zs_threshold);
}
// If you don't strong cuts on clusters, leave
// this list of bad cells empty.
std::vector<Int_t> cells;
TString files = AddAnalysisTaskPP(AliVEvent::kINT7, // Physics selection
"Changed ZS threshold to 20 MeV", // Comments, tags to distinguish output *.root files
"SelectionPrefix", // Prefix all your output if you want to use add multiple AliAnalysisTaskPPs
"", // Path to Bad Map, don't use it if you have set one in Tender
cells, // List of bad cells
isMC);
// Add files to the grid plugin
//
alienHandler->SetOutputFiles(files);
```
## Class hierarchy
```c++
AliAnalysisTaskPP13 // Main analysis
└─── MixingSample
└─── PhotonSelection
└─── PhysPhotonSelection // Fills all histograms needed to reconstruct $\pi^{0}$s
│ DetectorHistogram
│
└─── PhotonTimecutSelection // Study of timing cut efficiency and purity
└─── QualityPhotonSelection // QA plots for PHOS clusters
└─── TagAndProbeSelection
└─── PhysPhotonSelectionMC // Applies nonlinearity to PHOS clusters in MC
└─── MesonSelectionMC // Neutral meson efficiency study
│ ParticlesHistogram
│
└─── PythiaInfoSelection // Collects cross section and ntrials data. Needed for jet-jet MC only.
```
| {
"content_hash": "582dc5f45e7d4f78454f23d32ddabccf",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 269,
"avg_line_length": 43.26315789473684,
"alnum_prop": 0.6455798864557989,
"repo_name": "dlodato/AliPhysics",
"id": "528a9be64d4a3d41424b9ced9d57fc3c408a8565",
"size": "2546",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "PWGGA/PHOSTasks/PHOS_LHC16_pp/README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "56419045"
},
{
"name": "C++",
"bytes": "101716651"
},
{
"name": "CMake",
"bytes": "545777"
},
{
"name": "CSS",
"bytes": "5189"
},
{
"name": "Fortran",
"bytes": "134275"
},
{
"name": "HTML",
"bytes": "34737"
},
{
"name": "JavaScript",
"bytes": "3536"
},
{
"name": "Makefile",
"bytes": "25080"
},
{
"name": "Objective-C",
"bytes": "167533"
},
{
"name": "Perl",
"bytes": "17128"
},
{
"name": "Python",
"bytes": "720430"
},
{
"name": "Shell",
"bytes": "1018417"
},
{
"name": "TeX",
"bytes": "392122"
}
],
"symlink_target": ""
} |
package org.dswarm.persistence.model.schema;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import ch.lambdaj.Lambda;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.hamcrest.Matchers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.dswarm.init.DMPException;
import org.dswarm.persistence.model.BasicDMPJPAObject;
import org.dswarm.persistence.util.DMPPersistenceUtil;
/**
* A content schema is a schema that builds on top of a structure schema (meta data model), e.g., 'mabxml' is a structure schema
* for 'mab', which is a content schema.
*
* @author tgaengler
*/
@XmlRootElement
@Entity
// @Cacheable(true)
// @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Table(name = "CONTENT_SCHEMA")
public class ContentSchema extends BasicDMPJPAObject {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(AttributePath.class);
/**
* The value attribute path of the content schema.
*/
@ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH })
@JoinColumn(name = "RECORD_IDENTIFIER_ATTRIBUTE_PATH")
@XmlElement(name = "record_identifier_attribute_path")
private AttributePath recordIdentifierAttributePath;
/**
* All utilised attribute path of the key attribute paths.
*/
@JsonIgnore
@Access(AccessType.FIELD)
@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH })
@JoinTable(name = "CONTENT_SCHEMAS_KEY_ATTRIBUTE_PATHS",
joinColumns = { @JoinColumn(name = "CONTENT_SCHEMA_UUID", referencedColumnName = "UUID") },
inverseJoinColumns = { @JoinColumn(name = "ATTRIBUTE_PATH_UUID", referencedColumnName = "UUID") })
private Set<AttributePath> utilisedKeyAttributePaths;
/**
* all attribute paths of the key attribute paths as ordered list.
*/
@Transient
private LinkedList<AttributePath> orderedKeyAttributePaths;
/**
* A JSON object of the ordered list of key attribute paths.
*/
@Transient
private ArrayNode orderedKeyAttributePathsJSON;
/**
* A flag that indicates, whether the key attribute paths are initialised or not.
*/
@Transient
private boolean orderedKeyAttributePathsInitialized;
/**
* A string that holds the serialised JSON object of the key attribute paths (ordered list of attribute paths).
*/
@JsonIgnore
@Lob
@Access(AccessType.FIELD)
@Column(name = "KEY_ATTRIBUTE_PATHS", columnDefinition = "BLOB")
private byte[] keyAttributePaths;
/**
* The value attribute path of the content schema.
*/
@ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH })
@JoinColumn(name = "VALUE_ATTRIBUTE_PATH")
@XmlElement(name = "value_attribute_path")
private AttributePath valueAttributePath;
/**
* Creates a new content schema.
*/
protected ContentSchema() {
}
public ContentSchema(final String uuid) {
super(uuid);
}
/**
* Creates a new content schema with the given ordered list of key attribute paths and the value attribute path.
*
* @param recordIdentifierAttributePathArg the attribute path where the (legacy) record identifier is located
* @param keyAttributePathsArg an ordered list of key attribute paths
* @param valueAttributePath the attribute path where the values are located
*/
public ContentSchema(final String uuid, final AttributePath recordIdentifierAttributePathArg,
final LinkedList<AttributePath> keyAttributePathsArg, final AttributePath valueAttributePath) {
super(uuid);
setRecordIdentifierAttributePath(recordIdentifierAttributePathArg);
setKeyAttributePaths(keyAttributePathsArg);
setValueAttributePath(valueAttributePath);
}
/**
* Gets the record identifier attribute path of the content schema.
*
* @return the record attribute path of the content schema
*/
public AttributePath getRecordIdentifierAttributePath() {
return recordIdentifierAttributePath;
}
/**
* Sets the record identifier attribute path of the content schema.
*
* @param recordIdentifierAttributePathArg a new value attribute path
*/
public void setRecordIdentifierAttributePath(final AttributePath recordIdentifierAttributePathArg) {
recordIdentifierAttributePath = recordIdentifierAttributePathArg;
}
/**
* Gets the utilised attribute paths of the ordered list of key attribute paths.<br/>
* note: this is not the ordered list of key attribute paths, i.e., the key attribute paths; these are only the utilised
* attribute paths, i.e., an attribute path can occur multiple times in the ordered list of key attribute paths.
*
* @return the utilised attribute paths of the key attribute paths
*/
public Set<AttributePath> getUtilisedKeyAttributePaths() {
return utilisedKeyAttributePaths;
}
/**
* Gets the key attribute paths, i.e., the ordered list of attribute paths.
*
* @return the key attribute paths
*/
@XmlElement(name = "key_attribute_paths")
public LinkedList<AttributePath> getKeyAttributePaths() {
initKeyAttributePaths(false);
return orderedKeyAttributePaths;
}
/**
* Sets the key attribute paths (ordered list of attribute paths).
*
* @param keyAttributePathsArg new key attribute paths (ordered list of attribute paths)
*/
@XmlElement(name = "key_attribute_paths")
public void setKeyAttributePaths(final LinkedList<AttributePath> keyAttributePathsArg) {
if (keyAttributePathsArg == null && orderedKeyAttributePaths != null) {
if (utilisedKeyAttributePaths != null) {
utilisedKeyAttributePaths.clear();
}
orderedKeyAttributePaths.clear();
}
if (keyAttributePathsArg != null) {
if (orderedKeyAttributePaths == null) {
orderedKeyAttributePaths = Lists.newLinkedList();
}
if (!DMPPersistenceUtil.getAttributePathUtils().completeEquals(orderedKeyAttributePaths, keyAttributePathsArg)) {
orderedKeyAttributePaths.clear();
orderedKeyAttributePaths.addAll(keyAttributePathsArg);
checkUtilisedKeyAttributePaths();
utilisedKeyAttributePaths.clear();
for (final AttributePath keyAttributePath : orderedKeyAttributePaths) {
utilisedKeyAttributePaths.add(keyAttributePath);
}
}
}
refreshKeyAttributePathsString();
}
/**
* Adds a new key attribute path to the end of the ordered list of key attribute paths.<br>
* Created by: tgaengler
*
* @param keyAttributePathArg a new key attribute path
*/
public void addKeyAttributePath(final AttributePath keyAttributePathArg) {
if (keyAttributePathArg != null) {
checkUtilisedKeyAttributePaths();
checkOrderedKeyAttributePaths();
utilisedKeyAttributePaths.add(keyAttributePathArg);
orderedKeyAttributePaths.add(keyAttributePathArg);
refreshKeyAttributePathsString();
}
}
/**
* Gets the value attribute path of the content schema.
*
* @return the value attribute path of the content schema
*/
public AttributePath getValueAttributePath() {
return valueAttributePath;
}
/**
* Sets the value attribute path of the content schema.
*
* @param valueAttributePathArg a new value attribute path
*/
public void setValueAttributePath(final AttributePath valueAttributePathArg) {
valueAttributePath = valueAttributePathArg;
}
private void checkOrderedKeyAttributePaths() {
if (orderedKeyAttributePaths == null) {
initKeyAttributePaths(true);
if (orderedKeyAttributePaths == null) {
orderedKeyAttributePaths = Lists.newLinkedList();
}
}
}
private void checkUtilisedKeyAttributePaths() {
if (utilisedKeyAttributePaths == null) {
utilisedKeyAttributePaths = Sets.newCopyOnWriteArraySet();
}
}
/**
* Adds a new key attribute path to the given position in the ordered list of key attribute paths.<br>
* Created by: tgaengler
*
* @param keyAttributePathArg a new key attribute path
* @param keyAttributePathIndex the position of the key attribute path in the ordered list of key attribute paths
*/
protected void addKeyAttributePath(final AttributePath keyAttributePathArg, final int keyAttributePathIndex) {
if (keyAttributePathArg != null) {
checkUtilisedKeyAttributePaths();
checkOrderedKeyAttributePaths();
if (!keyAttributePathArg.equals(orderedKeyAttributePaths.get(keyAttributePathIndex))) {
orderedKeyAttributePaths.add(keyAttributePathIndex, keyAttributePathArg);
utilisedKeyAttributePaths.add(keyAttributePathArg);
refreshKeyAttributePathsString();
}
}
}
/**
* Removes an existing key attribute path from the key attribute paths.<br>
* Created by: tgaengler
*
* @param keyAttributePath an existing key attribute path that should be removed
* @param keyAttributePathIndex the position of the key attribute path in the ordered list of key attribute paths
*/
public void removeKeyAttributePath(final AttributePath keyAttributePath, final int keyAttributePathIndex) {
if (keyAttributePath != null
&& ((orderedKeyAttributePaths != null && orderedKeyAttributePaths.contains(keyAttributePath)) || (utilisedKeyAttributePaths != null
&& utilisedKeyAttributePaths
.contains(keyAttributePath)))) {
orderedKeyAttributePaths.remove(keyAttributePathIndex);
if (!orderedKeyAttributePaths.contains(keyAttributePath)) {
utilisedKeyAttributePaths.remove(keyAttributePath);
}
refreshKeyAttributePathsString();
}
}
/**
* Refreshes the string that holds the serialised JSON object of the key attribute paths (ordered list of attribute paths).
* This method should be called after every manipulation of the key attribute paths (to keep the states consistent).
*/
private void refreshKeyAttributePathsString() {
if (orderedKeyAttributePaths != null) {
orderedKeyAttributePathsJSON = new ArrayNode(DMPPersistenceUtil.getJSONFactory());
for (final AttributePath keyAttributePath : orderedKeyAttributePaths) {
orderedKeyAttributePathsJSON.add(keyAttributePath.getUuid());
}
}
if (null != orderedKeyAttributePathsJSON && orderedKeyAttributePathsJSON.size() > 0) {
keyAttributePaths = orderedKeyAttributePathsJSON.toString().getBytes(Charsets.UTF_8);
} else {
keyAttributePaths = null;
}
}
/**
* Initialises the key attribute paths, collection of attribute paths and JSON object from the string that holds the
* serialised JSON object of the key attribute paths.
*
* @param fromScratch flag that indicates, whether the key attribute paths should be initialised from scratch or not
*/
private void initKeyAttributePaths(final boolean fromScratch) {
if (orderedKeyAttributePathsJSON == null && !orderedKeyAttributePathsInitialized) {
if (keyAttributePaths == null) {
ContentSchema.LOG.debug("key attribute paths JSON is null for content schema '" + getUuid() + "'");
if (fromScratch) {
orderedKeyAttributePathsJSON = new ArrayNode(DMPPersistenceUtil.getJSONFactory());
orderedKeyAttributePaths = Lists.newLinkedList();
orderedKeyAttributePathsInitialized = true;
}
return;
}
try {
orderedKeyAttributePaths = Lists.newLinkedList();
// parse key attribute paths string
orderedKeyAttributePathsJSON = DMPPersistenceUtil.getJSONArray(StringUtils.toEncodedString(keyAttributePaths, Charsets.UTF_8));
if (null != orderedKeyAttributePathsJSON) {
for (final JsonNode keyAttributePathIdNode : orderedKeyAttributePathsJSON) {
final AttributePath keyAttributePath = getKeyAttributePath(keyAttributePathIdNode.asText());
if (null != keyAttributePath) {
orderedKeyAttributePaths.add(keyAttributePath);
}
}
}
} catch (final DMPException e) {
ContentSchema.LOG.debug("couldn't parse key attribute paths JSON for content schema '" + getUuid() + "'");
}
orderedKeyAttributePathsInitialized = true;
}
}
/**
* Gets the key attribute path for a given key attribute path identifier.
*
* @param uuid a key attribute path identifier
* @return the matched key attribute path or null
*/
public AttributePath getKeyAttributePath(final String uuid) {
if (null == uuid) {
return null;
}
if (null == utilisedKeyAttributePaths) {
return null;
}
if (StringUtils.toEncodedString(keyAttributePaths, Charsets.UTF_8).isEmpty()) {
return null;
}
final List<AttributePath> keyAttributePathsFiltered = Lambda.filter(
Lambda.having(Lambda.on(AttributePath.class).getUuid(), Matchers.equalTo(uuid)), utilisedKeyAttributePaths);
if (keyAttributePathsFiltered == null || keyAttributePathsFiltered.isEmpty()) {
return null;
}
return keyAttributePathsFiltered.get(0);
}
@Override
public boolean completeEquals(final Object obj) {
return ContentSchema.class.isInstance(obj)
&& super.completeEquals(obj)
&& DMPPersistenceUtil.getAttributePathUtils().completeEquals(((ContentSchema) obj).getRecordIdentifierAttributePath(),
getRecordIdentifierAttributePath())
&& DMPPersistenceUtil.getAttributePathUtils().completeEquals(((ContentSchema) obj).getUtilisedKeyAttributePaths(),
getUtilisedKeyAttributePaths())
&& DMPPersistenceUtil.getAttributePathUtils().completeEquals(((ContentSchema) obj).getKeyAttributePaths(), getKeyAttributePaths())
&& DMPPersistenceUtil.getAttributePathUtils().completeEquals(((ContentSchema) obj).getValueAttributePath(), getValueAttributePath());
}
}
| {
"content_hash": "eb0e39e5e93ff94f2ed7506c0fe6dcf9",
"timestamp": "",
"source": "github",
"line_count": 468,
"max_line_length": 137,
"avg_line_length": 30.574786324786324,
"alnum_prop": 0.758403801803061,
"repo_name": "knutwalker/dswarm",
"id": "8a9bdacd334634c8544a46e6c710bfbf290b5dd3",
"size": "14965",
"binary": false,
"copies": "3",
"ref": "refs/heads/builds/unstable",
"path": "persistence/src/main/java/org/dswarm/persistence/model/schema/ContentSchema.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2346625"
},
{
"name": "Python",
"bytes": "4042"
},
{
"name": "Shell",
"bytes": "624"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML>
<html lang="pl">
<head>
<title>Portfolio</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/main.css" />
<meta name="viewport" content="width=device-width" />
</head>
<body>
<nav class="nav">
<div class="container">
<ul>
<li><a href="#main">Home</a></li>
<li><a href="#about">About Me</a></li>
<li><a href="#skills">Skills</a></li>
<li><a href="#myProjects">My Projects</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div>
</nav>
<header id="main" class="header">
<div class="container_main">
<!-- <img src="images/logos/logo-transparent.png"></img>-->
<h2>YOSH1M1TZU</h2>
<p>Web Front-End and multi-platform C# developer</p>
</div>
</header>
<section id="about" class="section">
<div class="container">
<h2>About Me</h2>
<p>Hello! My name is Peter and I'm a young programming enthusiast.</p>
<p>I'm learning .NET C#, front-end and back-end in ASP.NET.</p>
<p>I care about every detail and I'm a well organized person. I have huge motivation to expand my knowledge about modern technologies.</p>
</div>
</section>
<section id="skills" class="section">
<div class="container">
<h2>Skills</h2>
<div class="skills">
<img src="images/logos/logo-html5.png"></img>
<img src="images/logos/logo-css3.png"></img>
<img src="images/logos/logo-js.png"></img>
<img src="images/logos/logo-sass.png"></img>
</div>
<div class="skills">
<img src="images/logos/logo-mysql.png"></img>
<img src="images/logos/logo-csharp.png"></img>
</div>
</div>
</section>
<section id="myProjects" class="section_projects">
<div class="container">
<h2>My Projects</h2>
<div class="project">
<img src="images/jade.png" style="float: right; width: 50%;"></img>
<h2>Jade</h2>
<p>Simple, yet beautifully designed messenger.</p>
<p>Technologies used:</p>
<ul>
<li>C# WPF for client side</li>
<li>C# ASP.NET for server side</li>
<li>Web Services for data exchange</li>
<li>MySQL Database for storage</li>
</ul>
</div>
<div class="project">
<img src="images/avatar.png" style="float: left; width: 50%;"></img>
<h2>Avatar</h2>
<p>Offline accounts manager encrypted with AES-256.</p>
<p>Technologies used:</p>
<ul>
<li>C# WPF for client side</li>
<li>AES-256 encryption</li>
</ul>
</div>
<div class="project">
<img src="images/projecto.png" style="float: right; width: 50%;"></img>
<h2>Projecto</h2>
<p>Modern and powerful project manager software.</p>
<p>Technologies used:</p>
<ul>
<li>C# WPF for client side</li>
<li>C# ASP.NET for server side</li>
<li>Web Services for data exchange</li>
<li>MySQL Database for storage</li>
</ul>
</div>
</div>
</section>
<section id="contact" class="section">
<div class="container">
<h2>Contact</h2>
<form class="form">
<input type="text" id="fname" name="fname" class="input_name" placeholder="Full Name" required>
<input type="email" id="femail" name="femail" class="input_email" placeholder="Email" required>
<p> </p>
<textarea type="text" id="fmessage" name="fmessage" class="input_message" placeholder="Message" required></textarea>
<input class="submit" type="submit" id="fsend" name="fsend" value="Submit">
</form>
</div>
</section>
<footer id="footer">
<div class="footer">
<p>© YOSH1M1TZU 2016. All rights reserved.</p>
</div>
</footer>
<script src="jquery.js"></script>
<script>
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
</script>
</body>
</html> | {
"content_hash": "9985b668297ab8ee29d617d553138125",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 154,
"avg_line_length": 36.00699300699301,
"alnum_prop": 0.47387842299475624,
"repo_name": "YOSH1M1TZU/yosh1m1tzu.github.io",
"id": "80f967744356d4f21115e308432c15932fd948d8",
"size": "5149",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5049"
},
{
"name": "HTML",
"bytes": "5149"
}
],
"symlink_target": ""
} |
var page = require('webpage').create();
var system = require('system');
var url = system.args[1];
var showConsole = system.args[2];
var maxMillisecondsPhantomCanBeOpen = 3 * 60 * 1000; // 3 minutes * 60 seconds in a minute * 1000 ms in a second
// phantom.outputEncoding = "utf8";
page.onError = function() { };
function closePage() {
page.close();
phantom.exit();
}
if (showConsole === "true") {
page.onConsoleMessage = function(msg) {
system.stdout.writeLine(msg +"<br>");
};
page.onCallback = closePage;
page.open(url);
} else {
page.onCallback = function (status) {
console.log(page.content);
closePage();
};
page.open(url, function(status){
if (status === 'fail') {
// What does russell want to do when it fails?
console.log(status);
closePage();
}
});
}
// Safeguard for page never calling the phantom callback, times out
setTimeout(closePage, maxMillisecondsPhantomCanBeOpen);
| {
"content_hash": "8dda35248a985bc8b0ff65b7871320a1",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 112,
"avg_line_length": 24.4390243902439,
"alnum_prop": 0.6227544910179641,
"repo_name": "rpalmite/webutilitykit",
"id": "3f92eea018dbfa9712a666116ed9f3bbcf57d2ac",
"size": "1195",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "build/phantomjs/render.js",
"mode": "33188",
"license": "bsd-2-clause",
"language": [],
"symlink_target": ""
} |
from flask import Flask, request, abort, render_template, flash, redirect, url_for, jsonify
from flask.ext.sqlalchemy import SQLAlchemy
from werkzeug import url_decode
import json
import threading
import time
import requests
import os
from datetime import datetime, timedelta
# Used to keep track of whether the main thread wants to quit
_terminate = False
class MethodRewriteMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
if '_method' in environ.get('QUERY_STRING', ''):
args = url_decode(environ['QUERY_STRING'])
method = args.get('_method')
if method:
method = method.encode('ascii', 'replace')
environ['REQUEST_METHOD'] = method.upper()
return self.app(environ, start_response)
app = Flask(__name__)
my_ip = requests.get('http://httpbin.org/ip').json()['origin']
print('Running on %s' % my_ip)
app.wsgi_app = MethodRewriteMiddleware(app.wsgi_app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///../db-dev.sqlite'
app.config['SECRET_KEY'] = 'supersecret'
app.config['SERVER_NAME'] = 'sasha.zza.no'
app.config['PREFERRED_URL_SCHEME'] = 'https'
db = SQLAlchemy(app)
def wants_json():
best = request.accept_mimetypes.best_match(['application/json', 'text/html'])
return best == 'application/json' and \
request.accept_mimetypes[best] > \
request.accept_mimetypes['text/html']
class Unit(db.Model):
id = db.Column(db.Integer, primary_key=True)
alias = db.Column(db.String(50), default='')
description = db.Column(db.Text())
ip = db.Column(db.String(46))
unit_type = db.Column(db.String(30))
state = db.Column(db.String(20), default='not-approved')
last_checkin = db.Column(db.DateTime())
certificate = db.Column(db.Text(), unique=True)
actuators = db.Column(db.Text())
sensors = db.Column(db.Text())
associated_to_id = db.Column(db.Integer, db.ForeignKey('unit.id'))
associated_to = db.relationship('Unit', remote_side=id, backref='associates')
def to_json(self):
return {
'ip': self.ip,
'id': self.id,
'unit_type': self.unit_type,
'certificate': self.certificate,
'sensors': json.loads(self.sensors),
'actuators': json.loads(self.actuators),
}
class Subscription(db.Model):
type = db.Column(db.String(30), primary_key=True)
subscribers = db.Column(db.Text())
class SensorReading(db.Model):
id = db.Column(db.Integer, primary_key=True)
unit_id = db.Column(db.Integer, db.ForeignKey('unit.id'))
interface = db.Column(db.Integer)
reading = db.Column(db.Float)
@app.route('/register-unit', methods=['POST'])
def register_unit():
posted_data = request.json or {}
csr = posted_data.get('csr')
unit_type = posted_data.get('unit_type')
sensors = posted_data.get('sensors', [])
actuators = posted_data.get('actuators', [])
description = posted_data.get('description', '')
subscribe_to = posted_data.get('subscribe_to', [])
print json.dumps(posted_data, indent=2)
if not (csr and unit_type):
abort(400)
unit = Unit.query.filter_by(certificate=csr).first()
if unit:
if unit.state == 'rejected':
return jsonify({
'status': 403,
'message': 'You have been rejected.'
}), 403
else:
# New unit registered
unit = Unit(
unit_type=unit_type,
certificate=csr,
sensors=json.dumps(sensors),
actuators=json.dumps(actuators),
description=description,
)
db.session.add(unit)
db.session.commit()
print 'Adding new unit, subscribing to %s' % subscribe_to
for unit_type_subscription in subscribe_to:
subscription = Subscription.query.get(unit_type_subscription)
if subscription:
subscription.subscribers = json.dumps(json.loads(subscription.subscribers) + [unit.id])
print 'Updated subscriptions, %s is now followed by %s' % (
unit_type_subscription, ', '.join(str(i) for i in json.loads(subscription.subscribers)))
else:
subscription = Subscription(type=unit_type_subscription, subscribers=json.dumps([unit.id]))
print 'Created new subscription, %s now follows %s' % (unit.id, unit_type_subscription)
db.session.add(subscription)
db.session.commit()
return jsonify({
'id': unit.id,
'checkin_url': url_for('unit_checkin', _external=True),
'certificate_url': url_for('certificate', unit_id=unit.id, _external=True),
'registry_url': url_for('registry', _external=True),
})
@app.route('/')
def main():
operational_units = Unit.query.filter(Unit.state!='not-approved').all()
unapproved_units = Unit.query.filter(Unit.state=='not-approved').all()
return render_template('main.html', operational_units=operational_units, unapproved_units=unapproved_units)
@app.route('/registry')
def registry():
units = Unit.query.all()
return jsonify({
'units': [unit.to_json() for unit in units],
})
@app.route('/units/<int:unit_id>', methods=['POST'])
def update_unit(unit_id):
unit = Unit.query.get_or_404(unit_id)
alias = request.form.get('alias', '')
description = request.form.get('description', '')
unit.alias = alias
unit.description = description
db.session.commit()
if wants_json():
return json.dumps({
'_meta': {
'status': 'OK',
}
})
else:
return redirect(url_for('main'))
@app.route('/checkin', methods=['POST'])
def unit_checkin():
changes = False
unit_ip = request.access_route[0]
data = request.json or {}
unit_id = data.get('unit_id')
readings = data.get('readings', {})
if not unit_id:
abort(400)
unit = Unit.query.get_or_404(unit_id)
if unit.state == 'not-approved' or unit.state == 'rejected':
abort(400)
if unit.ip != unit_ip or not unit.last_checkin or unit.state == 'gone':
changes = True
if not unit.last_checkin:
# First checkin for this unit, notify subscribers
subscription = Subscription.query.get(unit.unit_type)
if subscription:
listeners_that_still_exist = []
for listener_id in json.loads(subscription.subscribers):
listener = Unit.query.get(listener_id)
if listener:
# TODO: this code is going to act weird if there's several subscribers, should just choose the first one
unit.associated_to_id = listener_id
print 'Notifying %s about new %s unit %s' % (listener.alias or listener.id, unit.unit_type, unit.id)
notify_single_unit_of_registry_update(listener)
listeners_that_still_exist.append(listener_id)
subscription.subscribers = json.dumps(listeners_that_still_exist)
db.session.commit()
unit.ip = unit_ip
if unit.state == 'gone':
print 'Unit %d (%s) is back up!' % (unit.id, unit.alias)
unit.state = 'ok'
unit.last_checkin = datetime.utcnow()
db.session.commit()
if changes:
notify_units_of_registry_update()
return jsonify({
'status': 'OK!',
})
def notify_units_of_registry_update():
units = Unit.query.filter(Unit.state=='ok').all()
headers = {'content-type': 'application/json'}
for unit in units:
notify_single_unit_of_registry_update(unit)
def notify_single_unit_of_registry_update(unit):
try:
target = 'http://%s/registry-updated' % unit.ip
print('Notifying %s notified of registry update' % target)
requests.post(target, data=json.dumps({
'units': [u.to_json() for u in unit.associates],
}), timeout=1, headers={'content-type': 'application/json'})
except requests.exceptions.Timeout, requests.exceptions.ConnectionError:
print('Unit %s does not respond to registry update, skipping...' % unit.id)
@app.route('/units/<int:unit_id>', methods=['DELETE'])
def delete_unit(unit_id):
unit = Unit.query.get_or_404(unit_id)
db.session.delete(unit)
db.session.commit()
flash('Unit deleted!', 'info')
notify_units_of_registry_update()
if wants_json():
return jsonify({
'_meta': {
'status': 'OK!',
'message': 'Unit deleted',
}
})
else:
return redirect(url_for('main'))
@app.route('/approve-unit/<int:unit_id>', methods=['POST'])
def approve_unit(unit_id):
unit = Unit.query.get_or_404(unit_id)
unit.alias = request.form.get('alias', '')
unit.description = request.form.get('description', '')
unit.state = 'approved'
db.session.commit()
flash('Accepted unit %s' % unit.id, 'info')
return redirect(url_for('main'))
@app.route('/connect-units', methods=['POST'])
def connect_units():
unit_id = request.form.get('unit_id')
if not unit_id:
abort(400)
unit = Unit.query.get_or_404(unit_id)
other_unit_id = request.form.get('other_unit', '')
if other_unit_id:
other_unit = Unit.query.get_or_404(other_unit_id)
unit.associated_to = other_unit
flash('%s succcessfully associated to %s' % (unit.alias, other_unit.alias), 'info')
else:
unit.associated_to = None
flash('Removed associatation from %s' % unit.alias, 'info')
notify_units_of_registry_update()
db.session.commit()
return redirect(url_for('main'))
@app.route('/reject-unit/<int:unit_id>', methods=['POST'])
def reject_unit(unit_id):
unit = Unit.query.get_or_404(unit_id)
unit.state = 'rejected'
db.session.commit()
flash('Unit %s rejected' % unit.id, 'info')
return redirect(url_for('main'))
@app.route('/certificates/<int:unit_id>.crt')
def certificate(unit_id):
unit = Unit.query.get_or_404(unit_id)
if unit.state == 'rejected':
abort(410)
return os.urandom(30).encode('hex')
def watch_for_dead_units():
time.sleep(30)
while not _terminate:
print '[housekeeping] Scanning for dead units...'
changes = False
units = Unit.query.filter((Unit.state=='ok') | (Unit.state=='approved')).all()
for unit in units:
if unit.last_checkin:
now = datetime.utcnow()
print "[housekeeping]", now - unit.last_checkin
if now - unit.last_checkin > timedelta(minutes=1):
unit.state = 'gone'
print '[housekeeping] Unit %d (%s) considered dead, last heard from %s' % (unit.id, unit.alias, unit.last_checkin)
changes = True
if changes:
db.session.commit()
time.sleep(30)
def main():
''' CLI entry-point for running master. '''
db.create_all()
housekeeping_thread = threading.Thread(target=watch_for_dead_units)
housekeeping_thread.daemon = True
housekeeping_thread.start()
try:
app.run(debug=True, host='0.0.0.0', port=80)
except KeyboardInterrupt:
_terminate = True
raise
| {
"content_hash": "4443e8717c0688a06372da963a470b74",
"timestamp": "",
"source": "github",
"line_count": 327,
"max_line_length": 134,
"avg_line_length": 34.67278287461774,
"alnum_prop": 0.6090139354383489,
"repo_name": "thusoy/sasha",
"id": "5b7e86ff186b5681e8e5d984cff6e163ae355876",
"size": "11338",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sasha/master.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "44"
},
{
"name": "Makefile",
"bytes": "502"
},
{
"name": "Python",
"bytes": "28842"
},
{
"name": "Shell",
"bytes": "1369"
},
{
"name": "TeX",
"bytes": "24700"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<!-- Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.yahoo.vespa</groupId>
<artifactId>parent</artifactId>
<version>8-SNAPSHOT</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>
<artifactId>config-lib</artifactId>
<packaging>container-plugin</packaging>
<version>8-SNAPSHOT</version>
<name>${project.artifactId}</name>
<dependencies>
<dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>annotations</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>configgen</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.yahoo.vespa</groupId>
<artifactId>config-class-plugin</artifactId>
<version>${project.version}</version>
<executions>
<execution>
<id>configgen-test-defs</id>
<phase>generate-test-sources</phase>
<goals>
<goal>config-gen</goal>
</goals>
<configuration>
<defFilesDirectories>src/test/resources/configdefinitions</defFilesDirectories>
<outputDirectory>target/generated-test-sources/vespa-configgen-plugin</outputDirectory>
<testConfig>true</testConfig>
<requireNamespace>false</requireNamespace>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.yahoo.vespa</groupId>
<artifactId>bundle-plugin</artifactId>
<extensions>true</extensions>
</plugin>
<plugin>
<groupId>com.yahoo.vespa</groupId>
<artifactId>abi-check-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "4c349f1a2f25ff91c70a812d25e43dba",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 110,
"avg_line_length": 34.74683544303797,
"alnum_prop": 0.6225865209471767,
"repo_name": "vespa-engine/vespa",
"id": "66603deeb388dd0d8348ddfd5f9b8eec29bdb95a",
"size": "2745",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config-lib/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "8130"
},
{
"name": "C",
"bytes": "60315"
},
{
"name": "C++",
"bytes": "29580035"
},
{
"name": "CMake",
"bytes": "593981"
},
{
"name": "Emacs Lisp",
"bytes": "91"
},
{
"name": "GAP",
"bytes": "3312"
},
{
"name": "Go",
"bytes": "560664"
},
{
"name": "HTML",
"bytes": "54520"
},
{
"name": "Java",
"bytes": "40814190"
},
{
"name": "JavaScript",
"bytes": "73436"
},
{
"name": "LLVM",
"bytes": "6152"
},
{
"name": "Lex",
"bytes": "11499"
},
{
"name": "Makefile",
"bytes": "5553"
},
{
"name": "Objective-C",
"bytes": "12369"
},
{
"name": "Perl",
"bytes": "23134"
},
{
"name": "Python",
"bytes": "52392"
},
{
"name": "Roff",
"bytes": "17506"
},
{
"name": "Ruby",
"bytes": "10690"
},
{
"name": "Shell",
"bytes": "268737"
},
{
"name": "Yacc",
"bytes": "14735"
}
],
"symlink_target": ""
} |
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
require_once 'NoticiaTaula.php';
class ComentarisTaula extends Zend_Db_Table
{
protected $_name = "comentaris";
protected $_primary = "id_comentari";
public function getComentarisNoticia($idNoticia){
$comentarisOk = array();
$_User = new Users();
$select = $this->select();
$select->where("id_noticia = ?", $idNoticia);
$select->where("id_pare is null");
$select->order("data DESC");
$comentaris = $this->fetchAll($select);
$x=0;
foreach($comentaris as $comentari){
$_VotsNeg = new VotsComentarisNeg();
$_VotsPos = new VotsComentarisPos();
$user = $_User->getUsuari($comentari->id_user);
if(count($user)==1){
foreach($user as $usuarifinal){
$comentarisOk[$x] = new Comentari($comentari->id_comentari, $comentari->id_noticia, $usuarifinal, $comentari->data, $comentari->text);
}
}
$VotsPositius = $_VotsPos->getVotsComentari($comentari->id_comentari);
$comentarisOk[$x]->addVotsPos($VotsPositius);
$VotsNegatius = $_VotsNeg->getVotsComentari($comentari->id_comentari);
$comentarisOk[$x]->addVotsNeg($VotsNegatius);
//Comentaris Fills
$Fills = $this->getFills($comentari->id_comentari);
$comentarisOk[$x]->addFills($Fills);
$x++;
}
return $comentarisOk;
}
public function getFills($id){
$comentarisOk = array();
$_User = new Users();
$select = $this->select();
$select->where("id_pare = ?", $id);
$select->order("data ASC");
$comentaris = $this->fetchAll($select);
$x=0;
foreach($comentaris as $comentari){
$_VotsNeg = new VotsComentarisNeg();
$_VotsPos = new VotsComentarisPos();
$user = $_User->getUsuari($comentari->id_user);
if(count($user)==1){
foreach($user as $usuarifinal){
$comentarisOk[$x] = new Comentari($comentari->id_comentari, $comentari->id_noticia, $usuarifinal, $comentari->data, $comentari->text);
}
}
$VotsPositius = $_VotsPos->getVotsComentari($comentari->id_comentari);
$comentarisOk[$x]->addVotsPos($VotsPositius);
$VotsNegatius = $_VotsNeg->getVotsComentari($comentari->id_comentari);
$comentarisOk[$x]->addVotsNeg($VotsNegatius);
//Comentaris Fills
$Fills = $this->getFills2($comentari->id_comentari);
$comentarisOk[$x]->addFills($Fills);
$x++;
}
return $comentarisOk;
}
public function getFills2($id){
$comentarisOk = array();
$_User = new Users();
$select = $this->select();
$select->where("id_pare = ?", $id);
$select->order("data ASC");
$comentaris = $this->fetchAll($select);
$x=0;
foreach($comentaris as $comentari){
$_VotsNeg = new VotsComentarisNeg();
$_VotsPos = new VotsComentarisPos();
$user = $_User->getUsuari($comentari->id_user);
if(count($user)==1){
foreach($user as $usuarifinal){
$comentarisOk[$x] = new Comentari($comentari->id_comentari, $comentari->id_noticia, $usuarifinal, $comentari->data, $comentari->text);
}
}
$VotsPositius = $_VotsPos->getVotsComentari($comentari->id_comentari);
$comentarisOk[$x]->addVotsPos($VotsPositius);
$VotsNegatius = $_VotsNeg->getVotsComentari($comentari->id_comentari);
$comentarisOk[$x]->addVotsNeg($VotsNegatius);
//Comentaris Fills
$Fills = $this->getFills3($comentari->id_comentari);
$comentarisOk[$x]->addFills($Fills);
$x++;
}
return $comentarisOk;
}
public function getFills3($id){
$comentarisOk = array();
$_User = new Users();
$select = $this->select();
$select->where("id_pare = ?", $id);
$select->order("data ASC");
$comentaris = $this->fetchAll($select);
$x=0;
foreach($comentaris as $comentari){
$_VotsNeg = new VotsComentarisNeg();
$_VotsPos = new VotsComentarisPos();
$user = $_User->getUsuari($comentari->id_user);
if(count($user)==1){
foreach($user as $usuarifinal){
$comentarisOk[$x] = new Comentari($comentari->id_comentari, $comentari->id_noticia, $usuarifinal, $comentari->data, $comentari->text);
}
}
$VotsPositius = $_VotsPos->getVotsComentari($comentari->id_comentari);
$comentarisOk[$x]->addVotsPos($VotsPositius);
$VotsNegatius = $_VotsNeg->getVotsComentari($comentari->id_comentari);
$comentarisOk[$x]->addVotsNeg($VotsNegatius);
$x++;
}
return $comentarisOk;
}
public function getComentariIdUsuari($id){
$select = $this->select();
$select->where("id_comentari = ?", $id);
$comentari = $this->fetchAll($select);
foreach($comentari as $coment){
return $coment->id_user;
}
}
public function getComentari($id){
$comentariOk = array();
$_User = new Users();
$select = $this->select();
$select->where("id_comentari = ?", $id);
$comentari = $this->fetchAll($select);
$x=0;
foreach($comentari as $coment){
$_VotsNeg = new VotsComentarisNeg();
$_VotsPos = new VotsComentarisPos();
$user = $_User->getUsuari($coment->id_user);
if(count($user)==1){
foreach($user as $usuarifinal){
$comentariOk[] = new Comentari($coment->id_comentari,$coment->id_noticia,$user , $coment->data, $coment->text);
}
}
$VotsPositius = $_VotsPos->getVotsComentari($coment->id_comentari);
$comentariOk[$x]->addVotsPos($VotsPositius);
$VotsNegatius = $_VotsNeg->getVotsComentari($coment->id_comentari);
$comentariOk[$x]->addVotsNeg($VotsNegatius);
$x++;
}
return $comentariOk;
}
public function afegirComentari($idNoticia, $Usuari,$dataHora, $text){
$comentari = $this->createRow();
$comentari->id_noticia = $idNoticia;
$comentari->id_user = $Usuari->id_user;
$comentari->data = $dataHora;
$comentari->text = $text;
return $comentari->save();
}
public function afegirComentariFill($idNoticia, $Usuari,$dataHora, $text,$id_pare){
$comentari = $this->createRow();
$comentari->id_noticia = $idNoticia;
$comentari->id_user = $Usuari->id_user;
$comentari->data = $dataHora;
$comentari->text = $text;
$comentari->id_pare = $id_pare;
return $comentari->save();
}
public function setPunt($id){
$_VotsPos = new VotsComentarisPos();
$_VotsNeg = new VotsComentarisNeg();
$VotsPositius = $_VotsPos->getVotsComentari($id);
$VotsNegatius = $_VotsNeg->getVotsComentari($id);
$comentari = $this->find($id)->current();
$comentari->punts = count($VotsPositius)-count($VotsNegatius);
$comentari->save();
}
public function getComentarisNoticiaPunts($idNoticia){
$comentarisOk = array();
$_User = new Users();
$select = $this->select();
$select->where("id_noticia = ?", $idNoticia);
$select->where("id_pare is null");
$select->order("punts DESC");
$comentaris = $this->fetchAll($select);
$x=0;
foreach($comentaris as $comentari){
$_VotsNeg = new VotsComentarisNeg();
$_VotsPos = new VotsComentarisPos();
$user = $_User->getUsuari($comentari->id_user);
if(count($user)==1){
foreach($user as $usuarifinal){
$comentarisOk[$x] = new Comentari($comentari->id_comentari, $comentari->id_noticia, $usuarifinal, $comentari->data, $comentari->text);
}
}
$VotsPositius = $_VotsPos->getVotsComentari($comentari->id_comentari);
$comentarisOk[$x]->addVotsPos($VotsPositius);
$VotsNegatius = $_VotsNeg->getVotsComentari($comentari->id_comentari);
$comentarisOk[$x]->addVotsNeg($VotsNegatius);
//Comentaris Fills
$Fills = $this->getFills($comentari->id_comentari);
$comentarisOk[$x]->addFills($Fills);
$x++;
}
return $comentarisOk;
}
public function getComentarisNoticiaAntic($idNoticia){
$comentarisOk = array();
$_User = new Users();
$select = $this->select();
$select->where("id_noticia = ?", $idNoticia);
$select->where("id_pare is null");
$select->order("data ASC");
$comentaris = $this->fetchAll($select);
$x=0;
foreach($comentaris as $comentari){
$_VotsNeg = new VotsComentarisNeg();
$_VotsPos = new VotsComentarisPos();
$user = $_User->getUsuari($comentari->id_user);
if(count($user)==1){
foreach($user as $usuarifinal){
$comentarisOk[$x] = new Comentari($comentari->id_comentari, $comentari->id_noticia, $usuarifinal, $comentari->data, $comentari->text);
}
}
$VotsPositius = $_VotsPos->getVotsComentari($comentari->id_comentari);
$comentarisOk[$x]->addVotsPos($VotsPositius);
$VotsNegatius = $_VotsNeg->getVotsComentari($comentari->id_comentari);
$comentarisOk[$x]->addVotsNeg($VotsNegatius);
//Comentaris Fills
$Fills = $this->getFills($comentari->id_comentari);
$comentarisOk[$x]->addFills($Fills);
$x++;
}
return $comentarisOk;
}
//AGAFAR TOTS ELS COMENTARIS, PANELL DADMIN!
public function getAllComentaris(){
$comentariOk = array();
$_User = new Users();
$_Noticia = new NoticiaTaula();
$select = $this->select();
$select->order("data DESC");
$comentari = $this->fetchAll($select);
$count=0;
foreach($comentari as $coment){
$user = $_User->getUsuariTot($coment->id_user);
$noticia = $_Noticia->getTitol($coment->id_noticia);
//Zend_Debug::dump($noticia);
if($noticia != null && $user!=null){
$comentariOk[$count] = new Comentari($coment->id_comentari, $noticia, $user , $coment->data, $coment->text);
$count++;
//Zend_Debug::dump($noticia);
}
//Zend_Debug::dump($noticia);
}
return $comentariOk;
}
public function getComentariId($idComentari){
$comentariOk = array();
$_User = new Users();
$_Noticia = new NoticiaTaula();
$select = $this->select();
$select->where("id_comentari = ?", $idComentari);
$comentari = $this->fetchAll($select);
$count=0;
foreach($comentari as $coment){
$user = $_User->getUsuariTot($coment->id_user);
$noticia = $_Noticia->getTitol($coment->id_noticia);
//Zend_Debug::dump($noticia);
if($noticia != null && $user!=null){
$comentariOk[$count] = new Comentari($coment->id_comentari, $noticia, $user , $coment->data, $coment->text);
$count++;
//Zend_Debug::dump($noticia);
}
//Zend_Debug::dump($noticia);
}
return $comentariOk;
}
public function removeComentari($id){
$id_comentari = (int)$id;
$comentari = $this->getComentariId($id_comentari);
$borrar = $this->find($id_comentari)->current();
$borrar->delete();
}
public function getComentarisUser($id){
$comentariOk = array();
$_User = new Users();
$_Noticia = new NoticiaTaula();
$select = $this->select();
$select->where("id_user = ?", $id);
$select->order("data DESC");
$comentari = $this->fetchAll($select);
$count=0;
foreach($comentari as $coment){
$user = $_User->getUsuariTot($coment->id_user);
$noticia = $_Noticia->getTitol($coment->id_noticia);
//Zend_Debug::dump($noticia);
if($noticia != null && $user!=null){
$comentariOk[$count] = new Comentari($coment->id_comentari, $noticia, $user , $coment->data, $coment->text);
$count++;
//Zend_Debug::dump($noticia);
}
//Zend_Debug::dump($noticia);
}
return $comentariOk;
}
public function getComentarisText($id){
$comentariOk = array();
$_User = new Users();
$_Noticia = new NoticiaTaula();
$select = $this->select();
$select->where("MATCH(text) AGAINST(?)", $id);
$select->order("data DESC");
$comentari = $this->fetchAll($select);
$count=0;
foreach($comentari as $coment){
$user = $_User->getUsuariTot($coment->id_user);
$noticia = $_Noticia->getTitol($coment->id_noticia);
//Zend_Debug::dump($noticia);
if($noticia != null && $user!=null){
$comentariOk[$count] = new Comentari($coment->id_comentari, $noticia, $user , $coment->data, $coment->text);
$count++;
//Zend_Debug::dump($noticia);
}
//Zend_Debug::dump($noticia);
}
return $comentariOk;
}
public function getComentarisIdNoticia($id){
$comentariOk = array();
$_User = new Users();
$_Noticia = new NoticiaTaula();
$select = $this->select();
$select->where("id_noticia = ?", $id);
$select->order("data DESC");
$comentari = $this->fetchAll($select);
$count=0;
foreach($comentari as $coment){
$user = $_User->getUsuariTot($coment->id_user);
$noticia = $_Noticia->getTitol($coment->id_noticia);
//Zend_Debug::dump($noticia);
if($noticia != null && $user!=null){
$comentariOk[$count] = new Comentari($coment->id_comentari, $noticia, $user , $coment->data, $coment->text);
$count++;
//Zend_Debug::dump($noticia);
}
//Zend_Debug::dump($noticia);
}
return $comentariOk;
}
}
?> | {
"content_hash": "6a1d227a78330db8b6c3d1e9470e6a59",
"timestamp": "",
"source": "github",
"line_count": 386,
"max_line_length": 158,
"avg_line_length": 42.012953367875646,
"alnum_prop": 0.49078127890485296,
"repo_name": "alexperegrina/newsup",
"id": "94177b3b07f2b25a433c1ffc4c0db4f65b5e555c",
"size": "16217",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/models/BD/ComentarisTaula.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "129828"
},
{
"name": "JavaScript",
"bytes": "80855"
},
{
"name": "PHP",
"bytes": "361705"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.discrete.discrete_model.GeneralizedPoissonResults.summary2 — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/stylesheets/deprecation.css">
<link rel="stylesheet" href="../_static/material.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script src="../_static/language_data.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.discrete.discrete_model.GeneralizedPoissonResults.t_test" href="statsmodels.discrete.discrete_model.GeneralizedPoissonResults.t_test.html" />
<link rel="prev" title="statsmodels.discrete.discrete_model.GeneralizedPoissonResults.summary" href="statsmodels.discrete.discrete_model.GeneralizedPoissonResults.summary.html" />
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.discrete.discrete_model.GeneralizedPoissonResults.summary2" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels v0.12.1</span>
<span class="md-header-nav__topic"> statsmodels.discrete.discrete_model.GeneralizedPoissonResults.summary2 </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="GET" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../_static/versions.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../discretemod.html" class="md-tabs__link">Regression with Discrete Dependent Variable</a></li>
<li class="md-tabs__item"><a href="statsmodels.discrete.discrete_model.GeneralizedPoissonResults.html" class="md-tabs__link">statsmodels.discrete.discrete_model.GeneralizedPoissonResults</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels v0.12.1</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../regression.html" class="md-nav__link">Linear Regression</a>
</li>
<li class="md-nav__item">
<a href="../glm.html" class="md-nav__link">Generalized Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../gee.html" class="md-nav__link">Generalized Estimating Equations</a>
</li>
<li class="md-nav__item">
<a href="../gam.html" class="md-nav__link">Generalized Additive Models (GAM)</a>
</li>
<li class="md-nav__item">
<a href="../rlm.html" class="md-nav__link">Robust Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../mixed_linear.html" class="md-nav__link">Linear Mixed Effects Models</a>
</li>
<li class="md-nav__item">
<a href="../discretemod.html" class="md-nav__link">Regression with Discrete Dependent Variable</a>
</li>
<li class="md-nav__item">
<a href="../mixed_glm.html" class="md-nav__link">Generalized Linear Mixed Effects Models</a>
</li>
<li class="md-nav__item">
<a href="../anova.html" class="md-nav__link">ANOVA</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.discrete.discrete_model.GeneralizedPoissonResults.summary2.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<h1 id="generated-statsmodels-discrete-discrete-model-generalizedpoissonresults-summary2--page-root">statsmodels.discrete.discrete_model.GeneralizedPoissonResults.summary2<a class="headerlink" href="#generated-statsmodels-discrete-discrete-model-generalizedpoissonresults-summary2--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="py method">
<dt id="statsmodels.discrete.discrete_model.GeneralizedPoissonResults.summary2">
<code class="sig-prename descclassname">GeneralizedPoissonResults.</code><code class="sig-name descname">summary2</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">yname</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">xname</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">title</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">alpha</span><span class="o">=</span><span class="default_value">0.05</span></em>, <em class="sig-param"><span class="n">float_format</span><span class="o">=</span><span class="default_value">'%.4f'</span></em><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.summary2" title="Permalink to this definition">¶</a></dt>
<dd><p>Experimental function to summarize regression results.</p>
<dl class="field-list">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><dl>
<dt><strong>yname</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#str" title="(in Python v3.9)"><code class="docutils literal notranslate"><span class="pre">str</span></code></a></span></dt><dd><p>Name of the dependent variable (optional).</p>
</dd>
<dt><strong>xname</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#list" title="(in Python v3.9)"><code class="docutils literal notranslate"><span class="pre">list</span></code></a>[<a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#str" title="(in Python v3.9)"><code class="docutils literal notranslate"><span class="pre">str</span></code></a>], <code class="xref py py-obj docutils literal notranslate"><span class="pre">optional</span></code></span></dt><dd><p>List of strings of length equal to the number of parameters
Names of the independent variables (optional).</p>
</dd>
<dt><strong>title</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#str" title="(in Python v3.9)"><code class="docutils literal notranslate"><span class="pre">str</span></code></a>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">optional</span></code></span></dt><dd><p>Title for the top table. If not None, then this replaces the
default title.</p>
</dd>
<dt><strong>alpha</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/functions.html#float" title="(in Python v3.9)"><code class="docutils literal notranslate"><span class="pre">float</span></code></a></span></dt><dd><p>The significance level for the confidence intervals.</p>
</dd>
<dt><strong>float_format</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#str" title="(in Python v3.9)"><code class="docutils literal notranslate"><span class="pre">str</span></code></a></span></dt><dd><p>The print format for floats in parameters summary.</p>
</dd>
</dl>
</dd>
<dt class="field-even">Returns</dt>
<dd class="field-even"><dl class="simple">
<dt><code class="xref py py-obj docutils literal notranslate"><span class="pre">Summary</span></code></dt><dd><p>Instance that contains the summary tables and text, which can be
printed or converted to various output formats.</p>
</dd>
</dl>
</dd>
</dl>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<dl class="simple">
<dt><a class="reference internal" href="statsmodels.iolib.summary2.Summary.html#statsmodels.iolib.summary2.Summary" title="statsmodels.iolib.summary2.Summary"><code class="xref py py-obj docutils literal notranslate"><span class="pre">statsmodels.iolib.summary2.Summary</span></code></a></dt><dd><p>Class that holds summary results.</p>
</dd>
</dl>
</div>
</dd></dl>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.discrete.discrete_model.GeneralizedPoissonResults.summary.html" title="statsmodels.discrete.discrete_model.GeneralizedPoissonResults.summary"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.discrete.discrete_model.GeneralizedPoissonResults.summary </span>
</div>
</a>
<a href="statsmodels.discrete.discrete_model.GeneralizedPoissonResults.t_test.html" title="statsmodels.discrete.discrete_model.GeneralizedPoissonResults.t_test"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.discrete.discrete_model.GeneralizedPoissonResults.t_test </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Oct 29, 2020.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 3.2.1.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html> | {
"content_hash": "9088a1a762b93a1c466f0cd700ae4ce4",
"timestamp": "",
"source": "github",
"line_count": 523,
"max_line_length": 999,
"avg_line_length": 42.602294455066925,
"alnum_prop": 0.6200798886944033,
"repo_name": "statsmodels/statsmodels.github.io",
"id": "421eb6aad637475845287ed0eac288a7e97ac3a5",
"size": "22285",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "v0.12.1/generated/statsmodels.discrete.discrete_model.GeneralizedPoissonResults.summary2.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
layout: post
title: "MSBuild, Where does one get started"
subTitle:
heroImageUrl:
date: 2006-5-31
tags: ["MSBuild"]
keywords:
---
Long and short, if you don't know anything about MSBuild, it's time to hit the links below. Honestly it will do nothing but save you time and automate those dreaded processes. The links below will get you pointed in the right direction.
General Links
Blogs
Packages
Team Build | {
"content_hash": "317c765a82191f226a4f110dfd3ea5b8",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 248,
"avg_line_length": 23.72222222222222,
"alnum_prop": 0.7587822014051522,
"repo_name": "csell5/MyBlog",
"id": "57570b4ff3236b3d8420f72d17b5366ebbc48b16",
"size": "431",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/documents/2006/05/31/msbuild-where-does-one-get-started/index.html.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3233"
},
{
"name": "CoffeeScript",
"bytes": "14431"
},
{
"name": "HTML",
"bytes": "1685"
},
{
"name": "Shell",
"bytes": "2936"
}
],
"symlink_target": ""
} |
#ifndef GPG_SCORE_H_
#define GPG_SCORE_H_
#ifndef __cplusplus
#error Header file supports C++ only
#endif // __cplusplus
#include <memory>
#include <string>
#include "gpg/common.h"
namespace gpg {
class ScoreImpl;
/**
* Single data structure which allows you to access data about a player's
* score.
* @ingroup ValueType
*/
class GPG_EXPORT Score {
public:
Score();
/**
* Explicit constructor.
*/
explicit Score(std::shared_ptr<ScoreImpl const> impl);
/**
* Copy constructor for copying an existing score into a new one.
*/
Score(Score const ©_from);
/**
* Constructor for moving an existing score into a new one.
* r-value-reference version.
*/
Score(Score &&move_from);
/**
* Assignment operator for assigning this score's value from another score.
*/
Score &operator=(Score const ©_from);
/**
* Assignment operator for assigning this score's value from another score.
* r-value-reference version.
*/
Score &operator=(Score &&move_from);
~Score();
/**
* Returns true when the returned score is populated with data and is
* accompanied by a successful response status; false for an
* unpopulated user-created score or for a populated one accompanied by
* an unsuccessful response status.
* It must be true for the getter functions on this object to be usable.
*/
bool Valid() const;
/**
* Returns rank of the player's score compared to those of other players.
*/
uint64_t Rank() const;
/**
* Returns the player's score.
*/
uint64_t Value() const;
/**
* Returns the presentable string form of the score.
*/
/**
* Returns score-related metadata, including player ID and timespan.
*/
std::string const &Metadata() const;
private:
std::shared_ptr<ScoreImpl const> impl_;
};
} // namespace gpg
#endif // GPG_SCORE_H_
| {
"content_hash": "2d110f1e6ed92a98127d7c47201eab0b",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 77,
"avg_line_length": 21.28409090909091,
"alnum_prop": 0.6668446342765617,
"repo_name": "PopCap/GameIdea",
"id": "51c3f6ce6d2a9c43e72ebab1eb775fe069602e33",
"size": "2030",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Engine/Source/ThirdParty/GooglePlay/gpg-cpp-sdk.v1.1/gpg-cpp-sdk/android/include/gpg/score.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "ASP",
"bytes": "238055"
},
{
"name": "Assembly",
"bytes": "184134"
},
{
"name": "Batchfile",
"bytes": "116983"
},
{
"name": "C",
"bytes": "84264210"
},
{
"name": "C#",
"bytes": "9612596"
},
{
"name": "C++",
"bytes": "242290999"
},
{
"name": "CMake",
"bytes": "548754"
},
{
"name": "CSS",
"bytes": "134910"
},
{
"name": "GLSL",
"bytes": "96780"
},
{
"name": "HLSL",
"bytes": "124014"
},
{
"name": "HTML",
"bytes": "4097051"
},
{
"name": "Java",
"bytes": "757767"
},
{
"name": "JavaScript",
"bytes": "2742822"
},
{
"name": "Makefile",
"bytes": "1976144"
},
{
"name": "Objective-C",
"bytes": "75778979"
},
{
"name": "Objective-C++",
"bytes": "312592"
},
{
"name": "PAWN",
"bytes": "2029"
},
{
"name": "PHP",
"bytes": "10309"
},
{
"name": "PLSQL",
"bytes": "130426"
},
{
"name": "Pascal",
"bytes": "23662"
},
{
"name": "Perl",
"bytes": "218656"
},
{
"name": "Python",
"bytes": "21593012"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Shell",
"bytes": "2889614"
},
{
"name": "Tcl",
"bytes": "1452"
}
],
"symlink_target": ""
} |
var $ = require('cheerio');
module.exports = {
provides: "sm4",
getLink: function(sm4, whitelistRecord) {
if (!(sm4.video && sm4.video.embed && whitelistRecord.isAllowed && whitelistRecord.isAllowed('sm4.video'))) {
return;
}
var player = {
type: CONFIG.T.text_html,
rel:[CONFIG.R.player, CONFIG.R.sm4]
};
var $container = $('<div>');
try {
$container.html(sm4.video.embed);
} catch(ex) {}
var $iframe = $container.find('iframe');
if ($iframe.length == 1 && $iframe.attr('width') && $iframe.attr('height')) {
player.href = $iframe.attr('src');
if (whitelistRecord.isAllowed('sm4.video', 'ssl')) {
player.href = player.href.replace(/^http:\/\//i, '//');
}
if (whitelistRecord.isAllowed('sm4.video', 'responsive')) {
player['aspect-ratio'] = $iframe.attr('width') / $iframe.attr('height');
} else {
player.width = $iframe.attr('width');
player.height = $iframe.attr('height')
}
if (whitelistRecord.isAllowed('sm4.video', 'autoplay')) {
player.rel.push(CONFIG.R.autoplay);
}
if (whitelistRecord.isAllowed('sm4.video', 'html5')) {
player.rel.push(CONFIG.R.html5);
}
return player;
}
},
getMeta: function (sm4) {
return {
author: sm4.category
}
},
getData: function (meta) {
if (meta.sm4) {
return {
sm4: meta.sm4
}
}
},
tests: [{
skipMethods: ["getMeta"]
},
"http://thedailyshow.cc.com/guests/neil-degrasse-tyson/2abri1/neil-degrasse-tyson",
"http://tosh.cc.com/video-clips/gs28zs/kid-delivery",
"http://www.cc.com/video-clips/vyienh/comedy-central-presents-insane-clown-posse",
"http://thecolbertreport.cc.com/videos/y8jsuk/stephest-colbchella--013---daft-punk-d"
]
}; | {
"content_hash": "a17205d44ffa6b912ed827d90476ebe7",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 117,
"avg_line_length": 28.413333333333334,
"alnum_prop": 0.5035194744251525,
"repo_name": "loklak/loklak_webclient",
"id": "627cab2c0669ba6273f97777712fb156dc5009f0",
"size": "2131",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "iframely/plugins/links/sm4.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "395502"
},
{
"name": "HTML",
"bytes": "177601"
},
{
"name": "JavaScript",
"bytes": "1843716"
},
{
"name": "Shell",
"bytes": "497"
}
],
"symlink_target": ""
} |
The 'Note' class
----------------
.. autoclass:: music_essentials.note.Note
:member-order: bysource
:members:
:undoc-members:
:special-members:
:exclude-members: __dict__,__weakref__,__module__
| {
"content_hash": "5f1c74225609c95749ac1d418c1fb09a",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 53,
"avg_line_length": 26.75,
"alnum_prop": 0.5934579439252337,
"repo_name": "charlottepierce/music_essentials",
"id": "e1852c1c7f573a7a6a69f3caf7b8fe0469799bfe",
"size": "214",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/note.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "106634"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "4ab36131e4055b7ec531c59beba55218",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "2509dfe58c351d72327ac14831f4833a12683b7f",
"size": "184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fagales/Betulaceae/Alnus/Alnus firma/ Syn. Alnus yasha microcarpa/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
@interface NSArray (CocoaRouge)
- (NSArray *)map:(id (^)(id))block;
- (NSString *)join;
- (NSString *)join:(NSString *)separator;
- (BOOL)isEmpty;
- (BOOL)any:(BOOL (^)(id item))block;
- (NSArray *)select:(BOOL (^)(id item))block;
- (NSArray *)reject:(BOOL (^)(id item))block;
- (void)each:(void (^)(id item))block;
- (void)eachWithIndex:(void (^)(id item, int index))block;
@end
| {
"content_hash": "a54dc85a68a88f7710b6c6b9afd8dce1",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 58,
"avg_line_length": 29.384615384615383,
"alnum_prop": 0.6308900523560209,
"repo_name": "danieltiger/CocoaRouge",
"id": "b2c07432287c0c26fd94c161478ee96f50d4d8be",
"size": "528",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CocoaRouge/NSArray+CocoaRouge.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "15315"
},
{
"name": "Ruby",
"bytes": "568"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "fc0bd8b3874be00c0afbd9127787da55",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "e5b4dfad4807c2e1c46afbda0c2106d68b2ca865",
"size": "170",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Acanthaceae/Barleriacanthus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
.. _stm3210c_eval_board:
STM3210C-EVAL
#############
Overview
********
The STM3210C-EVAL evaluation board is a complete development platform for STMicroelectronic's
ARM Cortex-M3 core-based STM32F107VCT microcontroller.
The range of hardware features on the board help you to evaluate all peripherals
(USB-OTG FS, ethernet, motor control, CAN, microSD CardTM, smartcard, USART,
audio DAC, MEMS, EEPROM and more) and develop your own applications.
Extension headers make it easy to connect a daughterboard or wrapping board for your specific
application.
.. image:: img/stm3210c_eval_board.jpg
:width: 660px
:height: 792px
:align: center
:alt: STM3210C-EVAL
More information about the board can be found at the `STM3210C-EVAL website`_.
Hardware
********
STM3210C-EVAL provides the following hardware components:
- Three 5 V power supply options:
- Power jack
- USB connector
- daughterboard
- Boot from user Flash, system memory or SRAM.
- I2S audio DAC, stereo audio jack.
- 2 GByte (or more) microSD CardTM.
- Both type A and B smartcard support.
- I2C compatible serial interface 64 Kbit EEPROM, MEMS and I/O expander.
- RS-232 communication.
- IrDA transceiver.
- USB-OTG full speed, USB microAB connector.
- IEEE-802.3-2002 compliant ethernet connector.
- Two channels of CAN2.0A/B compliant connection.
- Inductor motor control connector.
- JTAG and trace debug support.
- 3.2" 240x320 TFT color LCD with touch screen.
- Joystick with 4-direction control and selector.
- Reset, Wakeup, Tamper and User button.
- 4 color LEDs.
- RTC with backup battery.
- MCU consumption measurement circuit.
- Extension connector for daughterboard or wrapping board.
More information about STM32F107VCT can be found here:
- `STM32F107VCT reference manual`_
Supported Features
==================
The Zephyr stm3210c_eval board configuration supports the following hardware features:
+-----------+------------+-------------------------------------+
| Interface | Controller | Driver/Component |
+===========+============+=====================================+
| NVIC | on-chip | nested vector interrupt controller |
+-----------+------------+-------------------------------------+
| UART | on-chip | serial port-polling; |
| | | serial port-interrupt |
+-----------+------------+-------------------------------------+
| PINMUX | on-chip | pinmux |
+-----------+------------+-------------------------------------+
| GPIO | on-chip | gpio |
+-----------+------------+-------------------------------------+
| CLOCK | on-chip | reset and clock control |
+-----------+------------+-------------------------------------+
| FLASH | on-chip | flash memory |
+-----------+------------+-------------------------------------+
| IWDG | on-chip | independent watchdog |
+-----------+------------+-------------------------------------+
Other hardware features are not yet supported in this Zephyr port.
The default configuration can be found in the defconfig file:
``boards/arm/stm3210c_eval/stm3210c_eval_defconfig``
Connections and IOs
===================
Each of the GPIO pins can be configured by software as output (push-pull or open-drain), as
input (with or without pull-up or pull-down), or as peripheral alternate function. Most of the
GPIO pins are shared with digital or analog alternate functions. All GPIOs are high current
capable except for analog inputs.
Board connectors:
-----------------
.. image:: img/stm3210c_eval_connectors.png
:width: 966px
:height: 1017px
:align: center
:alt: STM3210C_EVAL connectors
Default Zephyr Peripheral Mapping:
----------------------------------
- UART_2_TX : PD5
- UART_2_RX : PD6
- USER_PB : PB9
- LED2 : PD13
Programming and Debugging
*************************
Flashing
========
STM3210C-EVAL board includes an ST-LINK/V2-1 embedded debug tool interface.
At power-on, the board is in firmware-upgrade mode (also called DFU for
"Device Firmware Upgrade"), allowing the firmware to be updated through the USB.
This interface is supported by the openocd version included in Zephyr SDK.
Flashing an application to STM3210C-EVAL
----------------------------------------
The sample application `blinky` is being used in this tutorial:
.. code-block:: console
$<zephyr_root_path>/samples/basic/blinky
To build the Zephyr kernel and application, enter:
.. code-block:: console
$ cd <zephyr_root_path>
$ source zephyr-env.sh
$ cd $ZEPHYR_BASE/samples/basic/blinky
$ make BOARD=stm3210c_eval
Connect the STM3210C-EVAL to your host computer using the USB port.
Then, enter the following command:
.. code-block:: console
$ make BOARD=stm3210c_eval flash
Run a serial host program to connect with your STM3210C-EVAL board:
.. code-block:: console
$ minicom -D /dev/ttyACM0
You will see the LED blinking every second.
Debugging
=========
Access gdb with the following make command:
.. code-block:: console
$ make BOARD=stm3210c_eval debug
References
**********
.. target-notes::
.. _STM3210C-EVAL website:
http://www.st.com/en/evaluation-tools/stm3210c-eval.html
.. _STM32F107VCT reference manual:
http://www.st.com/resource/en/reference_manual/CD00171190.pdf
| {
"content_hash": "7989c20efa329998eb2ec397798f1526",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 94,
"avg_line_length": 31.14857142857143,
"alnum_prop": 0.606861126398826,
"repo_name": "sharronliu/zephyr",
"id": "d5b265aad075411d9c28dadc379ea10dee1e85d4",
"size": "5451",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "boards/arm/stm3210c_eval/doc/stm3210c_eval.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "316707"
},
{
"name": "C",
"bytes": "172046708"
},
{
"name": "C++",
"bytes": "2168044"
},
{
"name": "Lex",
"bytes": "11299"
},
{
"name": "Makefile",
"bytes": "184543"
},
{
"name": "Objective-C",
"bytes": "436925"
},
{
"name": "Perl",
"bytes": "269076"
},
{
"name": "Python",
"bytes": "202350"
},
{
"name": "Shell",
"bytes": "56172"
},
{
"name": "Verilog",
"bytes": "1449"
},
{
"name": "Yacc",
"bytes": "15396"
}
],
"symlink_target": ""
} |
Subsets and Splits