text
stringlengths 2
1.04M
| meta
dict |
---|---|
package griffon.plugins.rmi;
import griffon.annotations.core.Nonnull;
import griffon.annotations.core.Nullable;
import griffon.core.artifact.GriffonService;
import griffon.exceptions.GriffonException;
import griffon.plugins.rmi.exceptions.RmiException;
import griffon.util.CollectionUtils;
import org.codehaus.griffon.runtime.core.artifact.AbstractGriffonService;
import org.kordamp.jipsy.annotations.ServiceProviderFor;
import javax.inject.Inject;
import java.rmi.RemoteException;
import java.util.Map;
@ServiceProviderFor(GriffonService.class)
public class CalculatorService extends AbstractGriffonService {
@Inject
private RmiHandler rmiHandler;
public Double calculate(final double num1, final double num2) {
Map<String, Object> params = CollectionUtils.<String, Object>map()
.e("id", "client");
return rmiHandler.withRmi(params,
new RmiClientCallback<Double>() {
@Nullable
public Double handle(@Nonnull Map<String, Object> params, @Nonnull RmiClient client) throws RmiException {
return client.service(Calculator.NAME, new UnaryConsumer<Calculator, Double>() {
@Override
public Double consume(Calculator calculator) {
try {
return calculator.add(num1, num2);
} catch (RemoteException e) {
throw new GriffonException(e);
}
}
});
}
});
}
} | {
"content_hash": "b39fa8d09dbd1c9205e24abd3f00450c",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 122,
"avg_line_length": 38.642857142857146,
"alnum_prop": 0.6210720887245841,
"repo_name": "griffon-plugins/griffon-rmi-plugin",
"id": "56aada1a8ce84f9ddf227021a346249f78f36941",
"size": "2289",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "subprojects/griffon-rmi-core/src/test/groovy/griffon/plugins/rmi/CalculatorService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "40168"
},
{
"name": "Groovy",
"bytes": "7133"
},
{
"name": "Java",
"bytes": "46166"
}
],
"symlink_target": ""
} |
using AppBrix.Events.Contracts;
using AppBrix.Events.Schedule.Configuration;
using AppBrix.Events.Schedule.Contracts;
using AppBrix.Events.Schedule.Services;
using AppBrix.Lifecycle;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace AppBrix.Events.Schedule.Impl;
internal sealed class ScheduledEventHub : IScheduledEventHub, IApplicationLifecycle
{
#region IApplicationLifecycle implementation
public void Initialize(IInitializeContext context)
{
this.app = context.App;
this.config = this.app.ConfigService.GetScheduledEventsConfig();
this.timer = new PeriodicTimer(this.config.ExecutionCheck);
this.app.GetAsyncEventHub().Subscribe<PriorityQueueItem>(this.PriorityQueueItemRaised);
this.cts = new CancellationTokenSource();
_ = this.Run(this.cts.Token);
}
public void Uninitialize()
{
lock (this.queue)
{
this.timer.Dispose();
this.cts?.Cancel();
this.cts = null;
this.queue.Clear();
}
this.app.GetAsyncEventHub().Unsubscribe<PriorityQueueItem>(this.PriorityQueueItemRaised);
this.config = null;
this.app = null;
}
#endregion
#region IScheduledEventHub implementation
public void Schedule<T>(IScheduledEvent<T> args) where T : IEvent
{
if (args is null)
throw new ArgumentNullException(nameof(args));
var item = new PriorityQueueItem<T>(this.app, args);
item.MoveToNextOccurrence(this.app.GetTime());
lock (this.queue)
{
this.queue.Push(item);
}
}
public void Unschedule<T>(IScheduledEvent<T> args) where T : IEvent
{
if (args is null)
throw new ArgumentNullException(nameof(args));
lock (this.queue)
{
this.queue.Remove(args);
}
}
#endregion
#region Private methods
private void PriorityQueueItemRaised(PriorityQueueItem args) => args.Execute();
private async Task Run(CancellationToken token)
{
while (await this.timer.WaitForNextTickAsync(token).ConfigureAwait(false))
{
var now = this.app.GetTime();
lock (this.queue)
{
token.ThrowIfCancellationRequested(); // Unintialized
for (var args = this.queue.Peek(); args is not null && args.Occurrence <= now; args = this.queue.Peek())
{
this.app.GetAsyncEventHub().Raise(args);
args.MoveToNextOccurrence(now);
if (now < args.Occurrence)
this.queue.ReprioritizeHead();
else
this.queue.Pop();
}
}
}
}
#endregion
#region Private fields and constants
private readonly PriorityQueue queue = new PriorityQueue();
private CancellationTokenSource? cts;
#nullable disable
private IApp app;
private ScheduledEventsConfig config;
private PeriodicTimer timer;
#nullable restore
#endregion
}
| {
"content_hash": "75feca9c612701c583e6c84f4c4e15b4",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 120,
"avg_line_length": 30.388349514563107,
"alnum_prop": 0.6194888178913738,
"repo_name": "MarinAtanasov/AppBrix",
"id": "105660ae2c341c60dd2d097e004c38e16218234e",
"size": "3286",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Modules/AppBrix.Events.Schedule/Impl/ScheduledEventHub.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "623970"
},
{
"name": "PowerShell",
"bytes": "1396"
}
],
"symlink_target": ""
} |
from preggy import expect
from tests.base import FilterTestCase
class QualityFilterTestCase(FilterTestCase):
def test_quality_filter(self):
image = self.get_filtered('source.jpg', 'thumbor.filters.quality', 'quality(10)')
expected = self.get_fixture('quality-10%.jpg')
expect(self.context.request.quality).to_equal(10)
ssim = self.get_ssim(image, expected)
expect(ssim).to_be_greater_than(0.99)
| {
"content_hash": "49c01966416f39c5f6ee0082de578943",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 89,
"avg_line_length": 34.07692307692308,
"alnum_prop": 0.6952595936794582,
"repo_name": "Bladrak/thumbor",
"id": "565b4d9b39909895a90b94f4ff61b507b78190eb",
"size": "695",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "tests/filters/test_quality.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "52290"
},
{
"name": "Makefile",
"bytes": "1696"
},
{
"name": "Python",
"bytes": "490416"
}
],
"symlink_target": ""
} |
package org.drools.examples.conway;
import java.io.Serializable;
/**
* <code>CellState</code> enumerates all of the valid states that a Cell may
* be in.
*
* @see Cell
* @see CellGridImpl
*/
public class CellState implements Serializable {
public static final CellState LIVE = new CellState( "LIVE" );
public static final CellState DEAD = new CellState( "DEAD" );
private final String name;
private CellState(final String name) {
this.name = name;
}
public String toString() {
return "CellState: " + this.name;
}
}
| {
"content_hash": "fe10991893cc5ff34e5bb156f9713713",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 76,
"avg_line_length": 20.821428571428573,
"alnum_prop": 0.6518010291595198,
"repo_name": "murador/droolsjbpm-integration",
"id": "0d06df29a9bb4015d0abd4c0d2d02c84efae5564",
"size": "1203",
"binary": false,
"copies": "19",
"ref": "refs/heads/master",
"path": "droolsjbpm-integration-examples/src/main/java/org/drools/examples/conway/CellState.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2569"
},
{
"name": "CSS",
"bytes": "7748"
},
{
"name": "HTML",
"bytes": "2654"
},
{
"name": "Java",
"bytes": "5623797"
},
{
"name": "JavaScript",
"bytes": "32051"
},
{
"name": "Shell",
"bytes": "3525"
},
{
"name": "XSLT",
"bytes": "2865"
}
],
"symlink_target": ""
} |
window.jQuery = require('jquery');
require('./spinner');
require('./editor');
require('./uploads');
require('./big-header'); | {
"content_hash": "77e83adac625436c7805b06b67047d75",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 34,
"avg_line_length": 20.833333333333332,
"alnum_prop": 0.656,
"repo_name": "cpdt/codenetwork",
"id": "50fdc6c8c9cd989686f67e4f1d18784c8e02a9f1",
"size": "125",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "src/js/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "94368"
},
{
"name": "HTML",
"bytes": "35476"
},
{
"name": "JavaScript",
"bytes": "1875986"
}
],
"symlink_target": ""
} |
package com.digitalpebble.stormcrawler.parse.filter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.namespace.QName;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.xml.serialize.Method;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.digitalpebble.stormcrawler.Metadata;
import com.digitalpebble.stormcrawler.parse.ParseData;
import com.digitalpebble.stormcrawler.parse.ParseFilter;
import com.digitalpebble.stormcrawler.parse.ParseResult;
import com.fasterxml.jackson.databind.JsonNode;
/**
* Simple ParseFilter to illustrate and test the interface. Reads a XPATH
* pattern from the config file and stores the value as metadata
*/
public class XPathFilter extends ParseFilter {
private enum EvalFunction {
NONE, STRING, SERIALIZE;
public QName getReturnType() {
switch (this) {
case STRING:
return XPathConstants.STRING;
default:
return XPathConstants.NODESET;
}
}
}
private static final Logger LOG = LoggerFactory
.getLogger(XPathFilter.class);
private XPathFactory factory = XPathFactory.newInstance();
private XPath xpath = factory.newXPath();
protected final Map<String, List<LabelledExpression>> expressions = new HashMap<>();
class LabelledExpression {
String key;
private EvalFunction evalFunction;
private XPathExpression expression;
private LabelledExpression(String key, String expression)
throws XPathExpressionException {
this.key = key;
if (expression.startsWith("string(")) {
evalFunction = EvalFunction.STRING;
} else if (expression.startsWith("serialize(")) {
expression = expression.substring(10, expression.length() - 1);
evalFunction = EvalFunction.SERIALIZE;
} else {
evalFunction = EvalFunction.NONE;
}
this.expression = xpath.compile(expression);
}
List<String> evaluate(DocumentFragment doc)
throws XPathExpressionException, IOException {
Object evalResult = expression.evaluate(doc,
evalFunction.getReturnType());
List<String> values = new LinkedList<>();
switch (evalFunction) {
case STRING:
if (evalResult != null) {
String strippedValue = StringUtils
.strip((String) evalResult);
values.add(strippedValue);
}
break;
case SERIALIZE:
NodeList nodesToSerialize = (NodeList) evalResult;
StringWriter out = new StringWriter();
OutputFormat format = new OutputFormat(Method.XHTML, null,
false);
format.setOmitXMLDeclaration(true);
XMLSerializer serializer = new XMLSerializer(out, format);
for (int i = 0; i < nodesToSerialize.getLength(); i++) {
Node node = nodesToSerialize.item(i);
switch (node.getNodeType()) {
case Node.ELEMENT_NODE:
serializer.serialize((Element) node);
break;
case Node.DOCUMENT_NODE:
serializer.serialize((Document) node);
break;
case Node.DOCUMENT_FRAGMENT_NODE:
serializer.serialize((DocumentFragment) node);
break;
case Node.TEXT_NODE:
String text = node.getTextContent();
if (text.length() > 0) {
values.add(text);
}
// By pass the rest of the code since it is used to
// extract
// the value out of the serialized which isn't used in
// this case
continue;
}
String serializedValue = out.toString();
if (serializedValue.length() > 0) {
values.add(serializedValue);
}
out.getBuffer().setLength(0);
}
break;
default:
NodeList nodes = (NodeList) evalResult;
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
values.add(StringUtils.strip(node.getTextContent()));
}
}
return values;
}
}
@Override
public void filter(String URL, byte[] content, DocumentFragment doc,
ParseResult parse) {
ParseData parseData = parse.get(URL);
Metadata metadata = parseData.getMetadata();
// applies the XPATH expression in the order in which they are produced
java.util.Iterator<List<LabelledExpression>> iter = expressions
.values().iterator();
while (iter.hasNext()) {
List<LabelledExpression> leList = iter.next();
for (LabelledExpression le : leList) {
try {
List<String> values = le.evaluate(doc);
if (values != null && !values.isEmpty()) {
metadata.addValues(le.key, values);
break;
}
} catch (XPathExpressionException e) {
LOG.error("Error evaluating {}: {}", le.key, e);
} catch (IOException e) {
LOG.error("Error evaluating {}: {}", le.key, e);
}
}
}
}
@SuppressWarnings("rawtypes")
@Override
public void configure(Map stormConf, JsonNode filterParams) {
java.util.Iterator<Entry<String, JsonNode>> iter = filterParams
.fields();
while (iter.hasNext()) {
Entry<String, JsonNode> entry = iter.next();
String key = entry.getKey();
JsonNode node = entry.getValue();
if (node.isArray()) {
for (JsonNode expression : node) {
addExpression(key, expression);
}
} else {
addExpression(key, entry.getValue());
}
}
}
private void addExpression(String key, JsonNode expression) {
String xpathvalue = expression.asText();
try {
List<LabelledExpression> lexpressionList = expressions.get(key);
if (lexpressionList == null) {
lexpressionList = new ArrayList<>();
expressions.put(key, lexpressionList);
}
LabelledExpression lexpression = new LabelledExpression(key,
xpathvalue);
lexpressionList.add(lexpression);
} catch (XPathExpressionException e) {
throw new RuntimeException("Can't compile expression : "
+ xpathvalue, e);
}
}
@Override
public boolean needsDOM() {
return true;
}
}
| {
"content_hash": "465e2d50c3182c86ef2fcab37dc1c7c3",
"timestamp": "",
"source": "github",
"line_count": 217,
"max_line_length": 88,
"avg_line_length": 36.41013824884793,
"alnum_prop": 0.5556258701430199,
"repo_name": "foromer4/storm-crawler",
"id": "43054cb632b846e5550090076d4573d61f59681a",
"size": "8690",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "core/src/main/java/com/digitalpebble/stormcrawler/parse/filter/XPathFilter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FLUX",
"bytes": "1993"
},
{
"name": "HTML",
"bytes": "5343"
},
{
"name": "Java",
"bytes": "493112"
}
],
"symlink_target": ""
} |
package org.testng;
import org.testng.collections.Lists;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlInclude;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class IDEARemoteTestNG extends TestNG {
private final String myParam;
public IDEARemoteTestNG(String param) {
myParam = param;
}
private static void calculateAllSuites(List<XmlSuite> suites, List<XmlSuite> outSuites) {
for (XmlSuite s : suites) {
outSuites.add(s);
calculateAllSuites(s.getChildSuites(), outSuites);
}
}
@Override
public void run() {
try {
initializeSuitesAndJarFile();
List<XmlSuite> suites = Lists.newArrayList();
calculateAllSuites(m_suites, suites);
if(suites.size() > 0) {
for (XmlSuite suite : suites) {
final List<XmlTest> tests = suite.getTests();
for (XmlTest test : tests) {
try {
if (myParam != null) {
for (XmlClass aClass : test.getXmlClasses()) {
List<XmlInclude> includes = new ArrayList<XmlInclude>();
for (XmlInclude include : aClass.getIncludedMethods()) {
includes.add(new XmlInclude(include.getName(), Collections.singletonList(Integer.parseInt(myParam)), 0));
}
aClass.setIncludedMethods(includes);
}
}
}
catch (NumberFormatException e) {
System.err.println("Invocation number: expected integer but found: " + myParam);
}
}
}
attachListeners(new IDEATestNGRemoteListener());
super.run();
}
else {
System.out.println("##teamcity[enteredTheMatrix]");
System.err.println("Nothing found to run");
}
System.exit(0);
}
catch(Throwable cause) {
cause.printStackTrace(System.err);
System.exit(-1);
}
}
private void attachListeners(IDEATestNGRemoteListener listener) {
addListener((Object)new IDEATestNGSuiteListener(listener));
addListener((Object)new IDEATestNGTestListener(listener));
try {
Class<?> configClass = Class.forName("org.testng.IDEATestNGConfigurationListener");
Object configurationListener = configClass.getConstructor(new Class[] {IDEATestNGRemoteListener.class}).newInstance(listener);
addListener(configurationListener);
Class<?> invokeClass = Class.forName("org.testng.IDEATestNGInvokedMethodListener");
Object invokedMethodListener = invokeClass.getConstructor(new Class[]{IDEATestNGRemoteListener.class}).newInstance(listener);
addListener(invokedMethodListener);
//start with configuration started if invoke method listener was not added, otherwise with
configClass.getMethod("setIgnoreStarted").invoke(configurationListener);
}
catch (Throwable ignored) {}
}
}
| {
"content_hash": "b135f94748cfb1ad3c1ef098620c5f94",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 132,
"avg_line_length": 33.15555555555556,
"alnum_prop": 0.6558310991957105,
"repo_name": "msebire/intellij-community",
"id": "33306531c912b920e5872b13e50b6526371b53d6",
"size": "3584",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "plugins/testng_rt/src/org/testng/IDEARemoteTestNG.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>continuations: Not compatible</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / extra-dev</a></li>
<li class="active"><a href="">8.11.dev / continuations - 8.10.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
continuations
<small>
8.10.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-07-24 01:10:59 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-24 01:10:59 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.11.dev Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/continuations"
license: "Unknown"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Continuations"]
depends: [
"ocaml"
"coq" {>= "8.10" & < "8.11~"}
]
tags: [
"keyword: exceptions"
"keyword: monads"
"keyword: continuations"
"keyword: cps"
"category: Computer Science/Semantics and Compilation/Semantics"
"category: Miscellaneous/Extracted Programs/Combinatorics"
]
authors: [
"Jean-François Monin"
]
bug-reports: "https://github.com/coq-contribs/continuations/issues"
dev-repo: "git+https://github.com/coq-contribs/continuations.git"
synopsis: "A toolkit to reason with programs raising exceptions"
description: """
We show a way of developing correct functionnal programs
raising exceptions. This is made possible using a Continuation
Passing Style translation, see the contribution "exceptions" from
P. Casteran at Bordeaux. Things are made easier and more modular using
some general definitions."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/continuations/archive/v8.10.0.tar.gz"
checksum: "md5=b1c38624cece12679e24681edc342e5c"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-continuations.8.10.0 coq.8.11.dev</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.11.dev).
The following dependencies couldn't be met:
- coq-continuations -> coq < 8.11~ -> ocaml < 4.05.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-continuations.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "39407c6fa62bd3d3a9a6742c2860666c",
"timestamp": "",
"source": "github",
"line_count": 178,
"max_line_length": 157,
"avg_line_length": 41.19101123595506,
"alnum_prop": 0.5596017457719585,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "950def32756b34623bcd7f86e552c68bed6c640c",
"size": "7335",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.05.0-2.0.6/extra-dev/8.11.dev/continuations/8.10.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
'use strict';
const shardUUID = require('./build/Release/shard-uuid.node');
const Long = require('long');
const is = require('is_js');
/**
* UUID (64bits) = timestamp (32 bits) | shardId (22 bits) | localId (10 bits)
*/
/**
* Convert buffer to Long
* @param buffer
* @returns {Long|undefined}
*/
function bufferToLong (buffer) {
return buffer ? new Long(buffer.readInt32LE(0), buffer.readInt32LE(4), true) : undefined;
}
module.exports = {
/**
* Generate UUID
* @param shardId
* @param localId
* @param timestamp
* @returns {Promise}
*/
getUUID (shardId, localId, timestamp) {
return new Promise((resolve, reject) => {
let buffer = shardUUID.getUUID(shardId, localId, timestamp);
if (is.existy(buffer)) {
let uuid = bufferToLong(buffer);
if (is.existy(uuid) && Long.isLong(uuid)) {
resolve(uuid.toString());
} else {
reject(new Error('UUID error: buffer conversion'));
}
} else {
reject(new Error('UUID error: empty buffer'));
}
});
},
/**
* Get time from UUID
* @param uuid
* @returns {Promise}
*/
getTime (uuid) {
return new Promise((resolve, reject) => {
let time = shardUUID.getTime(uuid);
if (is.existy(time) && is.number(time)) {
resolve(time);
} else {
reject(new Error('UUID error: invalid time'));
}
});
},
/**
* Get shard id from UUID
* @param uuid
* @returns {Promise}
*/
getShardId (uuid) {
return new Promise((resolve, reject) => {
let shardId = shardUUID.getShardId(uuid);
if (is.existy(shardId) && is.number(shardId)) {
resolve(shardId);
} else {
reject(new Error('UUID error: invalid shard id'));
}
});
},
/**
* Get local id from UUID
* @param uuid
* @returns {Promise}
*/
getLocalId (uuid) {
return new Promise((resolve, reject) => {
let localId = shardUUID.getLocalId(uuid);
if (is.existy(localId) && is.number(localId)) {
resolve(localId);
} else {
reject(new Error('UUID error: invalid local id'));
}
});
},
getInfo (uuid) {
return new Promise((resolve, reject) => {
let info = shardUUID.getInfo(uuid);
if (is.existy(info) && is.object(info)) {
resolve(info);
} else {
reject(new Error('UUID error: invalid info'));
}
});
}
}; | {
"content_hash": "5cc9ab13e33924656b63c9359667f9eb",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 93,
"avg_line_length": 27.235294117647058,
"alnum_prop": 0.49352051835853133,
"repo_name": "nanom1t/shard-uuid",
"id": "09f941f9259f7080216173d5d33dbe9738c777c8",
"size": "2778",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "4031"
},
{
"name": "JavaScript",
"bytes": "12919"
},
{
"name": "Python",
"bytes": "601"
}
],
"symlink_target": ""
} |
package operationexecutor
import (
"fmt"
"time"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
"k8s.io/kubernetes/pkg/api/v1"
"k8s.io/kubernetes/pkg/client/clientset_generated/clientset"
kevents "k8s.io/kubernetes/pkg/kubelet/events"
"k8s.io/kubernetes/pkg/util/mount"
"k8s.io/kubernetes/pkg/volume"
"k8s.io/kubernetes/pkg/volume/util/volumehelper"
)
var _ OperationGenerator = &operationGenerator{}
type operationGenerator struct {
// Used to fetch objects from the API server like Node in the
// VerifyControllerAttachedVolume operation.
kubeClient clientset.Interface
// volumePluginMgr is the volume plugin manager used to create volume
// plugin objects.
volumePluginMgr *volume.VolumePluginMgr
// recorder is used to record events in the API server
recorder record.EventRecorder
// checkNodeCapabilitiesBeforeMount, if set, enables the CanMount check,
// which verifies that the components (binaries, etc.) required to mount
// the volume are available on the underlying node before attempting mount.
checkNodeCapabilitiesBeforeMount bool
}
// NewOperationGenerator is returns instance of operationGenerator
func NewOperationGenerator(kubeClient clientset.Interface,
volumePluginMgr *volume.VolumePluginMgr,
recorder record.EventRecorder,
checkNodeCapabilitiesBeforeMount bool) OperationGenerator {
return &operationGenerator{
kubeClient: kubeClient,
volumePluginMgr: volumePluginMgr,
recorder: recorder,
checkNodeCapabilitiesBeforeMount: checkNodeCapabilitiesBeforeMount,
}
}
// OperationGenerator interface that extracts out the functions from operation_executor to make it dependency injectable
type OperationGenerator interface {
// Generates the MountVolume function needed to perform the mount of a volume plugin
GenerateMountVolumeFunc(waitForAttachTimeout time.Duration, volumeToMount VolumeToMount, actualStateOfWorldMounterUpdater ActualStateOfWorldMounterUpdater, isRemount bool) (func() error, error)
// Generates the UnmountVolume function needed to perform the unmount of a volume plugin
GenerateUnmountVolumeFunc(volumeToUnmount MountedVolume, actualStateOfWorld ActualStateOfWorldMounterUpdater) (func() error, error)
// Generates the AttachVolume function needed to perform attach of a volume plugin
GenerateAttachVolumeFunc(volumeToAttach VolumeToAttach, actualStateOfWorld ActualStateOfWorldAttacherUpdater) (func() error, error)
// Generates the DetachVolume function needed to perform the detach of a volume plugin
GenerateDetachVolumeFunc(volumeToDetach AttachedVolume, verifySafeToDetach bool, actualStateOfWorld ActualStateOfWorldAttacherUpdater) (func() error, error)
// Generates the VolumesAreAttached function needed to verify if volume plugins are attached
GenerateVolumesAreAttachedFunc(attachedVolumes []AttachedVolume, nodeName types.NodeName, actualStateOfWorld ActualStateOfWorldAttacherUpdater) (func() error, error)
// Generates the UnMountDevice function needed to perform the unmount of a device
GenerateUnmountDeviceFunc(deviceToDetach AttachedVolume, actualStateOfWorld ActualStateOfWorldMounterUpdater, mounter mount.Interface) (func() error, error)
// Generates the function needed to check if the attach_detach controller has attached the volume plugin
GenerateVerifyControllerAttachedVolumeFunc(volumeToMount VolumeToMount, nodeName types.NodeName, actualStateOfWorld ActualStateOfWorldAttacherUpdater) (func() error, error)
// GetVolumePluginMgr returns volume plugin manager
GetVolumePluginMgr() *volume.VolumePluginMgr
GenerateBulkVolumeVerifyFunc(
map[types.NodeName][]*volume.Spec,
string,
map[*volume.Spec]v1.UniqueVolumeName, ActualStateOfWorldAttacherUpdater) (func() error, error)
}
func (og *operationGenerator) GenerateVolumesAreAttachedFunc(
attachedVolumes []AttachedVolume,
nodeName types.NodeName,
actualStateOfWorld ActualStateOfWorldAttacherUpdater) (func() error, error) {
// volumesPerPlugin maps from a volume plugin to a list of volume specs which belong
// to this type of plugin
volumesPerPlugin := make(map[string][]*volume.Spec)
// volumeSpecMap maps from a volume spec to its unique volumeName which will be used
// when calling MarkVolumeAsDetached
volumeSpecMap := make(map[*volume.Spec]v1.UniqueVolumeName)
// Iterate each volume spec and put them into a map index by the pluginName
for _, volumeAttached := range attachedVolumes {
volumePlugin, err :=
og.volumePluginMgr.FindPluginBySpec(volumeAttached.VolumeSpec)
if err != nil || volumePlugin == nil {
glog.Errorf(volumeAttached.GenerateErrorDetailed("VolumesAreAttached.FindPluginBySpec failed", err).Error())
}
volumeSpecList, pluginExists := volumesPerPlugin[volumePlugin.GetPluginName()]
if !pluginExists {
volumeSpecList = []*volume.Spec{}
}
volumeSpecList = append(volumeSpecList, volumeAttached.VolumeSpec)
volumesPerPlugin[volumePlugin.GetPluginName()] = volumeSpecList
volumeSpecMap[volumeAttached.VolumeSpec] = volumeAttached.VolumeName
}
return func() error {
// For each volume plugin, pass the list of volume specs to VolumesAreAttached to check
// whether the volumes are still attached.
for pluginName, volumesSpecs := range volumesPerPlugin {
attachableVolumePlugin, err :=
og.volumePluginMgr.FindAttachablePluginByName(pluginName)
if err != nil || attachableVolumePlugin == nil {
glog.Errorf(
"VolumeAreAttached.FindAttachablePluginBySpec failed for plugin %q with: %v",
pluginName,
err)
continue
}
volumeAttacher, newAttacherErr := attachableVolumePlugin.NewAttacher()
if newAttacherErr != nil {
glog.Errorf(
"VolumesAreAttached.NewAttacher failed for getting plugin %q with: %v",
pluginName,
newAttacherErr)
continue
}
attached, areAttachedErr := volumeAttacher.VolumesAreAttached(volumesSpecs, nodeName)
if areAttachedErr != nil {
glog.Errorf(
"VolumesAreAttached failed for checking on node %q with: %v",
nodeName,
areAttachedErr)
continue
}
for spec, check := range attached {
if !check {
actualStateOfWorld.MarkVolumeAsDetached(volumeSpecMap[spec], nodeName)
glog.V(1).Infof("VerifyVolumesAreAttached determined volume %q (spec.Name: %q) is no longer attached to node %q, therefore it was marked as detached.",
volumeSpecMap[spec], spec.Name(), nodeName)
}
}
}
return nil
}, nil
}
func (og *operationGenerator) GenerateBulkVolumeVerifyFunc(
pluginNodeVolumes map[types.NodeName][]*volume.Spec,
pluginName string,
volumeSpecMap map[*volume.Spec]v1.UniqueVolumeName,
actualStateOfWorld ActualStateOfWorldAttacherUpdater) (func() error, error) {
return func() error {
attachableVolumePlugin, err :=
og.volumePluginMgr.FindAttachablePluginByName(pluginName)
if err != nil || attachableVolumePlugin == nil {
glog.Errorf(
"BulkVerifyVolume.FindAttachablePluginBySpec failed for plugin %q with: %v",
pluginName,
err)
return nil
}
volumeAttacher, newAttacherErr := attachableVolumePlugin.NewAttacher()
if newAttacherErr != nil {
glog.Errorf(
"BulkVerifyVolume.NewAttacher failed for getting plugin %q with: %v",
attachableVolumePlugin,
newAttacherErr)
return nil
}
bulkVolumeVerifier, ok := volumeAttacher.(volume.BulkVolumeVerifier)
if !ok {
glog.Errorf("BulkVerifyVolume failed to type assert attacher %q", bulkVolumeVerifier)
return nil
}
attached, bulkAttachErr := bulkVolumeVerifier.BulkVerifyVolumes(pluginNodeVolumes)
if bulkAttachErr != nil {
glog.Errorf("BulkVerifyVolume.BulkVerifyVolumes Error checking volumes are attached with %v", bulkAttachErr)
return nil
}
for nodeName, volumeSpecs := range pluginNodeVolumes {
for _, volumeSpec := range volumeSpecs {
nodeVolumeSpecs, nodeChecked := attached[nodeName]
if !nodeChecked {
glog.V(2).Infof("VerifyVolumesAreAttached.BulkVerifyVolumes failed for node %q and leaving volume %q as attached",
nodeName,
volumeSpec.Name())
continue
}
check := nodeVolumeSpecs[volumeSpec]
if !check {
glog.V(2).Infof("VerifyVolumesAreAttached.BulkVerifyVolumes failed for node %q and volume %q",
nodeName,
volumeSpec.Name())
actualStateOfWorld.MarkVolumeAsDetached(volumeSpecMap[volumeSpec], nodeName)
}
}
}
return nil
}, nil
}
func (og *operationGenerator) GenerateAttachVolumeFunc(
volumeToAttach VolumeToAttach,
actualStateOfWorld ActualStateOfWorldAttacherUpdater) (func() error, error) {
// Get attacher plugin
attachableVolumePlugin, err :=
og.volumePluginMgr.FindAttachablePluginBySpec(volumeToAttach.VolumeSpec)
if err != nil || attachableVolumePlugin == nil {
return nil, volumeToAttach.GenerateErrorDetailed("AttachVolume.FindAttachablePluginBySpec failed", err)
}
volumeAttacher, newAttacherErr := attachableVolumePlugin.NewAttacher()
if newAttacherErr != nil {
return nil, volumeToAttach.GenerateErrorDetailed("AttachVolume.NewAttacher failed", newAttacherErr)
}
return func() error {
// Execute attach
devicePath, attachErr := volumeAttacher.Attach(
volumeToAttach.VolumeSpec, volumeToAttach.NodeName)
if attachErr != nil {
// On failure, return error. Caller will log and retry.
eventErr, detailedErr := volumeToAttach.GenerateError("AttachVolume.Attach failed", attachErr)
for _, pod := range volumeToAttach.ScheduledPods {
og.recorder.Eventf(pod, v1.EventTypeWarning, kevents.FailedMountVolume, eventErr.Error())
}
return detailedErr
} else if devicePath == "" {
// do nothing and get device path next time.
return nil
}
glog.Infof(volumeToAttach.GenerateMsgDetailed("AttachVolume.Attach succeeded", ""))
// Update actual state of world
addVolumeNodeErr := actualStateOfWorld.MarkVolumeAsAttached(
v1.UniqueVolumeName(""), volumeToAttach.VolumeSpec, volumeToAttach.NodeName, devicePath)
if addVolumeNodeErr != nil {
// On failure, return error. Caller will log and retry.
return volumeToAttach.GenerateErrorDetailed("AttachVolume.MarkVolumeAsAttached failed", addVolumeNodeErr)
}
return nil
}, nil
}
func (og *operationGenerator) GetVolumePluginMgr() *volume.VolumePluginMgr {
return og.volumePluginMgr
}
func (og *operationGenerator) GenerateDetachVolumeFunc(
volumeToDetach AttachedVolume,
verifySafeToDetach bool,
actualStateOfWorld ActualStateOfWorldAttacherUpdater) (func() error, error) {
var volumeName string
var attachableVolumePlugin volume.AttachableVolumePlugin
var err error
if volumeToDetach.VolumeSpec != nil {
// Get attacher plugin
attachableVolumePlugin, err =
og.volumePluginMgr.FindAttachablePluginBySpec(volumeToDetach.VolumeSpec)
if err != nil || attachableVolumePlugin == nil {
return nil, volumeToDetach.GenerateErrorDetailed("DetachVolume.FindAttachablePluginBySpec failed", err)
}
volumeName, err =
attachableVolumePlugin.GetVolumeName(volumeToDetach.VolumeSpec)
if err != nil {
return nil, volumeToDetach.GenerateErrorDetailed("DetachVolume.GetVolumeName failed", err)
}
} else {
var pluginName string
// Get attacher plugin and the volumeName by splitting the volume unique name in case
// there's no VolumeSpec: this happens only on attach/detach controller crash recovery
// when a pod has been deleted during the controller downtime
pluginName, volumeName, err = volumehelper.SplitUniqueName(volumeToDetach.VolumeName)
if err != nil {
return nil, volumeToDetach.GenerateErrorDetailed("DetachVolume.SplitUniqueName failed", err)
}
attachableVolumePlugin, err = og.volumePluginMgr.FindAttachablePluginByName(pluginName)
if err != nil {
return nil, volumeToDetach.GenerateErrorDetailed("DetachVolume.FindAttachablePluginBySpec failed", err)
}
}
volumeDetacher, err := attachableVolumePlugin.NewDetacher()
if err != nil {
return nil, volumeToDetach.GenerateErrorDetailed("DetachVolume.NewDetacher failed", err)
}
return func() error {
var err error
if verifySafeToDetach {
err = og.verifyVolumeIsSafeToDetach(volumeToDetach)
}
if err == nil {
err = volumeDetacher.Detach(volumeName, volumeToDetach.NodeName)
}
if err != nil {
// On failure, add volume back to ReportAsAttached list
actualStateOfWorld.AddVolumeToReportAsAttached(
volumeToDetach.VolumeName, volumeToDetach.NodeName)
return volumeToDetach.GenerateErrorDetailed("DetachVolume.Detach failed", err)
}
glog.Infof(volumeToDetach.GenerateMsgDetailed("DetachVolume.Detach succeeded", ""))
// Update actual state of world
actualStateOfWorld.MarkVolumeAsDetached(
volumeToDetach.VolumeName, volumeToDetach.NodeName)
return nil
}, nil
}
func (og *operationGenerator) GenerateMountVolumeFunc(
waitForAttachTimeout time.Duration,
volumeToMount VolumeToMount,
actualStateOfWorld ActualStateOfWorldMounterUpdater,
isRemount bool) (func() error, error) {
// Get mounter plugin
volumePlugin, err :=
og.volumePluginMgr.FindPluginBySpec(volumeToMount.VolumeSpec)
if err != nil || volumePlugin == nil {
return nil, volumeToMount.GenerateErrorDetailed("MountVolume.FindPluginBySpec failed", err)
}
volumeMounter, newMounterErr := volumePlugin.NewMounter(
volumeToMount.VolumeSpec,
volumeToMount.Pod,
volume.VolumeOptions{})
if newMounterErr != nil {
eventErr, detailedErr := volumeToMount.GenerateError("MountVolume.NewMounter initialization failed", newMounterErr)
og.recorder.Eventf(volumeToMount.Pod, v1.EventTypeWarning, kevents.FailedMountVolume, eventErr.Error())
return nil, detailedErr
}
mountCheckError := checkMountOptionSupport(og, volumeToMount, volumePlugin)
if mountCheckError != nil {
return nil, mountCheckError
}
// Get attacher, if possible
attachableVolumePlugin, _ :=
og.volumePluginMgr.FindAttachablePluginBySpec(volumeToMount.VolumeSpec)
var volumeAttacher volume.Attacher
if attachableVolumePlugin != nil {
volumeAttacher, _ = attachableVolumePlugin.NewAttacher()
}
var fsGroup *types.UnixGroupID
if volumeToMount.Pod.Spec.SecurityContext != nil &&
volumeToMount.Pod.Spec.SecurityContext.FSGroup != nil {
fsGroup = volumeToMount.Pod.Spec.SecurityContext.FSGroup
}
return func() error {
if volumeAttacher != nil {
// Wait for attachable volumes to finish attaching
glog.Infof(volumeToMount.GenerateMsgDetailed("MountVolume.WaitForAttach entering", fmt.Sprintf("DevicePath %q", volumeToMount.DevicePath)))
devicePath, err := volumeAttacher.WaitForAttach(
volumeToMount.VolumeSpec, volumeToMount.DevicePath, waitForAttachTimeout)
if err != nil {
// On failure, return error. Caller will log and retry.
return volumeToMount.GenerateErrorDetailed("MountVolume.WaitForAttach failed", err)
}
glog.Infof(volumeToMount.GenerateMsgDetailed("MountVolume.WaitForAttach succeeded", ""))
deviceMountPath, err :=
volumeAttacher.GetDeviceMountPath(volumeToMount.VolumeSpec)
if err != nil {
// On failure, return error. Caller will log and retry.
return volumeToMount.GenerateErrorDetailed("MountVolume.GetDeviceMountPath failed", err)
}
// Mount device to global mount path
err = volumeAttacher.MountDevice(
volumeToMount.VolumeSpec,
devicePath,
deviceMountPath)
if err != nil {
// On failure, return error. Caller will log and retry.
eventErr, detailedErr := volumeToMount.GenerateError("MountVolume.MountDevice failed", err)
og.recorder.Eventf(volumeToMount.Pod, v1.EventTypeWarning, kevents.FailedMountVolume, eventErr.Error())
return detailedErr
}
glog.Infof(volumeToMount.GenerateMsgDetailed("MountVolume.MountDevice succeeded", fmt.Sprintf("device mount path %q", deviceMountPath)))
// Update actual state of world to reflect volume is globally mounted
markDeviceMountedErr := actualStateOfWorld.MarkDeviceAsMounted(
volumeToMount.VolumeName)
if markDeviceMountedErr != nil {
// On failure, return error. Caller will log and retry.
return volumeToMount.GenerateErrorDetailed("MountVolume.MarkDeviceAsMounted failed", markDeviceMountedErr)
}
}
if og.checkNodeCapabilitiesBeforeMount {
if canMountErr := volumeMounter.CanMount(); canMountErr != nil {
err = fmt.Errorf(
"Verify that your node machine has the required components before attempting to mount this volume type. %s",
canMountErr)
eventErr, detailedErr := volumeToMount.GenerateError("MountVolume.CanMount failed", err)
og.recorder.Eventf(volumeToMount.Pod, v1.EventTypeWarning, kevents.FailedMountVolume, eventErr.Error())
return detailedErr
}
}
// Execute mount
mountErr := volumeMounter.SetUp(fsGroup)
if mountErr != nil {
// On failure, return error. Caller will log and retry.
eventErr, detailedErr := volumeToMount.GenerateError("MountVolume.SetUp failed", mountErr)
og.recorder.Eventf(volumeToMount.Pod, v1.EventTypeWarning, kevents.FailedMountVolume, eventErr.Error())
return detailedErr
}
verbosity := glog.Level(1)
if isRemount {
verbosity = glog.Level(7)
}
glog.V(verbosity).Infof(volumeToMount.GenerateMsgDetailed("MountVolume.SetUp succeeded", ""))
// Update actual state of world
markVolMountedErr := actualStateOfWorld.MarkVolumeAsMounted(
volumeToMount.PodName,
volumeToMount.Pod.UID,
volumeToMount.VolumeName,
volumeMounter,
volumeToMount.OuterVolumeSpecName,
volumeToMount.VolumeGidValue)
if markVolMountedErr != nil {
// On failure, return error. Caller will log and retry.
return volumeToMount.GenerateErrorDetailed("MountVolume.MarkVolumeAsMounted failed", markVolMountedErr)
}
return nil
}, nil
}
func (og *operationGenerator) GenerateUnmountVolumeFunc(
volumeToUnmount MountedVolume,
actualStateOfWorld ActualStateOfWorldMounterUpdater) (func() error, error) {
// Get mountable plugin
volumePlugin, err :=
og.volumePluginMgr.FindPluginByName(volumeToUnmount.PluginName)
if err != nil || volumePlugin == nil {
return nil, volumeToUnmount.GenerateErrorDetailed("UnmountVolume.FindPluginByName failed", err)
}
volumeUnmounter, newUnmounterErr := volumePlugin.NewUnmounter(
volumeToUnmount.InnerVolumeSpecName, volumeToUnmount.PodUID)
if newUnmounterErr != nil {
return nil, volumeToUnmount.GenerateErrorDetailed("UnmountVolume.NewUnmounter failed", newUnmounterErr)
}
return func() error {
// Execute unmount
unmountErr := volumeUnmounter.TearDown()
if unmountErr != nil {
// On failure, return error. Caller will log and retry.
return volumeToUnmount.GenerateErrorDetailed("UnmountVolume.TearDown failed", unmountErr)
}
glog.Infof(
"UnmountVolume.TearDown succeeded for volume %q (OuterVolumeSpecName: %q) pod %q (UID: %q). InnerVolumeSpecName %q. PluginName %q, VolumeGidValue %q",
volumeToUnmount.VolumeName,
volumeToUnmount.OuterVolumeSpecName,
volumeToUnmount.PodName,
volumeToUnmount.PodUID,
volumeToUnmount.InnerVolumeSpecName,
volumeToUnmount.PluginName,
volumeToUnmount.VolumeGidValue)
// Update actual state of world
markVolMountedErr := actualStateOfWorld.MarkVolumeAsUnmounted(
volumeToUnmount.PodName, volumeToUnmount.VolumeName)
if markVolMountedErr != nil {
// On failure, just log and exit
glog.Errorf(volumeToUnmount.GenerateErrorDetailed("UnmountVolume.MarkVolumeAsUnmounted failed", markVolMountedErr).Error())
}
return nil
}, nil
}
func (og *operationGenerator) GenerateUnmountDeviceFunc(
deviceToDetach AttachedVolume,
actualStateOfWorld ActualStateOfWorldMounterUpdater,
mounter mount.Interface) (func() error, error) {
// Get attacher plugin
attachableVolumePlugin, err :=
og.volumePluginMgr.FindAttachablePluginBySpec(deviceToDetach.VolumeSpec)
if err != nil || attachableVolumePlugin == nil {
return nil, deviceToDetach.GenerateErrorDetailed("UnmountDevice.FindAttachablePluginBySpec failed", err)
}
volumeDetacher, err := attachableVolumePlugin.NewDetacher()
if err != nil {
return nil, deviceToDetach.GenerateErrorDetailed("UnmountDevice.NewDetacher failed", err)
}
volumeAttacher, err := attachableVolumePlugin.NewAttacher()
if err != nil {
return nil, deviceToDetach.GenerateErrorDetailed("UnmountDevice.NewAttacher failed", err)
}
return func() error {
deviceMountPath, err :=
volumeAttacher.GetDeviceMountPath(deviceToDetach.VolumeSpec)
if err != nil {
// On failure, return error. Caller will log and retry.
return deviceToDetach.GenerateErrorDetailed("GetDeviceMountPath failed", err)
}
refs, err := attachableVolumePlugin.GetDeviceMountRefs(deviceMountPath)
if err != nil || hasMountRefs(deviceMountPath, refs) {
if err == nil {
err = fmt.Errorf("The device mount path %q is still mounted by other references %v", deviceMountPath, refs)
}
return deviceToDetach.GenerateErrorDetailed("GetDeviceMountRefs check failed", err)
}
// Execute unmount
unmountDeviceErr := volumeDetacher.UnmountDevice(deviceMountPath)
if unmountDeviceErr != nil {
// On failure, return error. Caller will log and retry.
return deviceToDetach.GenerateErrorDetailed("UnmountDevice failed", unmountDeviceErr)
}
// Before logging that UnmountDevice succeeded and moving on,
// use mounter.PathIsDevice to check if the path is a device,
// if so use mounter.DeviceOpened to check if the device is in use anywhere
// else on the system. Retry if it returns true.
isDevicePath, devicePathErr := mounter.PathIsDevice(deviceToDetach.DevicePath)
var deviceOpened bool
var deviceOpenedErr error
if !isDevicePath && devicePathErr == nil {
// not a device path or path doesn't exist
//TODO: refer to #36092
glog.V(3).Infof("Not checking device path %s", deviceToDetach.DevicePath)
deviceOpened = false
} else {
deviceOpened, deviceOpenedErr = mounter.DeviceOpened(deviceToDetach.DevicePath)
if deviceOpenedErr != nil {
return deviceToDetach.GenerateErrorDetailed("UnmountDevice.DeviceOpened failed", deviceOpenedErr)
}
}
// The device is still in use elsewhere. Caller will log and retry.
if deviceOpened {
return deviceToDetach.GenerateErrorDetailed(
"UnmountDevice failed",
fmt.Errorf("the device is in use when it was no longer expected to be in use"))
}
glog.Infof(deviceToDetach.GenerateMsgDetailed("UnmountDevice succeeded", ""))
// Update actual state of world
markDeviceUnmountedErr := actualStateOfWorld.MarkDeviceAsUnmounted(
deviceToDetach.VolumeName)
if markDeviceUnmountedErr != nil {
// On failure, return error. Caller will log and retry.
return deviceToDetach.GenerateErrorDetailed("MarkDeviceAsUnmounted failed", markDeviceUnmountedErr)
}
return nil
}, nil
}
func (og *operationGenerator) GenerateVerifyControllerAttachedVolumeFunc(
volumeToMount VolumeToMount,
nodeName types.NodeName,
actualStateOfWorld ActualStateOfWorldAttacherUpdater) (func() error, error) {
return func() error {
if !volumeToMount.PluginIsAttachable {
// If the volume does not implement the attacher interface, it is
// assumed to be attached and the actual state of the world is
// updated accordingly.
addVolumeNodeErr := actualStateOfWorld.MarkVolumeAsAttached(
volumeToMount.VolumeName, volumeToMount.VolumeSpec, nodeName, "" /* devicePath */)
if addVolumeNodeErr != nil {
// On failure, return error. Caller will log and retry.
return volumeToMount.GenerateErrorDetailed("VerifyControllerAttachedVolume.MarkVolumeAsAttachedByUniqueVolumeName failed", addVolumeNodeErr)
}
return nil
}
if !volumeToMount.ReportedInUse {
// If the given volume has not yet been added to the list of
// VolumesInUse in the node's volume status, do not proceed, return
// error. Caller will log and retry. The node status is updated
// periodically by kubelet, so it may take as much as 10 seconds
// before this clears.
// Issue #28141 to enable on demand status updates.
return volumeToMount.GenerateErrorDetailed("Volume has not been added to the list of VolumesInUse in the node's volume status", nil)
}
// Fetch current node object
node, fetchErr := og.kubeClient.Core().Nodes().Get(string(nodeName), metav1.GetOptions{})
if fetchErr != nil {
// On failure, return error. Caller will log and retry.
return volumeToMount.GenerateErrorDetailed("VerifyControllerAttachedVolume failed fetching node from API server", fetchErr)
}
if node == nil {
// On failure, return error. Caller will log and retry.
return volumeToMount.GenerateErrorDetailed(
"VerifyControllerAttachedVolume failed",
fmt.Errorf("Node object retrieved from API server is nil"))
}
for _, attachedVolume := range node.Status.VolumesAttached {
if attachedVolume.Name == volumeToMount.VolumeName {
addVolumeNodeErr := actualStateOfWorld.MarkVolumeAsAttached(
v1.UniqueVolumeName(""), volumeToMount.VolumeSpec, nodeName, attachedVolume.DevicePath)
glog.Infof(volumeToMount.GenerateMsgDetailed("Controller attach succeeded", fmt.Sprintf("device path: %q", attachedVolume.DevicePath)))
if addVolumeNodeErr != nil {
// On failure, return error. Caller will log and retry.
return volumeToMount.GenerateErrorDetailed("VerifyControllerAttachedVolume.MarkVolumeAsAttached failed", addVolumeNodeErr)
}
return nil
}
}
// Volume not attached, return error. Caller will log and retry.
return volumeToMount.GenerateErrorDetailed("Volume not attached according to node status", nil)
}, nil
}
func (og *operationGenerator) verifyVolumeIsSafeToDetach(
volumeToDetach AttachedVolume) error {
// Fetch current node object
node, fetchErr := og.kubeClient.Core().Nodes().Get(string(volumeToDetach.NodeName), metav1.GetOptions{})
if fetchErr != nil {
if errors.IsNotFound(fetchErr) {
glog.Warningf(volumeToDetach.GenerateMsgDetailed("Node not found on API server. DetachVolume will skip safe to detach check", ""))
return nil
}
// On failure, return error. Caller will log and retry.
return volumeToDetach.GenerateErrorDetailed("DetachVolume failed fetching node from API server", fetchErr)
}
if node == nil {
// On failure, return error. Caller will log and retry.
return volumeToDetach.GenerateErrorDetailed(
"DetachVolume failed fetching node from API server",
fmt.Errorf("node object retrieved from API server is nil"))
}
for _, inUseVolume := range node.Status.VolumesInUse {
if inUseVolume == volumeToDetach.VolumeName {
return volumeToDetach.GenerateErrorDetailed(
"DetachVolume failed",
fmt.Errorf("volume is still in use by node, according to Node status"))
}
}
// Volume is not marked as in use by node
glog.Infof(volumeToDetach.GenerateMsgDetailed("Verified volume is safe to detach", ""))
return nil
}
func checkMountOptionSupport(og *operationGenerator, volumeToMount VolumeToMount, plugin volume.VolumePlugin) error {
mountOptions := volume.MountOptionFromSpec(volumeToMount.VolumeSpec)
if len(mountOptions) > 0 && !plugin.SupportsMountOption() {
eventErr, detailedErr := volumeToMount.GenerateError("Mount options are not supported for this volume type", nil)
og.recorder.Eventf(volumeToMount.Pod, v1.EventTypeWarning, kevents.UnsupportedMountOption, eventErr.Error())
return detailedErr
}
return nil
}
| {
"content_hash": "9dd671c25c2e5bcb4870e779cccb41dd",
"timestamp": "",
"source": "github",
"line_count": 701,
"max_line_length": 194,
"avg_line_length": 39.00713266761769,
"alnum_prop": 0.7706260971328263,
"repo_name": "bobveznat/kubernetes",
"id": "20059b527ace52bbdbca069fb32f91c91ab4cdf9",
"size": "27913",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "pkg/volume/util/operationexecutor/operation_generator.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2525"
},
{
"name": "Go",
"bytes": "47517634"
},
{
"name": "HTML",
"bytes": "2708865"
},
{
"name": "Makefile",
"bytes": "79498"
},
{
"name": "Nginx",
"bytes": "1608"
},
{
"name": "PowerShell",
"bytes": "4261"
},
{
"name": "Protocol Buffer",
"bytes": "730956"
},
{
"name": "Python",
"bytes": "2088383"
},
{
"name": "Ruby",
"bytes": "1296"
},
{
"name": "SaltStack",
"bytes": "54360"
},
{
"name": "Shell",
"bytes": "1551068"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace BGE
{
class Lazer:MonoBehaviour
{
public void Update()
{
float speed = 5.0f;
float width = 500;
float height = 500;
if ((transform.position.x < -(width / 2)) || (transform.position.x > width / 2) || (transform.position.z < -(height / 2)) || (transform.position.z > height / 2) || (transform.position.y < 0) || (transform.position.y > 100))
{
Destroy(gameObject);
}
transform.position += transform.forward * speed;
LineDrawer.DrawLine(transform.position, transform.position + transform.forward * 10.0f, Color.red);
}
}
}
| {
"content_hash": "6103a960dadc53e597a9573781cacc2b",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 235,
"avg_line_length": 31.08,
"alnum_prop": 0.5817245817245817,
"repo_name": "PaulKennedyDIT/Unity_SpaceBattle_Assignment_2",
"id": "16ed7a0eef7608a317535fb3041c26eef554d935",
"size": "779",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "Assets/Code/Lazer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "118649"
},
{
"name": "C",
"bytes": "2483"
},
{
"name": "C#",
"bytes": "213512"
},
{
"name": "JavaScript",
"bytes": "10830"
}
],
"symlink_target": ""
} |
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The type WorkbookChartSetPositionRequest.
/// </summary>
public partial class WorkbookChartSetPositionRequest : BaseRequest, IWorkbookChartSetPositionRequest
{
/// <summary>
/// Constructs a new WorkbookChartSetPositionRequest.
/// </summary>
public WorkbookChartSetPositionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
this.ContentType = "application/json";
this.RequestBody = new WorkbookChartSetPositionRequestBody();
}
/// <summary>
/// Gets the request body.
/// </summary>
public WorkbookChartSetPositionRequestBody RequestBody { get; private set; }
/// <summary>
/// Issues the POST request.
/// </summary>
public System.Threading.Tasks.Task PostAsync()
{
return this.PostAsync(CancellationToken.None);
}
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name=""cancellationToken"">The <see cref=""CancellationToken""/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task PostAsync(
CancellationToken cancellationToken)
{
this.Method = "POST";
return this.SendAsync(this.RequestBody, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartSetPositionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartSetPositionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
}
}
| {
"content_hash": "98b6abe77f7b86283ef8e906e4d5d480",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 108,
"avg_line_length": 32.532467532467535,
"alnum_prop": 0.5892215568862276,
"repo_name": "garethj-msft/msgraph-sdk-dotnet",
"id": "e598a6d341f4412d0e1ca33383e7f0ddd5b2879f",
"size": "2909",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Microsoft.Graph/Requests/Generated/WorkbookChartSetPositionRequest.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "9032877"
},
{
"name": "Smalltalk",
"bytes": "12638"
}
],
"symlink_target": ""
} |
'''@file multi_target_dummy_processor.py
contains the MultiTargetDummyProcessor class'''
import os
import subprocess
import StringIO
import scipy.io.wavfile as wav
import numpy as np
import processor
from nabu.processing.feature_computers import feature_computer_factory
import pdb
class MultiTargetDummyProcessor(processor.Processor):
'''a processor for audio files, this will compute the multiple targets'''
def __init__(self, conf, segment_lengths):
'''MultiTargetDummyProcessor constructor
Args:
conf: MultiTargetDummyProcessor configuration as a dict of strings
segment_lengths: A list containing the desired lengths of segments.
Possibly multiple segment lengths'''
#create the feature computer
self.comp = feature_computer_factory.factory(conf['feature'])(conf)
#set the length of the segments. Possibly multiple segment lengths
self.segment_lengths = segment_lengths
#initialize the metadata
self.nrS = int(conf['nrs'])
self.target_dim = self.comp.get_dim()
self.nontime_dims=[self.target_dim,self.nrS]
super(MultiTargetDummyProcessor, self).__init__(conf)
def __call__(self, dataline):
'''process the data in dataline
Args:
dataline: either a path to a wav file or a command to read and pipe
an audio file
Returns:
segmented_data: The segmented targets as a list of numpy arrays per segment length
utt_info: some info on the utterance'''
utt_info= dict()
targets = None
for ind in range(self.nrS):
#read the wav file
rate, utt = _read_wav(dataline)
#compute the features
features = self.comp(utt, rate)
features = np.expand_dims(features, 2)
if targets is None:
targets = features
else:
targets = np.append(targets,features,2)
# split the data for all desired segment lengths
segmented_data = self.segment_data(targets)
return segmented_data, utt_info
def write_metadata(self, datadir):
'''write the processor metadata to disk
Args:
dir: the directory where the metadata should be written'''
for i,seg_length in enumerate(self.segment_lengths):
seg_dir = os.path.join(datadir,seg_length)
with open(os.path.join(seg_dir, 'nrS'), 'w') as fid:
fid.write(str(self.nrS))
with open(os.path.join(seg_dir, 'dim'), 'w') as fid:
fid.write(str(self.target_dim))
with open(os.path.join(seg_dir, 'nontime_dims'), 'w') as fid:
fid.write(str(self.nontime_dims)[1:-1])
def _read_wav(wavfile):
'''
read a wav file
Args:
wavfile: either a path to a wav file or a command to read and pipe
an audio file
Returns:
- the sampling rate
- the utterance as a numpy array
'''
if os.path.exists(wavfile):
#its a file
(rate, utterance) = wav.read(wavfile)
elif wavfile[-1] == '|':
#its a command
#read the audio file
pid = subprocess.Popen(wavfile + ' tee', shell=True,
stdout=subprocess.PIPE)
output, _ = pid.communicate()
output_buffer = StringIO.StringIO(output)
(rate, utterance) = wav.read(output_buffer)
else:
#its a segment of an utterance
split = wavfile.split(' ')
begin = float(split[-2])
end = float(split[-1])
unsegmented = ' '.join(split[:-2])
rate, full_utterance = _read_wav(unsegmented)
utterance = full_utterance[int(begin*rate):int(end*rate)]
return rate, utterance
| {
"content_hash": "bf51043f67c4f7d895617809678687da",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 94,
"avg_line_length": 31.025,
"alnum_prop": 0.6226161697555734,
"repo_name": "JeroenZegers/Nabu-MSSS",
"id": "4b030cbdbdc318395ea67fe3015391f3981f0673",
"size": "3723",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nabu/processing/processors/multi_target_dummy_processor.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "981104"
},
{
"name": "Shell",
"bytes": "4125"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="5b21e2ff-84bc-455d-9e49-58d639886e46" name="Default" comment="">
<change type="MODIFICATION" beforePath="$PROJECT_DIR$/public/js/app.js" afterPath="$PROJECT_DIR$/public/js/app.js" />
</list>
<ignored path="gifs.iws" />
<ignored path=".idea/workspace.xml" />
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<option name="TRACKING_ENABLED" value="true" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
<component name="CreatePatchCommitExecutor">
<option name="PATCH_PATH" value="" />
</component>
<component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
<component name="FavoritesManager">
<favorites_list name="gifs" />
</component>
<component name="FileEditorManager">
<leaf>
<file leaf-file-name="index.js" pinned="true" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/../generator/routes/index.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="2" column="0" selection-start-line="2" selection-start-column="0" selection-end-line="2" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="app.js" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/src/app/app.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="17" column="5" selection-start-line="17" selection-start-column="5" selection-end-line="17" selection-end-column="5" />
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="app.js" pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/public/js/app.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.7989865">
<caret line="181" column="40" selection-start-line="181" selection-start-column="40" selection-end-line="181" selection-end-column="40" />
<folding>
<element signature="e#2569#2584#0" expanded="false" />
<element signature="e#8270#8296#0" expanded="false" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="HTML5.js" pinned="false" current-in-tab="false">
<entry file="jar://$APPLICATION_HOME_DIR$/plugins/JavaScriptLanguage/lib/JavaScriptLanguage.jar!/com/intellij/lang/javascript/index/predefined/HTML5.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="1269" column="0" selection-start-line="1269" selection-start-column="0" selection-end-line="1269" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="gulpfile.js" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/gulpfile.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="33" column="43" selection-start-line="33" selection-start-column="43" selection-end-line="33" selection-end-column="43" />
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="gif.js" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/models/gif.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="22" column="6" selection-start-line="22" selection-start-column="6" selection-end-line="22" selection-end-column="6" />
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="index.jade" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/views/index.jade">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="10" column="43" selection-start-line="10" selection-start-column="35" selection-end-line="10" selection-end-column="43" />
<folding>
<marker date="1437147127799" expanded="true" signature="21:329" placeholder="..." />
<marker date="1437147127799" expanded="true" signature="224:299" placeholder="..." />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="list.jade" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/views/angular/list.jade">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="3" column="73" selection-start-line="3" selection-start-column="73" selection-end-line="3" selection-end-column="73" />
<folding>
<marker date="1437150102146" expanded="true" signature="6:428" placeholder="..." />
</folding>
</state>
</provider>
</entry>
</file>
</leaf>
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="IdeDocumentHistory">
<option name="CHANGED_PATHS">
<list>
<option value="$PROJECT_DIR$/public/css/lib.min.css" />
<option value="$PROJECT_DIR$/lib/gifMiddleware.js" />
<option value="$PROJECT_DIR$/lib/gifService.js" />
<option value="$PROJECT_DIR$/lib/file-service.js" />
<option value="$PROJECT_DIR$/lib/gif-service.js" />
<option value="$PROJECT_DIR$/models/gif.js" />
<option value="$PROJECT_DIR$/routes/api/gifs.js" />
<option value="$PROJECT_DIR$/app.js" />
<option value="$PROJECT_DIR$/routes/index.js" />
<option value="$PROJECT_DIR$/src/app/index.js" />
<option value="$PROJECT_DIR$/src/app/directives.js" />
<option value="$PROJECT_DIR$/src/app/index.coffee" />
<option value="$PROJECT_DIR$/src/app/directives.coffee" />
<option value="$PROJECT_DIR$/views/layout.jade" />
<option value="$PROJECT_DIR$/gulpfile.js" />
<option value="$PROJECT_DIR$/poc/video.html" />
<option value="$PROJECT_DIR$/views/index.jade" />
<option value="$PROJECT_DIR$/views/angular/list.jade" />
<option value="$PROJECT_DIR$/public/js/app.js" />
</list>
</option>
</component>
<component name="JsBuildToolGruntFileManager" detection-done="true" />
<component name="JsGulpfileManager">
<detection-done>true</detection-done>
<gulpfiles>
<GulpfileState>
<gulpfile-path>$PROJECT_DIR$/gulpfile.js</gulpfile-path>
</GulpfileState>
<GulpfileState>
<gulpfile-path>$PROJECT_DIR$/gulpfile.config.js</gulpfile-path>
</GulpfileState>
</gulpfiles>
</component>
<component name="JsKarmaPackageDirSetting">
<data>C:\Users\altuhov\AppData\Roaming\npm\node_modules\karma</data>
</component>
<component name="NamedScopeManager">
<order />
</component>
<component name="ProjectFrameBounds">
<option name="x" value="-8" />
<option name="y" value="-8" />
<option name="width" value="1936" />
<option name="height" value="1056" />
</component>
<component name="ProjectLevelVcsManager" settingsEditedManually="false">
<OptionsSetting value="true" id="Add" />
<OptionsSetting value="true" id="Remove" />
<OptionsSetting value="true" id="Checkout" />
<OptionsSetting value="true" id="Update" />
<OptionsSetting value="true" id="Status" />
<OptionsSetting value="true" id="Edit" />
<ConfirmationsSetting value="2" id="Add" />
<ConfirmationsSetting value="0" id="Remove" />
</component>
<component name="ProjectView">
<navigator currentView="ProjectPane" proportions="" version="1">
<flattenPackages />
<showMembers />
<showModules />
<showLibraryContents />
<hideEmptyPackages />
<abbreviatePackageNames />
<autoscrollToSource />
<autoscrollFromSource />
<sortByType />
</navigator>
<panes>
<pane id="ProjectPane">
<subPane>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="gifs" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="gifs" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="gifs" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="gifs" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="gifs" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="views" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="gifs" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="gifs" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="views" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="angular" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="gifs" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="gifs" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="public" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="gifs" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="gifs" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="public" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="js" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="gifs" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="gifs" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="models" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="gifs" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="gifs" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="lib" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
</subPane>
</pane>
<pane id="Scope" />
<pane id="Scratches" />
</panes>
</component>
<component name="PropertiesComponent">
<property name="settings.editor.selected.configurable" value="JavaScript.Libraries" />
<property name="settings.editor.splitter.proportion" value="0.2" />
<property name="WebServerToolWindowFactoryState" value="false" />
<property name="HbShouldOpenHtmlAsHb" value="" />
<property name="recentsLimit" value="5" />
<property name="last_opened_file_path" value="$PROJECT_DIR$" />
<property name="restartRequiresConfirmation" value="true" />
<property name="FullScreen" value="false" />
</component>
<component name="RunManager" selected="Node.js.www">
<configuration default="false" name="www" type="NodeJSConfigurationType" factoryName="Node.js" temporary="true" path-to-node="C:/Program Files/nodejs/node" path-to-js-file="$PROJECT_DIR$/bin/www" working-dir="$PROJECT_DIR$">
<envs>
<env name="MONGOLAB_URI" value="localhost/gifs" />
</envs>
<method />
</configuration>
<configuration default="true" type="DartCommandLineRunConfigurationType" factoryName="Dart Command Line Application">
<method />
</configuration>
<configuration default="true" type="DartUnitRunConfigurationType" factoryName="DartUnit">
<method />
</configuration>
<configuration default="true" type="JavaScriptTestRunnerKarma" factoryName="Karma" config-file="">
<envs />
<method />
</configuration>
<configuration default="true" type="JavascriptDebugType" factoryName="JavaScript Debug">
<method />
</configuration>
<configuration default="true" type="JsTestDriver-test-runner" factoryName="JsTestDriver">
<setting name="configLocationType" value="CONFIG_FILE" />
<setting name="settingsFile" value="" />
<setting name="serverType" value="INTERNAL" />
<setting name="preferredDebugBrowser" value="Chrome" />
<method />
</configuration>
<configuration default="true" type="NodeJSConfigurationType" factoryName="Node.js" path-to-node="C:/Program Files/nodejs/node" path-to-js-file="$PROJECT_DIR$/bin/www" working-dir="$PROJECT_DIR$">
<envs>
<env name="MONGOLAB_URI" value="localhost/gifs" />
</envs>
<method />
</configuration>
<configuration default="true" type="NodeJSRemoteDebug" factoryName="Node.js Remote Debug">
<node-js-remote-debug />
<method />
</configuration>
<configuration default="true" type="NodeWebKit" factoryName="NW.js">
<method />
</configuration>
<configuration default="true" type="cucumber.js" factoryName="Cucumber.js">
<option name="cucumberJsArguments" value="" />
<option name="executablePath" />
<option name="filePath" />
<method />
</configuration>
<configuration default="true" type="js.build_tools.gulp" factoryName="Gulp.js">
<node-options />
<gulpfile />
<tasks />
<arguments />
<pass-parent-envs>true</pass-parent-envs>
<envs />
<method />
</configuration>
<list size="1">
<item index="0" class="java.lang.String" itemvalue="Node.js.www" />
</list>
<recent_temporary>
<list size="1">
<item index="0" class="java.lang.String" itemvalue="Node.js.www" />
</list>
</recent_temporary>
</component>
<component name="ShelveChangesManager" show_recycled="false" />
<component name="SvnConfiguration">
<configuration />
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="5b21e2ff-84bc-455d-9e49-58d639886e46" name="Default" comment="" />
<created>1436774262261</created>
<option name="number" value="Default" />
<updated>1436774262261</updated>
</task>
<servers />
</component>
<component name="TodoView">
<todo-panel id="selected-file">
<is-autoscroll-to-source value="true" />
</todo-panel>
<todo-panel id="all">
<are-packages-shown value="true" />
<is-autoscroll-to-source value="true" />
</todo-panel>
</component>
<component name="ToolWindowManager">
<frame x="-8" y="-8" width="1936" height="1056" extended-state="6" />
<editor active="true" />
<layout>
<window_info id="Gulp" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="true" content_ui="tabs" />
<window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.24973656" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
<window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32972974" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
<window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="true" content_ui="tabs" />
<window_info id="Application Servers" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
<window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.32972974" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32972974" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
<window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32972974" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
<window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32972974" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
<window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="true" content_ui="tabs" />
<window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
<window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
<window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
<window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
<window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
<window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
<window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
</layout>
</component>
<component name="Vcs.Log.UiProperties">
<option name="RECENTLY_FILTERED_USER_GROUPS">
<collection />
</option>
<option name="RECENTLY_FILTERED_BRANCH_GROUPS">
<collection />
</option>
</component>
<component name="VcsContentAnnotationSettings">
<option name="myLimit" value="2678400000" />
</component>
<component name="XDebuggerManager">
<breakpoint-manager>
<breakpoints-dialog>
<breakpoints-dialog />
</breakpoints-dialog>
<option name="time" value="13" />
</breakpoint-manager>
<watches-manager />
</component>
<component name="editorHistoryManager">
<entry file="file://$PROJECT_DIR$/routes/index.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="1" column="7" selection-start-line="1" selection-start-column="7" selection-end-line="1" selection-end-column="7" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/models/gif.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="18" column="19" selection-start-line="18" selection-start-column="19" selection-end-line="18" selection-end-column="19" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/routes/api/index.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="2" column="24" selection-start-line="2" selection-start-column="24" selection-end-line="2" selection-end-column="24" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/../file_upload/server.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="5" column="0" selection-start-line="5" selection-start-column="0" selection-end-line="6" selection-end-column="38" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/lib/file-service.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="13" column="9" selection-start-line="13" selection-start-column="9" selection-end-line="13" selection-end-column="9" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/package.json">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="32" column="23" selection-start-line="32" selection-start-column="23" selection-end-line="32" selection-end-column="23" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/app.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="15" column="39" selection-start-line="15" selection-start-column="39" selection-end-line="15" selection-end-column="39" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/../pasport_auth/app/models/user.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="27" column="0" selection-start-line="27" selection-start-column="0" selection-end-line="27" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/routes/index.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="4" column="0" selection-start-line="4" selection-start-column="0" selection-end-line="4" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/routes/api/gifs.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="11" column="18" selection-start-line="11" selection-start-column="18" selection-end-line="11" selection-end-column="18" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/models/gif.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="10" column="3" selection-start-line="10" selection-start-column="3" selection-end-line="10" selection-end-column="3" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/routes/api/index.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="2" column="24" selection-start-line="2" selection-start-column="24" selection-end-line="2" selection-end-column="24" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/public/css/lib.min.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="15.740741">
<caret line="4" column="3679" selection-start-line="4" selection-start-column="3679" selection-end-line="4" selection-end-column="3679" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/Procfile">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/README.md">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/.env">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="1" column="43" selection-start-line="1" selection-start-column="43" selection-end-line="1" selection-end-column="43" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/node_modules/body-parser/package.json">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/package.json">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="32" column="23" selection-start-line="32" selection-start-column="23" selection-end-line="32" selection-end-column="23" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/../pasport_auth/app/models/user.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="25" column="5" selection-start-line="25" selection-start-column="5" selection-end-line="25" selection-end-column="5" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/../file_upload/server.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.26532888">
<caret line="19" column="17" selection-start-line="19" selection-start-column="17" selection-end-line="19" selection-end-column="17" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/lib/file-service.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="13" column="9" selection-start-line="13" selection-start-column="9" selection-end-line="13" selection-end-column="9" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/../new_chat/models/user.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="50" column="53" selection-start-line="50" selection-start-column="53" selection-end-line="50" selection-end-column="53" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/node_modules/mongoose/lib/utils.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.05743243">
<caret line="101" column="3" selection-start-line="101" selection-start-column="3" selection-end-line="101" selection-end-column="3" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/node_modules/mongoose/index.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.1722973">
<caret line="6" column="30" selection-start-line="6" selection-start-column="30" selection-end-line="6" selection-end-column="30" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/../generator/app.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="30" column="19" selection-start-line="30" selection-start-column="19" selection-end-line="30" selection-end-column="19" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/bin/www">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="6" column="10" selection-start-line="6" selection-start-column="10" selection-end-line="6" selection-end-column="10" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/node_modules/express/lib/router/index.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="453" column="23" selection-start-line="453" selection-start-column="23" selection-end-line="453" selection-end-column="23" />
</state>
</provider>
</entry>
<entry file="file://$USER_HOME$/.WebStorm10/system/extLibs/nodejs-v0.11.14-nightly-20140819-pre-src/core-modules-sources/lib/module.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="450" column="7" selection-start-line="450" selection-start-column="7" selection-end-line="450" selection-end-column="7" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/routes/api/gifs.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="12" column="0" selection-start-line="12" selection-start-column="0" selection-end-line="12" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/routes/api/index.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="4" column="6" selection-start-line="4" selection-start-column="0" selection-end-line="4" selection-end-column="6" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/app.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="5" column="27" selection-start-line="5" selection-start-column="27" selection-end-line="5" selection-end-column="27" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/routes/index.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="15" column="26" selection-start-line="15" selection-start-column="26" selection-end-line="15" selection-end-column="26" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/views/5xx.jade">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="-3.148148">
<caret line="5" column="7" selection-start-line="5" selection-start-column="7" selection-end-line="5" selection-end-column="7" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/app/directives.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="78" column="54" selection-start-line="78" selection-start-column="54" selection-end-line="78" selection-end-column="54" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/public/js/lib.min.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/views/layout.jade">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="-4.4074073">
<caret line="7" column="27" selection-start-line="7" selection-start-column="27" selection-end-line="7" selection-end-column="27" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/public/js/app.min.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/app/app.coffee">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="19" column="10" selection-start-line="19" selection-start-column="10" selection-end-line="19" selection-end-column="10" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/app/app.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="17" column="5" selection-start-line="17" selection-start-column="5" selection-end-line="17" selection-end-column="5" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/app/directives.coffee">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.18053098">
<caret line="19" column="32" selection-start-line="19" selection-start-column="32" selection-end-line="19" selection-end-column="32" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/app/index.coffee">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="1.0831858">
<caret line="36" column="1" selection-start-line="36" selection-start-column="1" selection-end-line="36" selection-end-column="1" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/app/index.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.028716216">
<caret line="1" column="0" selection-start-line="1" selection-start-column="0" selection-end-line="1" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/../generator/routes/index.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="2" column="0" selection-start-line="2" selection-start-column="0" selection-end-line="2" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/gulpfile.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="33" column="43" selection-start-line="33" selection-start-column="43" selection-end-line="33" selection-end-column="43" />
<folding />
</state>
</provider>
</entry>
<entry file="jar://$APPLICATION_HOME_DIR$/plugins/JavaScriptLanguage/lib/JavaScriptLanguage.jar!/com/intellij/lang/javascript/index/predefined/HTML5.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="1269" column="0" selection-start-line="1269" selection-start-column="0" selection-end-line="1269" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/poc/video.html">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="-0.38162544">
<caret line="36" column="13" selection-start-line="36" selection-start-column="13" selection-end-line="36" selection-end-column="13" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/gulpfile.config.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.8614865">
<caret line="30" column="2" selection-start-line="30" selection-start-column="2" selection-end-line="30" selection-end-column="2" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/models/gif.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="22" column="6" selection-start-line="22" selection-start-column="6" selection-end-line="22" selection-end-column="6" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/views/index.jade">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="10" column="43" selection-start-line="10" selection-start-column="35" selection-end-line="10" selection-end-column="43" />
<folding>
<marker date="1437147127799" expanded="true" signature="21:329" placeholder="..." />
<marker date="1437147127799" expanded="true" signature="224:299" placeholder="..." />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/views/angular/list.jade">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="3" column="73" selection-start-line="3" selection-start-column="73" selection-end-line="3" selection-end-column="73" />
<folding>
<marker date="1437150102146" expanded="true" signature="6:428" placeholder="..." />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/public/js/app.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.7989865">
<caret line="181" column="40" selection-start-line="181" selection-start-column="40" selection-end-line="181" selection-end-column="40" />
<folding>
<element signature="e#2569#2584#0" expanded="false" />
<element signature="e#8270#8296#0" expanded="false" />
</folding>
</state>
</provider>
</entry>
</component>
</project> | {
"content_hash": "89c152f4ca19f5b771f552a7149dea62",
"timestamp": "",
"source": "github",
"line_count": 827,
"max_line_length": 228,
"avg_line_length": 51.67956469165659,
"alnum_prop": 0.6210252930578628,
"repo_name": "Albametr/gifs",
"id": "f58f2a43bcbc4731ee5a47aa2ca0e66d1a544a95",
"size": "42739",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/workspace.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "4667"
},
{
"name": "HTML",
"bytes": "4046"
},
{
"name": "JavaScript",
"bytes": "25187"
}
],
"symlink_target": ""
} |
ALTER TABLE gistic_genomic_region_reporter ADD COLUMN GENOMIC_DESCRIPTOR VARCHAR(100) AFTER ID; | {
"content_hash": "960eb393cc90f8ae5196229d3dbc4d08",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 95,
"avg_line_length": 95,
"alnum_prop": 0.8421052631578947,
"repo_name": "NCIP/caintegrator",
"id": "ffb9f097ef2ced9704f1c1fe935edb6f83896e48",
"size": "95",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "common/resources/db-upgrade/mysql/1.2/upgrade-1.2.08.sql",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "61091"
},
{
"name": "FreeMarker",
"bytes": "30688"
},
{
"name": "HTML",
"bytes": "828"
},
{
"name": "Java",
"bytes": "5239823"
},
{
"name": "JavaScript",
"bytes": "163834"
},
{
"name": "PLSQL",
"bytes": "55084"
},
{
"name": "Perl",
"bytes": "2710"
},
{
"name": "Shell",
"bytes": "3376"
},
{
"name": "TeX",
"bytes": "90"
},
{
"name": "XSLT",
"bytes": "157133"
}
],
"symlink_target": ""
} |
(function(addon) {
var component;
if (jQuery && jQuery.UIkit) {
component = addon(jQuery, jQuery.UIkit);
}
if (typeof define == "function" && define.amd) {
define("uikit-autocomplete", ["uikit"], function(){
return component || addon(jQuery, jQuery.UIkit);
});
}
})(function($, UI){
UI.component('autocomplete', {
defaults: {
minLength: 3,
param: 'search',
method: 'post',
delay: 300,
loadingClass: 'uk-loading',
flipDropdown: false,
skipClass: 'uk-skip',
hoverClass: 'uk-active',
source: null,
renderer: null,
// template
template: '<ul class="uk-nav uk-nav-autocomplete uk-autocomplete-results">{{~items}}<li data-value="{{$item.value}}"><a>{{$item.value}}</a></li>{{/items}}</ul>'
},
visible : false,
value : null,
selected : null,
init: function() {
var $this = this,
select = false,
trigger = UI.Utils.debounce(function(e) {
if(select) {
return (select = false);
}
$this.handle();
}, this.options.delay);
this.dropdown = this.find('.uk-dropdown');
this.template = this.find('script[type="text/autocomplete"]').html();
this.template = UI.Utils.template(this.template || this.options.template);
this.input = this.find("input:first").attr("autocomplete", "off");
if (!this.dropdown.length) {
this.dropdown = $('<div class="uk-dropdown"></div>').appendTo(this.element);
}
if (this.options.flipDropdown) {
this.dropdown.addClass('uk-dropdown-flip');
}
this.input.on({
"keydown": function(e) {
if (e && e.which && !e.shiftKey) {
switch (e.which) {
case 13: // enter
select = true;
if ($this.selected) {
e.preventDefault();
$this.select();
}
break;
case 38: // up
e.preventDefault();
$this.pick('prev', true);
break;
case 40: // down
e.preventDefault();
$this.pick('next', true);
break;
case 27:
case 9: // esc, tab
$this.hide();
break;
default:
break;
}
}
},
"keyup": trigger,
"blur": function(e) {
setTimeout(function() { $this.hide(); }, 200);
}
});
this.dropdown.on("click", ".uk-autocomplete-results > *", function(){
$this.select();
});
this.dropdown.on("mouseover", ".uk-autocomplete-results > *", function(){
$this.pick($(this));
});
this.triggercomplete = trigger;
},
handle: function() {
var $this = this, old = this.value;
this.value = this.input.val();
if (this.value.length < this.options.minLength) return this.hide();
if (this.value != old) {
$this.request();
}
return this;
},
pick: function(item, scrollinview) {
var $this = this,
items = this.dropdown.find('.uk-autocomplete-results').children(':not(.'+this.options.skipClass+')'),
selected = false;
if (typeof item !== "string" && !item.hasClass(this.options.skipClass)) {
selected = item;
} else if (item == 'next' || item == 'prev') {
if (this.selected) {
var index = items.index(this.selected);
if (item == 'next') {
selected = items.eq(index + 1 < items.length ? index + 1 : 0);
} else {
selected = items.eq(index - 1 < 0 ? items.length - 1 : index - 1);
}
} else {
selected = items[(item == 'next') ? 'first' : 'last']();
}
}
if (selected && selected.length) {
this.selected = selected;
items.removeClass(this.options.hoverClass);
this.selected.addClass(this.options.hoverClass);
// jump to selected if not in view
if (scrollinview) {
var top = selected.position().top,
scrollTop = $this.dropdown.scrollTop(),
dpheight = $this.dropdown.height();
if (top > dpheight || top < 0) {
$this.dropdown.scrollTop(scrollTop + top);
}
}
}
},
select: function() {
if(!this.selected) return;
var data = this.selected.data();
this.trigger("autocomplete-select", [data, this]);
if (data.value) {
this.input.val(data.value);
}
this.hide();
},
show: function() {
if (this.visible) return;
this.visible = true;
this.element.addClass("uk-open");
return this;
},
hide: function() {
if (!this.visible) return;
this.visible = false;
this.element.removeClass("uk-open");
return this;
},
request: function() {
var $this = this,
release = function(data) {
if(data) {
$this.render(data);
}
$this.element.removeClass($this.options.loadingClass);
};
this.element.addClass(this.options.loadingClass);
if (this.options.source) {
var source = this.options.source;
switch(typeof(this.options.source)) {
case 'function':
this.options.source.apply(this, [release]);
break;
case 'object':
if(source.length) {
var items = [];
source.forEach(function(item){
if(item.value && item.value.toLowerCase().indexOf($this.value.toLowerCase())!=-1) {
items.push(item);
}
});
release(items);
}
break;
case 'string':
var params ={};
params[this.options.param] = this.value;
$.ajax({
url: this.options.source,
data: params,
type: this.options.method,
dataType: 'json',
complete: function(xhr) {
release(xhr.responseJSON || []);
}
});
break;
default:
release(null);
}
} else {
this.element.removeClass($this.options.loadingClass);
}
},
render: function(data) {
var $this = this;
this.dropdown.empty();
this.selected = false;
if (this.options.renderer) {
this.options.renderer.apply(this, [data]);
} else if(data && data.length) {
this.dropdown.append(this.template({"items":data}));
this.show();
this.trigger('autocomplete-show');
}
return this;
}
});
// init code
$(document).on("focus.autocomplete.uikit", "[data-uk-autocomplete]", function(e) {
var ele = $(this);
if (!ele.data("autocomplete")) {
var obj = UI.autocomplete(ele, UI.Utils.options(ele.attr("data-uk-autocomplete")));
}
});
return UI.autocomplete;
}); | {
"content_hash": "b86fc938d42d7827ef9e753cc699ec9d",
"timestamp": "",
"source": "github",
"line_count": 304,
"max_line_length": 172,
"avg_line_length": 29.49671052631579,
"alnum_prop": 0.39600758336121333,
"repo_name": "depapp/tambut",
"id": "dd4532cd445583987da0750f4807beebbf5c5d0a",
"size": "8967",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/uikit/uikit/src/js/addons/autocomplete.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "607312"
},
{
"name": "HTML",
"bytes": "33590"
},
{
"name": "JavaScript",
"bytes": "2799286"
},
{
"name": "PHP",
"bytes": "286864"
},
{
"name": "Shell",
"bytes": "1490"
}
],
"symlink_target": ""
} |
/**
* @Author: KingZhao
*/
package com.jcommerce.core.service;
import java.util.List;
import com.jcommerce.core.model.AutoManage;
import com.jcommerce.core.service.Criteria;
public interface AutoManageManager extends Manager {
public AutoManage initialize(AutoManage obj);
public List<AutoManage> getAutoManageList(int firstRow, int maxRow);
public int getAutoManageCount(Criteria criteria);
public List<AutoManage> getAutoManageList(Criteria criteria);
public List<AutoManage> getAutoManageList(int firstRow, int maxRow, Criteria criteria);
public List<AutoManage> getAutoManageList();
public AutoManage getAutoManage(Long id);
public void saveAutoManage(AutoManage obj);
public void removeAutoManage(Long id);
}
| {
"content_hash": "4446482b0789a546f4f14612cb02852c",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 91,
"avg_line_length": 26.24137931034483,
"alnum_prop": 0.7726675427069645,
"repo_name": "jbosschina/jcommerce",
"id": "3ac7aabd46ff198fa397663d48450f9d5e7db189",
"size": "761",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "sandbox/core/src/main/java/com/jcommerce/core/service/AutoManageManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "200608"
},
{
"name": "GAP",
"bytes": "2286"
},
{
"name": "Java",
"bytes": "4485563"
}
],
"symlink_target": ""
} |
angular.module('quick-survey').directive('questionDetails', function () {
return {
restrict: 'A',
scope: {
question: '=',
questionTypes: '=',
index: '=',
// TODO: figure out a way to not pass survey through here, just
// the save() method on survey.
questions: '=',
save: '='
},
controller: function ($scope) {
$scope.editingQuestion = false;
$scope.saved = false;
$scope.editQuestion = function (question) {
$scope.editingQuestion = !$scope.editingQuestion;
};
$scope.cancel = function(question) {
$scope.editingQuestion = false;
};
$scope.deleteQuestion = function (index) {
var success = confirm("Are you sure you want to delete this question?");
if (success) {
$scope.questions.splice(index, 1);
$scope.save();
}
};
$scope.isDisabled = function (question) {
if (question.type === 'radio') {
return question.options.length <= 1;
}
return false;
}
},
templateUrl: 'client/js/manage/directives/question-details.ng.html',
};
});
| {
"content_hash": "f6998cdcdee88598cfbfec9eac554672",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 80,
"avg_line_length": 26.930232558139537,
"alnum_prop": 0.5578583765112263,
"repo_name": "simonv3/quick-survey",
"id": "4da46d800ea728f6c622eafb9e745418757c15f2",
"size": "1158",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "client/js/manage/directives/question-details.ng.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "2522"
},
{
"name": "CSS",
"bytes": "5474"
},
{
"name": "Cap'n Proto",
"bytes": "8284"
},
{
"name": "HTML",
"bytes": "15338"
},
{
"name": "JavaScript",
"bytes": "481336"
},
{
"name": "Makefile",
"bytes": "713"
},
{
"name": "Ruby",
"bytes": "4160"
},
{
"name": "Shell",
"bytes": "5339"
}
],
"symlink_target": ""
} |
package com._4dconcept.springframework.data.marklogic.repository.query;
import com._4dconcept.springframework.data.marklogic.core.MarklogicOperations;
import com._4dconcept.springframework.data.marklogic.core.query.Query;
import org.springframework.data.repository.query.ParameterAccessor;
import org.springframework.data.repository.query.ParametersParameterAccessor;
import org.springframework.data.repository.query.RepositoryQuery;
import org.springframework.data.repository.query.ResultProcessor;
import org.springframework.util.Assert;
/**
* Base class for {@link RepositoryQuery} implementations for Marklogic.
*
* @author Stéphane Toussaint
*/
public abstract class AbstractMarklogicQuery implements RepositoryQuery {
private final MarklogicQueryMethod method;
private final MarklogicOperations operations;
/**
* Creates a new {@link AbstractMarklogicQuery} from the given {@link MarklogicQueryMethod} and {@link MarklogicOperations}.
*
* @param method must not be {@literal null}.
* @param operations must not be {@literal null}.
*/
AbstractMarklogicQuery(MarklogicQueryMethod method, MarklogicOperations operations) {
Assert.notNull(operations, "MarklogicOperations must not be null!");
Assert.notNull(method, "MarklogicQueryMethod must not be null!");
this.method = method;
this.operations = operations;
}
public MarklogicQueryMethod getQueryMethod() {
return method;
}
public Object execute(Object[] parameters) {
ParameterAccessor accessor = new ParametersParameterAccessor(method.getParameters(), parameters);
Query query = createQuery(accessor);
ResultProcessor processor = method.getResultProcessor().withDynamicProjection(accessor);
if (isDeleteQuery()) {
// operations.remove(query);
return null;
} else if (method.isCollectionQuery()) {
return operations.find(query, processor.getReturnedType().getDomainType());
} else {
return operations.findOne(query, processor.getReturnedType().getDomainType());
}
}
/**
* Creates a {@link Query} instance using the given {@link ParameterAccessor}
*
* @param accessor must not be {@literal null}.
* @return a created Query instance
*/
protected abstract Query createQuery(ParameterAccessor accessor);
protected abstract boolean isDeleteQuery();
}
| {
"content_hash": "b9cbeba912de5e30bbdef17fc48f9829",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 128,
"avg_line_length": 36.791044776119406,
"alnum_prop": 0.7233265720081136,
"repo_name": "stoussaint/spring-data-marklogic",
"id": "7fb1386354debbfef5710e757be4211c3f8183e1",
"size": "3081",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/_4dconcept/springframework/data/marklogic/repository/query/AbstractMarklogicQuery.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "467712"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "d2497a56becda3308d598e6f5a6a1349",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "8a32c9dd395e62dfa15a19366d000ca77efc8928",
"size": "193",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Plantaginaceae/Pseudolysimachion/Pseudolysimachion orchideum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
namespace Sakuno.IO
{
public sealed class RecyclableMemoryStream : Stream
{
BufferPool r_BufferPool;
volatile int r_DisposeState;
bool IsOpen => r_DisposeState == 0;
int r_Length;
int r_Position;
public override bool CanRead => IsOpen;
public override bool CanSeek => IsOpen;
public override bool CanWrite => IsOpen;
public override long Length
{
get
{
CheckDisposed();
return r_Length;
}
}
public override long Position
{
get
{
CheckDisposed();
return r_Position;
}
set
{
r_Position = (int)value;
}
}
public int Capacity
{
get
{
CheckDisposed();
return r_BufferPool.BlockSize * r_Blocks.Count;
}
set
{
CheckDisposed();
EnsureCapacity(value);
}
}
readonly byte[] r_ByteBuffer = new byte[1];
readonly List<BufferSegment> r_Blocks = new List<BufferSegment>(1);
public RecyclableMemoryStream() : this(BufferPool.Default) { }
public RecyclableMemoryStream(BufferPool bufferPool)
{
r_BufferPool = bufferPool;
}
void CheckDisposed()
{
if (!IsOpen)
throw new ObjectDisposedException("The stream is disposed.");
}
public override int Read(byte[] buffer, int offset, int count)
{
CheckDisposed();
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), "The offset cannot be negative.");
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), "The count cannot be negative.");
if (offset + count > buffer.Length)
throw new ArgumentException("The length of buffer should not be less than offset + count.");
var rCount = ReadCore(buffer, offset, r_Position, count);
r_Position += rCount;
return rCount;
}
unsafe int ReadCore(byte[] rpBuffer, int rpOffset, int rpStartPosition, int rpCount)
{
if (r_Length <= rpStartPosition)
return 0;
var rBlockSize = r_BufferPool.BlockSize;
var rBlockIndex = rpStartPosition / rBlockSize;
var rBlockOffset = rpStartPosition % rBlockSize;
var rRemaining = Math.Min(rpCount, r_Length - rpStartPosition);
var rWritten = 0;
fixed (byte* rInput = rpBuffer)
while (rRemaining > 0)
{
var rSource = r_Blocks[rBlockIndex].Address + rBlockOffset;
var rDesination = rInput + rpOffset + rWritten;
var rCount = Math.Min(rBlockSize - rBlockOffset, rRemaining);
Memory.Copy(rSource, rDesination, rCount);
rWritten += rCount;
rRemaining -= rCount;
rBlockIndex++;
rBlockOffset = 0;
}
return rWritten;
}
public override long Seek(long offset, SeekOrigin origin)
{
CheckDisposed();
if (offset > int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(offset), "The offset cannot be greater than " + int.MaxValue);
int rNewPosition;
switch (origin)
{
case SeekOrigin.Begin:
rNewPosition = (int)offset;
break;
case SeekOrigin.Current:
rNewPosition = (int)offset + r_Position;
break;
case SeekOrigin.End:
rNewPosition = (int)offset;
break;
default:
throw new ArgumentException(nameof(origin), "The origin is invalid.");
}
if (rNewPosition < 0)
throw new IOException("The new position is before the beginning.");
return r_Position = rNewPosition;
}
public override void SetLength(long value)
{
CheckDisposed();
if (value < 0 || value > int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(value), "The value must be non-negative and at most " + int.MaxValue);
var rLength = (int)value;
EnsureCapacity(rLength);
r_Length = rLength;
if (r_Position > rLength)
r_Position = rLength;
}
void EnsureCapacity(int rpSize)
{
var rCapacity = Capacity;
var rBlockSize = r_BufferPool.BlockSize;
while (rCapacity < rpSize)
{
r_Blocks.Add(r_BufferPool.AcquireBlock());
rCapacity += rBlockSize;
}
}
public override unsafe void Write(byte[] buffer, int offset, int count)
{
CheckDisposed();
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), "The offset cannot be negative.");
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), "The count cannot be negative.");
if (offset + count > buffer.Length)
throw new ArgumentException("The length of buffer should not be less than offset + count.");
EnsureCapacity(r_Position + count);
var rBlockSize = r_BufferPool.BlockSize;
var rBlockIndex = r_Position / rBlockSize;
var rBlockOffset = r_Position % rBlockSize;
var rRemaining = count;
var rWritten = 0;
fixed (byte* rInput = buffer)
while (rRemaining > 0)
{
var rSource = rInput + offset + rWritten;
var rDesination = r_Blocks[rBlockIndex].Address + rBlockOffset;
var rCount = Math.Min(rBlockSize - rBlockOffset, rRemaining);
Memory.Copy(rSource, rDesination, rCount);
rWritten += rCount;
rRemaining -= rCount;
rBlockIndex++;
rBlockOffset = 0;
}
r_Position += count;
r_Length = Math.Max(r_Length, r_Position);
}
public override void WriteByte(byte value)
{
CheckDisposed();
r_ByteBuffer[0] = value;
Write(r_ByteBuffer, 0, 1);
}
public void WriteTo(Stream stream)
{
CheckDisposed();
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var rBlockIndex = 0;
var rRemaining = r_Length;
while (rRemaining > 0)
{
var rSegment = r_Blocks[rBlockIndex];
var rCount = Math.Min(rSegment.Length, rRemaining);
stream.Write(rSegment.Buffer, rSegment.Offset, rCount);
rRemaining -= rCount;
rBlockIndex++;
}
}
public override void Flush() { }
public byte[] ToArray()
{
CheckDisposed();
var rResult = new byte[r_Length];
ReadCore(rResult, 0, 0, r_Length);
return rResult;
}
~RecyclableMemoryStream() { Dispose(false); }
public override void Close() => Dispose(true);
protected override void Dispose(bool rpDisposing)
{
if (Interlocked.Exchange(ref r_DisposeState, 1) != 0)
return;
if (rpDisposing)
GC.SuppressFinalize(this);
r_BufferPool.Collect(r_Blocks);
r_Blocks.Clear();
base.Dispose(rpDisposing);
}
}
}
| {
"content_hash": "04dda6f1fb7576d4daac3130b8254f2a",
"timestamp": "",
"source": "github",
"line_count": 279,
"max_line_length": 131,
"avg_line_length": 30.096774193548388,
"alnum_prop": 0.5100631177801596,
"repo_name": "KodamaSakuno/Library",
"id": "6f33f6c3da5cbe58a50734f082603241dde6a673",
"size": "8399",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Sakuno.Base/IO/RecyclableMemoryStream.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "543281"
},
{
"name": "HLSL",
"bytes": "534"
}
],
"symlink_target": ""
} |
<?php
namespace Oro\Bundle\WorkflowBundle\Tests\Functional\Entity\Repository;
use Doctrine\ORM\EntityManager;
use Oro\Bundle\WorkflowBundle\Entity\ProcessDefinition;
use Oro\Bundle\WorkflowBundle\Entity\ProcessTrigger;
use Oro\Bundle\WorkflowBundle\Entity\Repository\ProcessTriggerRepository;
use Oro\Bundle\TestFrameworkBundle\Test\WebTestCase;
use Oro\Bundle\WorkflowBundle\Tests\Functional\DataFixtures\LoadProcessEntities;
class ProcessTriggerRepositoryTest extends WebTestCase
{
/**
* @var ProcessTriggerRepository
*/
protected $repository;
/**
* @var EntityManager
*/
protected $entityManager;
protected function setUp()
{
$this->initClient();
$doctrine = $this->getContainer()->get('doctrine');
$this->loadFixtures(['Oro\Bundle\WorkflowBundle\Tests\Functional\DataFixtures\LoadProcessEntities']);
$this->entityManager = $doctrine->getManager();
$this->repository = $doctrine->getRepository('OroWorkflowBundle:ProcessTrigger');
}
public function testEqualTriggers()
{
$definition = $this->entityManager->find(
'OroWorkflowBundle:ProcessDefinition',
LoadProcessEntities::FIRST_DEFINITION
);
$trigger = $this->repository->findOneBy(['definition' => $definition]);
// test equal (existing) trigger
$equalTrigger = new ProcessTrigger();
$equalTrigger->setDefinition($definition)
->setEvent(ProcessTrigger::EVENT_UPDATE)
->setField(LoadProcessEntities::UPDATE_TRIGGER_FIELD);
$this->assertEquals($trigger, $this->repository->findEqualTrigger($equalTrigger));
$this->assertTrue($this->repository->isEqualTriggerExists($equalTrigger));
// test not equal (not existing) trigger
$notEqualTrigger = new ProcessTrigger();
$notEqualTrigger->setDefinition($definition)
->setEvent(ProcessTrigger::EVENT_CREATE);
$this->assertNull($this->repository->findEqualTrigger($notEqualTrigger));
$this->assertFalse($this->repository->isEqualTriggerExists($notEqualTrigger));
}
public function testFindAllWithDefinitions()
{
// all definitions
$triggers = $this->repository->findAllWithDefinitions();
$this->assertCount($this->getTriggersCount(), $triggers);
$this->assertTriggersOrder($triggers);
// enabled definitions
$triggers = $this->repository->findAllWithDefinitions(true);
$this->assertCount($this->getTriggersCount(true), $triggers);
$this->assertTriggersOrder($triggers);
// disabled definitions
$triggers = $this->repository->findAllWithDefinitions(false);
$this->assertCount($this->getTriggersCount(false), $triggers);
$this->assertTriggersOrder($triggers);
// without cron triggers
$triggers = $this->repository->findAllWithDefinitions(false, false);
$this->assertCount($this->getTriggersCount(false, false), $triggers);
$this->assertTriggersOrder($triggers);
}
public function testFindAllCronTriggers()
{
$triggers = $this->repository->findAllCronTriggers();
$this->assertContains($this->getReference(LoadProcessEntities::TRIGGER_CRON), $triggers);
$this->assertNotContains($this->getReference(LoadProcessEntities::TRIGGER_CREATE), $triggers);
}
/**
* @param ProcessTrigger[] $triggers
*/
protected function assertTriggersOrder(array $triggers)
{
$previousOrder = null;
foreach ($triggers as $trigger) {
$this->assertInstanceOf('Oro\Bundle\WorkflowBundle\Entity\ProcessTrigger', $trigger);
$definition = $trigger->getDefinition();
$executionOrder = $definition->getExecutionOrder();
if ($previousOrder === null) {
$previousOrder = $executionOrder;
}
$this->assertGreaterThanOrEqual($previousOrder, $executionOrder);
$previousOrder = $executionOrder;
}
}
/**
* @param bool|null $enabled
* @param bool $withCronTriggers
* @return int
*/
protected function getTriggersCount($enabled = null, $withCronTriggers = false)
{
$queryBuilder = $this->repository->createQueryBuilder('trigger')
->select('COUNT(trigger.id) as triggerCount')
->innerJoin('trigger.definition', 'definition');
if (!$withCronTriggers) {
$queryBuilder->andWhere($queryBuilder->expr()->isNull('trigger.cron'));
$queryBuilder->andWhere($queryBuilder->expr()->isNotNull('trigger.event'));
}
if (null !== $enabled) {
$queryBuilder->andWhere('definition.enabled = :enabled')->setParameter('enabled', $enabled);
}
return (int)$queryBuilder->getQuery()->getSingleScalarResult();
}
public function testFindByDefinitionName()
{
$firstDefinitionTriggers = $this->repository->findByDefinitionName(LoadProcessEntities::FIRST_DEFINITION);
$this->assertCount(1, $firstDefinitionTriggers);
$this->assertContains($this->getReference(LoadProcessEntities::TRIGGER_UPDATE), $firstDefinitionTriggers);
$this->assertNotContains($this->getReference(LoadProcessEntities::TRIGGER_CREATE), $firstDefinitionTriggers);
$this->assertNotContains($this->getReference(LoadProcessEntities::TRIGGER_DISABLED), $firstDefinitionTriggers);
$firstDefinitionTriggers = $this->repository->findByDefinitionName(LoadProcessEntities::SECOND_DEFINITION);
$this->assertCount(3, $firstDefinitionTriggers);
$this->assertContains($this->getReference(LoadProcessEntities::TRIGGER_CREATE), $firstDefinitionTriggers);
$this->assertNotContains($this->getReference(LoadProcessEntities::TRIGGER_UPDATE), $firstDefinitionTriggers);
$this->assertNotContains($this->getReference(LoadProcessEntities::TRIGGER_DISABLED), $firstDefinitionTriggers);
}
}
| {
"content_hash": "7a4f0484623ce2e86b2bad834e7d31e4",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 119,
"avg_line_length": 39.546052631578945,
"alnum_prop": 0.6777574446847446,
"repo_name": "Djamy/platform",
"id": "17c1906cc29c01c19899c17f0c2a21a5fbd0624b",
"size": "6011",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Oro/Bundle/WorkflowBundle/Tests/Functional/Entity/Repository/ProcessTriggerRepositoryTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "542736"
},
{
"name": "Gherkin",
"bytes": "73480"
},
{
"name": "HTML",
"bytes": "1633049"
},
{
"name": "JavaScript",
"bytes": "3284434"
},
{
"name": "PHP",
"bytes": "35536269"
}
],
"symlink_target": ""
} |
package org.hisp.dhis.webapi.controller.metadata.version;
import org.apache.commons.lang.StringUtils;
import org.hisp.dhis.common.cache.CacheStrategy;
import org.hisp.dhis.dxf2.metadata.version.exception.MetadataVersionServiceException;
import org.hisp.dhis.metadata.version.MetadataVersion;
import org.hisp.dhis.metadata.version.MetadataVersionService;
import org.hisp.dhis.metadata.version.VersionType;
import org.hisp.dhis.node.types.RootNode;
import org.hisp.dhis.schema.descriptors.MetadataVersionSchemaDescriptor;
import org.hisp.dhis.setting.SettingKey;
import org.hisp.dhis.setting.SystemSettingManager;
import org.hisp.dhis.webapi.controller.CrudControllerAdvice;
import org.hisp.dhis.webapi.controller.exception.MetadataVersionException;
import org.hisp.dhis.webapi.mvc.annotation.ApiVersion;
import org.hisp.dhis.webapi.utils.ContextUtils;
import org.omg.PortableServer.CurrentPackage.NoContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.zip.GZIPOutputStream;
/**
* Controller for MetadataVersion
*
* @author aamerm
*/
@Controller
@ApiVersion( { ApiVersion.Version.DEFAULT, ApiVersion.Version.ALL } )
public class MetadataVersionController
extends CrudControllerAdvice
{
@Autowired
private SystemSettingManager systemSettingManager;
@Autowired
private MetadataVersionService versionService;
@Autowired
private ContextUtils contextUtils;
//Gets the version by versionName or latest system version
@RequestMapping( value = MetadataVersionSchemaDescriptor.API_ENDPOINT, method = RequestMethod.GET, produces = ContextUtils.CONTENT_TYPE_JSON )
public @ResponseBody MetadataVersion getMetaDataVersion( @RequestParam( value = "versionName", required = false ) String versionName ) throws MetadataVersionException
{
MetadataVersion versionToReturn = null;
boolean enabled = isMetadataVersioningEnabled();
try
{
if ( !enabled )
{
throw new MetadataVersionException( "Metadata versioning is not enabled for this instance." );
}
if ( StringUtils.isNotEmpty( versionName ) )
{
versionToReturn = versionService.getVersionByName( versionName );
if ( versionToReturn == null )
{
throw new MetadataVersionException( "No metadata version with name " + versionName + " exists. Please check again later." );
}
}
else
{
versionToReturn = versionService.getCurrentVersion();
if ( versionToReturn == null )
{
throw new MetadataVersionException( "No metadata versions exist. Please check again later." );
}
}
return versionToReturn;
}
catch ( MetadataVersionServiceException ex )
{
throw new MetadataVersionException( "Exception occurred while getting metadata version." + (StringUtils.isNotEmpty( versionName ) ? versionName : " ") + ex.getMessage(), ex );
}
}
//Gets the list of all versions in between the passed version name and latest system version
@RequestMapping( value = MetadataVersionSchemaDescriptor.API_ENDPOINT + "/history", method = RequestMethod.GET, produces = ContextUtils.CONTENT_TYPE_JSON )
public @ResponseBody RootNode getMetaDataVersionHistory( @RequestParam( value = "baseline", required = false ) String versionName )
throws MetadataVersionException, NoContext
{
List<MetadataVersion> allVersionsInBetween = new ArrayList<>();
boolean enabled = isMetadataVersioningEnabled();
try
{
if ( !enabled )
{
throw new MetadataVersionException( "Metadata versioning is not enabled for this instance." );
}
Date startDate;
if ( versionName == null || versionName.isEmpty() )
{
MetadataVersion initialVersion = versionService.getInitialVersion();
if ( initialVersion == null )
{
return versionService.getMetadataVersionsAsNode( allVersionsInBetween );
}
startDate = initialVersion.getCreated();
}
else
{
startDate = versionService.getCreatedDate( versionName );
}
if ( startDate == null )
{
throw new MetadataVersionException( "There is no such metadata version. The latest version is Version " + versionService.getCurrentVersion().getName() );
}
Date endDate = new Date();
allVersionsInBetween = versionService.getAllVersionsInBetween( startDate, endDate );
if ( allVersionsInBetween != null )
{
//now remove the baseline version details
for ( Iterator<MetadataVersion> iterator = allVersionsInBetween.iterator(); iterator.hasNext(); )
{
MetadataVersion m = iterator.next();
if ( m.getName().equals( versionName ) )
{
iterator.remove();
break;
}
}
if ( !allVersionsInBetween.isEmpty() )
{
return versionService.getMetadataVersionsAsNode( allVersionsInBetween );
}
}
}
catch ( MetadataVersionServiceException ex )
{
throw new MetadataVersionException( ex.getMessage(), ex );
}
return null;
}
//Gets the list of all versions
@RequestMapping( value = "/metadata/versions", method = RequestMethod.GET, produces = ContextUtils.CONTENT_TYPE_JSON )
public @ResponseBody RootNode getAllVersion() throws MetadataVersionException
{
boolean enabled = isMetadataVersioningEnabled();
try
{
if ( !enabled )
{
throw new MetadataVersionException( "Metadata versioning is not enabled for this instance." );
}
List<MetadataVersion> allVersions = versionService.getAllVersions();
return versionService.getMetadataVersionsAsNode( allVersions );
}
catch ( MetadataVersionServiceException ex )
{
throw new MetadataVersionException( "Exception occurred while getting all metadata versions. " + ex.getMessage() );
}
}
//Creates version in versioning table, exports the metadata and saves the snapshot in datastore
@PreAuthorize( "hasRole('ALL') or hasRole('F_METADATA_MANAGE')" )
@RequestMapping( value = MetadataVersionSchemaDescriptor.API_ENDPOINT + "/create", method = RequestMethod.POST, produces = ContextUtils.CONTENT_TYPE_JSON )
public @ResponseBody MetadataVersion createSystemVersion( @RequestParam( value = "type", required = true ) VersionType versionType ) throws MetadataVersionException
{
MetadataVersion versionToReturn = null;
boolean enabled = isMetadataVersioningEnabled();
try
{
if ( !enabled )
{
throw new MetadataVersionException( "Metadata versioning is not enabled for this instance." );
}
versionService.saveVersion( versionType );
versionToReturn = versionService.getCurrentVersion();
return versionToReturn;
}
catch ( MetadataVersionServiceException ex )
{
throw new MetadataVersionException( "Unable to create version in system. " + ex.getMessage() );
}
}
//endpoint to download metadata
@PreAuthorize( "hasRole('ALL') or hasRole('F_METADATA_MANAGE')" )
@RequestMapping( value = MetadataVersionSchemaDescriptor.API_ENDPOINT + "/{versionName}/data", method = RequestMethod.GET, produces = "application/json" )
public @ResponseBody String downloadVersion( @PathVariable( "versionName" ) String versionName ) throws MetadataVersionException
{
boolean enabled = isMetadataVersioningEnabled();
try
{
if ( !enabled )
{
throw new MetadataVersionException( "Metadata versioning is not enabled for this instance." );
}
String versionData = versionService.getVersionData( versionName );
if ( versionData == null )
{
throw new MetadataVersionException( "No metadata version snapshot found for the given version " + versionName );
}
return versionData;
}
catch ( MetadataVersionServiceException ex )
{
throw new MetadataVersionException( "Unable to download version from system: " + versionName + ex.getMessage() );
}
}
//endpoint to download metadata in gzip format
@PreAuthorize( "hasRole('ALL') or hasRole('F_METADATA_MANAGE')" )
@RequestMapping( value = MetadataVersionSchemaDescriptor.API_ENDPOINT + "/{versionName}/data.gz", method = RequestMethod.GET, produces = "*/*" )
public void downloadGZipVersion( @PathVariable( "versionName" ) String versionName, HttpServletResponse response ) throws MetadataVersionException, IOException
{
boolean enabled = isMetadataVersioningEnabled();
try
{
if ( !enabled )
{
throw new MetadataVersionException( "Metadata versioning is not enabled for this instance." );
}
contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_GZIP, CacheStrategy.NO_CACHE, "metadata.json.gz", true );
response.addHeader( ContextUtils.HEADER_CONTENT_TRANSFER_ENCODING, "binary" );
String versionData = versionService.getVersionData( versionName );
if ( versionData == null )
{
throw new MetadataVersionException( "No metadata version snapshot found for the given version " + versionName );
}
GZIPOutputStream gos = new GZIPOutputStream( response.getOutputStream() );
gos.write( versionData.getBytes( StandardCharsets.UTF_8 ) );
gos.close();
}
catch ( MetadataVersionServiceException ex )
{
throw new MetadataVersionException( "Unable to download version from system: " + versionName + ex.getMessage() );
}
}
//----------------------------------------------------------------------------------------
// Private Methods
//----------------------------------------------------------------------------------------
private boolean isMetadataVersioningEnabled()
{
Boolean setting = (Boolean) systemSettingManager.getSystemSetting( SettingKey.METADATAVERSION_ENABLED );
return setting.booleanValue();
}
}
| {
"content_hash": "ca792f7eaae5e387c807b01b8b151ce5",
"timestamp": "",
"source": "github",
"line_count": 292,
"max_line_length": 187,
"avg_line_length": 39.78767123287671,
"alnum_prop": 0.6403856085384748,
"repo_name": "HRHR-project/palestine",
"id": "2780b2cb9c6f0d11c9ec10bf981abd3166b399be",
"size": "13174",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dhis-2/dhis-web/dhis-web-api/src/main/java/org/hisp/dhis/webapi/controller/metadata/version/MetadataVersionController.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "349044"
},
{
"name": "Game Maker Language",
"bytes": "20893"
},
{
"name": "HTML",
"bytes": "449001"
},
{
"name": "Java",
"bytes": "16145967"
},
{
"name": "JavaScript",
"bytes": "3960411"
},
{
"name": "Ruby",
"bytes": "1011"
},
{
"name": "Shell",
"bytes": "394"
},
{
"name": "XSLT",
"bytes": "8281"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>proxy</servlet-name>
<servlet-class>org.jivesoftware.openfire.plugin.ofmeet.HttpProxyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>proxy</servlet-name>
<url-pattern>/proxy</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>config</servlet-name>
<servlet-class>org.jivesoftware.openfire.plugin.ofmeet.ConfigServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>config</servlet-name>
<url-pattern>/jitsi-meet/config.js</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>interfaceConfig</servlet-name>
<servlet-class>org.jivesoftware.openfire.plugin.ofmeet.InterfaceConfigServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>interfaceConfig</servlet-name>
<url-pattern>/jitsi-meet/interface_config.js</url-pattern>
</servlet-mapping>
<filter>
<filter-name>WatermarkFilter</filter-name>
<filter-class>org.jivesoftware.openfire.plugin.ofmeet.WatermarkFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>WatermarkFilter</filter-name>
<url-pattern>/jitsi-meet/images/watermark.png</url-pattern>
<url-pattern>/jitsi-meet/images/rightwatermark.png</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<filter>
<filter-name>JitsiMeetRedirectFilter</filter-name>
<filter-class>org.jivesoftware.openfire.plugin.ofmeet.JitsiMeetRedirectFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>JitsiMeetRedirectFilter</filter-name>
<url-pattern>/jitsi-meet/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app> | {
"content_hash": "f16076ba56b23e38195d998a1d49d086",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 109,
"avg_line_length": 31.571428571428573,
"alnum_prop": 0.7390648567119156,
"repo_name": "deleolajide/ofmeet-openfire-plugin",
"id": "3ec8603ec0f530bb470002ffa58c108203e2ae7e",
"size": "1989",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/src/main/webapp/WEB-INF/web.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3385"
},
{
"name": "CSS",
"bytes": "12209"
},
{
"name": "HTML",
"bytes": "34935"
},
{
"name": "Java",
"bytes": "1284412"
},
{
"name": "JavaScript",
"bytes": "3137813"
}
],
"symlink_target": ""
} |
#ifndef _OPENSIM_HOPPERDEVICE_H_
#define _OPENSIM_HOPPERDEVICE_H_
#include "osimExampleComponentsDLL.h"
#include <OpenSim/Simulation/Model/PathActuator.h>
#include <OpenSim/Simulation/Model/Actuator.h>
#include <OpenSim/Simulation/Model/ModelComponent.h>
#include <OpenSim/Simulation/Model/Model.h>
namespace OpenSim {
//------------------------------------------------------------------------------
// HopperDevice is a type of ModelComponent that contains all the parts
// comprising a assistive device model (a PathActuator plus bodies and joints
// for attaching the actuator to the hopper or testbed). Devices are built by
// buildDevice() (see buildDeviceModel.cpp).
// This class is written to be used with Hopper example and is not generic
// to be used elsewhere.
//------------------------------------------------------------------------------
class OSIMEXAMPLECOMPONENTS_API HopperDevice : public ModelComponent {
OpenSim_DECLARE_CONCRETE_OBJECT(HopperDevice, ModelComponent);
public:
// Outputs that report quantities in which we are interested.
// The total length of the device.
OpenSim_DECLARE_OUTPUT(length, double, getLength, SimTK::Stage::Position);
// The lengthening speed of the device.
OpenSim_DECLARE_OUTPUT(speed, double, getSpeed, SimTK::Stage::Velocity);
// The force transmitted by the device.
OpenSim_DECLARE_OUTPUT(tension, double, getTension, SimTK::Stage::Dynamics);
// The power produced(+) or dissipated(-) by the device.
OpenSim_DECLARE_OUTPUT(power, double, getPower, SimTK::Stage::Dynamics);
// The height of the model to which the device is attached.
OpenSim_DECLARE_OUTPUT(height, double, getHeight, SimTK::Stage::Position);
// The center of mass height of the model to which the device is attached.
OpenSim_DECLARE_OUTPUT(com_height, double, getCenterOfMassHeight,
SimTK::Stage::Position);
OpenSim_DECLARE_PROPERTY(actuator_name, std::string,
"Name of the actuator to use for outputs and path coloring.");
HopperDevice() { constructProperty_actuator_name("cableAtoB"); }
// Member functions that access quantities in which we are interested. These
// methods are used by the outputs declared above.
double getLength(const SimTK::State& s) const {
return getComponent<PathActuator>(get_actuator_name()).getLength(s);
}
double getSpeed(const SimTK::State& s) const {
return getComponent<PathActuator>(
get_actuator_name()).getLengtheningSpeed(s);
}
double getTension(const SimTK::State& s) const {
return getComponent<PathActuator>(
get_actuator_name()).computeActuation(s);
}
double getPower(const SimTK::State& s) const {
return getComponent<PathActuator>(get_actuator_name()).getPower(s);
}
double getHeight(const SimTK::State& s) const {
static const std::string hopperHeightCoord =
"/Dennis/jointset/slider/yCoord";
return getModel().getComponent(hopperHeightCoord)
.getOutputValue<double>(s, "value");
}
double getCenterOfMassHeight(const SimTK::State& s) const {
SimTK::Vec3 com_position = getModel().calcMassCenterPosition(s);
return com_position[SimTK::YAxis];
}
protected:
// Change the color of the device's path as its tension changes.
void extendRealizeDynamics(const SimTK::State& s) const override {
const auto& actuator = getComponent<PathActuator>(get_actuator_name());
double level = fmin(1., getTension(s) / actuator.get_optimal_force());
actuator.getGeometryPath().setColor(s, SimTK::Vec3(level, 0.5, 0));
}
}; // end of HopperDevice
} // namespace OpenSim
#endif // _OPENSIM_HOPPERDEVICE_H_
| {
"content_hash": "1e6e3d79ebd1cc1dd872bf7867caf019",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 80,
"avg_line_length": 42.49438202247191,
"alnum_prop": 0.674246430460074,
"repo_name": "opensim-org/opensim-core",
"id": "d63c6f6aa11dacc3f0ea9100479880be46c2b868",
"size": "5622",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "OpenSim/ExampleComponents/HopperDevice.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2463647"
},
{
"name": "C++",
"bytes": "14727896"
},
{
"name": "CMake",
"bytes": "284589"
},
{
"name": "HTML",
"bytes": "230"
},
{
"name": "Java",
"bytes": "81560"
},
{
"name": "MATLAB",
"bytes": "576488"
},
{
"name": "Python",
"bytes": "320084"
},
{
"name": "SWIG",
"bytes": "155144"
},
{
"name": "Shell",
"bytes": "862"
},
{
"name": "Yacc",
"bytes": "19078"
}
],
"symlink_target": ""
} |
#include <aws/email/model/GetCustomVerificationEmailTemplateRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
using namespace Aws::SES::Model;
using namespace Aws::Utils;
GetCustomVerificationEmailTemplateRequest::GetCustomVerificationEmailTemplateRequest() :
m_templateNameHasBeenSet(false)
{
}
Aws::String GetCustomVerificationEmailTemplateRequest::SerializePayload() const
{
Aws::StringStream ss;
ss << "Action=GetCustomVerificationEmailTemplate&";
if(m_templateNameHasBeenSet)
{
ss << "TemplateName=" << StringUtils::URLEncode(m_templateName.c_str()) << "&";
}
ss << "Version=2010-12-01";
return ss.str();
}
void GetCustomVerificationEmailTemplateRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const
{
uri.SetQueryString(SerializePayload());
}
| {
"content_hash": "06a369a17e6dd0d2ecd59c219ca55c58",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 90,
"avg_line_length": 26.15625,
"alnum_prop": 0.7610513739545998,
"repo_name": "jt70471/aws-sdk-cpp",
"id": "a5b7dbc787c5e913dafd6e4d7788b2a7508d7f6e",
"size": "956",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-email/source/model/GetCustomVerificationEmailTemplateRequest.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "13452"
},
{
"name": "C++",
"bytes": "278594037"
},
{
"name": "CMake",
"bytes": "653931"
},
{
"name": "Dockerfile",
"bytes": "5555"
},
{
"name": "HTML",
"bytes": "4471"
},
{
"name": "Java",
"bytes": "302182"
},
{
"name": "Python",
"bytes": "110380"
},
{
"name": "Shell",
"bytes": "4674"
}
],
"symlink_target": ""
} |
<section class="row" data-ng-controller="AuthenticationController">
<h3 class="col-md-12 text-center">SIGN IN</h3>
<div class="col-xs-offset-2 col-xs-8 col-md-offset-5 col-md-2">
<form data-ng-submit="signin()" class="signin form-horizontal" autocomplete="off">
<fieldset>
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username" class="form-control" data-ng-model="credentials.username" placeholder="Username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" class="form-control" data-ng-model="credentials.password" placeholder="Password">
</div>
<div class="text-center form-group">
<button type="submit" class="btn btn-primary">Sign in</button> or
<a href="/#!/signup" style="color:#A5D622">Sign up</a>
</div>
<div class="forgot-password">
<a href="/#!/password/forgot" style="color:#A5D622">Forgot your password?</a>
</div>
<div data-ng-show="error" class="text-center text-danger">
<strong data-ng-bind="error"></strong>
</div>
</fieldset>
</form>
</div>
</section>
| {
"content_hash": "7016f28f9ae331d26bdf0912c55b690f",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 139,
"avg_line_length": 44.77777777777778,
"alnum_prop": 0.6592224979321754,
"repo_name": "th30retical/project_ration",
"id": "d46194f02265fe0b39c8075ab3f43de01b6f0763",
"size": "1209",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/modules/users/views/authentication/signin.client.view.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "668"
},
{
"name": "HTML",
"bytes": "29231"
},
{
"name": "JavaScript",
"bytes": "117104"
},
{
"name": "Shell",
"bytes": "414"
}
],
"symlink_target": ""
} |
namespace TheXDS.MCART.Attributes;
using TheXDS.MCART.Resources;
/// <summary>
/// Define una serie de miembros a implementar por un tipo que obtenga
/// licencias a partir del valor de un atributo.
/// </summary>
public abstract class LicenseAttributeBase : TextAttribute
{
/// <summary>
/// Inicializa una nueva instancia de la clase
/// <see cref="LicenseAttributeBase"/>.
/// </summary>
/// <param name="text">
/// Texto a asociar con el valor de este atributo.
/// </param>
protected LicenseAttributeBase(string text)
: base(text)
{
}
/// <summary>
/// Obtiene una licencia asociada a este atributo.
/// </summary>
/// <param name="context">
/// Objeto del cual se ha extraído este atributo.
/// </param>
/// <returns>
/// Una licencia asociada a este atributo.
/// </returns>
public abstract License GetLicense(object context);
}
| {
"content_hash": "bfed70e259af813e1b3a4271d45bbbdb",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 70,
"avg_line_length": 27.38235294117647,
"alnum_prop": 0.635875402792696,
"repo_name": "TheXDS/MCART",
"id": "fadb86a0f237c4b802102a46b4a84f0a09fbdc21",
"size": "2197",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/MCART/Attributes/LicenseAttributeBase.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "2964307"
},
{
"name": "PowerShell",
"bytes": "720"
},
{
"name": "Vim Snippet",
"bytes": "17002"
}
],
"symlink_target": ""
} |
package org.lbzip2;
public class ManberMyersBWTTest
extends AbstractBWTTest
{
public ManberMyersBWTTest()
{
super( new ManberMyersBWT() );
}
}
| {
"content_hash": "6eeef1a9e1be88ee61e0659270f9fabb",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 38,
"avg_line_length": 15.363636363636363,
"alnum_prop": 0.6686390532544378,
"repo_name": "kjn/lbzip2-java",
"id": "badb1c8e46519126370535248d77bfabc85e5bff",
"size": "773",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/org/lbzip2/ManberMyersBWTTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "268085"
}
],
"symlink_target": ""
} |
package slack
// @NOTE: Blocks are in beta and subject to change.
// More Information: https://api.slack.com/block-kit
// MessageBlockType defines a named string type to define each block type
// as a constant for use within the package.
type MessageBlockType string
const (
MBTSection MessageBlockType = "section"
MBTDivider MessageBlockType = "divider"
MBTImage MessageBlockType = "image"
MBTAction MessageBlockType = "actions"
MBTContext MessageBlockType = "context"
MBTInput MessageBlockType = "input"
)
// Block defines an interface all block types should implement
// to ensure consistency between blocks.
type Block interface {
BlockType() MessageBlockType
}
// Blocks is a convenience struct defined to allow dynamic unmarshalling of
// the "blocks" value in Slack's JSON response, which varies depending on block type
type Blocks struct {
BlockSet []Block `json:"blocks,omitempty"`
}
// BlockAction is the action callback sent when a block is interacted with
type BlockAction struct {
ActionID string `json:"action_id"`
BlockID string `json:"block_id"`
Type actionType `json:"type"`
Text TextBlockObject `json:"text"`
Value string `json:"value"`
ActionTs string `json:"action_ts"`
SelectedOption OptionBlockObject `json:"selected_option"`
SelectedOptions []OptionBlockObject `json:"selected_options"`
SelectedUser string `json:"selected_user"`
SelectedChannel string `json:"selected_channel"`
SelectedConversation string `json:"selected_conversation"`
SelectedDate string `json:"selected_date"`
InitialOption OptionBlockObject `json:"initial_option"`
InitialUser string `json:"initial_user"`
InitialChannel string `json:"initial_channel"`
InitialConversation string `json:"initial_conversation"`
InitialDate string `json:"initial_date"`
}
// actionType returns the type of the action
func (b BlockAction) actionType() actionType {
return b.Type
}
// NewBlockMessage creates a new Message that contains one or more blocks to be displayed
func NewBlockMessage(blocks ...Block) Message {
return Message{
Msg: Msg{
Blocks: Blocks{
BlockSet: blocks,
},
},
}
}
// AddBlockMessage appends a block to the end of the existing list of blocks
func AddBlockMessage(message Message, newBlk Block) Message {
message.Msg.Blocks.BlockSet = append(message.Msg.Blocks.BlockSet, newBlk)
return message
}
| {
"content_hash": "fd1dbeb3ddf7c40f71544427a3367781",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 89,
"avg_line_length": 36.63013698630137,
"alnum_prop": 0.675018698578908,
"repo_name": "178inaba/slack",
"id": "32ff260cc395acfd008a7e543626d82574042f6d",
"size": "2674",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "block.go",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Go",
"bytes": "542633"
},
{
"name": "Makefile",
"bytes": "627"
}
],
"symlink_target": ""
} |
#ifndef __XFS_SUPPORT_RADIX_TREE_H__
#define __XFS_SUPPORT_RADIX_TREE_H__
#define RADIX_TREE_TAGS
struct radix_tree_root {
unsigned int height;
struct radix_tree_node *rnode;
};
#define RADIX_TREE_INIT(mask) { \
.height = 0, \
.rnode = NULL, \
}
#define RADIX_TREE(name, mask) \
struct radix_tree_root name = RADIX_TREE_INIT(mask)
#define INIT_RADIX_TREE(root, mask) \
do { \
(root)->height = 0; \
(root)->rnode = NULL; \
} while (0)
#ifdef RADIX_TREE_TAGS
#define RADIX_TREE_MAX_TAGS 2
#endif
int radix_tree_insert(struct radix_tree_root *, unsigned long, void *);
void *radix_tree_lookup(struct radix_tree_root *, unsigned long);
void **radix_tree_lookup_slot(struct radix_tree_root *, unsigned long);
void *radix_tree_lookup_first(struct radix_tree_root *, unsigned long *);
void *radix_tree_delete(struct radix_tree_root *, unsigned long);
unsigned int
radix_tree_gang_lookup(struct radix_tree_root *root, void **results,
unsigned long first_index, unsigned int max_items);
unsigned int
radix_tree_gang_lookup_ex(struct radix_tree_root *root, void **results,
unsigned long first_index, unsigned long last_index,
unsigned int max_items);
void radix_tree_init(void);
#ifdef RADIX_TREE_TAGS
void *radix_tree_tag_set(struct radix_tree_root *root,
unsigned long index, unsigned int tag);
void *radix_tree_tag_clear(struct radix_tree_root *root,
unsigned long index, unsigned int tag);
int radix_tree_tag_get(struct radix_tree_root *root,
unsigned long index, unsigned int tag);
unsigned int
radix_tree_gang_lookup_tag(struct radix_tree_root *root, void **results,
unsigned long first_index, unsigned int max_items,
unsigned int tag);
int radix_tree_tagged(struct radix_tree_root *root, unsigned int tag);
#endif
#endif /* __XFS_SUPPORT_RADIX_TREE_H__ */
| {
"content_hash": "2621e0ebbde2fcb29e725b4e1a4112c5",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 73,
"avg_line_length": 31.084745762711865,
"alnum_prop": 0.7082878953107961,
"repo_name": "calee0219/Course",
"id": "e16e08d5ff33650088bebf80563d12d6609772e5",
"size": "2612",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "SAP/hw2/partclone-0.2.89/src/xfs/radix-tree.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "2289"
},
{
"name": "Batchfile",
"bytes": "15462"
},
{
"name": "C",
"bytes": "3743223"
},
{
"name": "C++",
"bytes": "5215847"
},
{
"name": "CMake",
"bytes": "58587"
},
{
"name": "CSS",
"bytes": "3594"
},
{
"name": "Coq",
"bytes": "17175"
},
{
"name": "Forth",
"bytes": "476"
},
{
"name": "HTML",
"bytes": "1179412"
},
{
"name": "Jupyter Notebook",
"bytes": "3982275"
},
{
"name": "Lex",
"bytes": "13550"
},
{
"name": "M4",
"bytes": "91072"
},
{
"name": "Makefile",
"bytes": "502535"
},
{
"name": "OpenEdge ABL",
"bytes": "8142"
},
{
"name": "Perl",
"bytes": "4976"
},
{
"name": "Python",
"bytes": "40779"
},
{
"name": "Roff",
"bytes": "48176"
},
{
"name": "Shell",
"bytes": "117131"
},
{
"name": "Tcl",
"bytes": "49089"
},
{
"name": "TeX",
"bytes": "1847"
},
{
"name": "TypeScript",
"bytes": "8296"
},
{
"name": "Verilog",
"bytes": "1306446"
},
{
"name": "XSLT",
"bytes": "1477"
}
],
"symlink_target": ""
} |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S14_D6_T2;
* @section: 14;
* @assertion: Function declaration may be inside of while block ;
*/
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (typeof __func !== "function") {
$ERROR('1: Function declaration may be inside of while block');
}
//
//////////////////////////////////////////////////////////////////////////////
while(1){
break;
function __func(){return BANNER;};
}
BANNER="union jack";
//////////////////////////////////////////////////////////////////////////////
//CHECK#2
if (__func() !== "union jack") {
$ERROR('2: Function declaration may be inside of while block');
}
//
//////////////////////////////////////////////////////////////////////////////
| {
"content_hash": "d022befcdefb0372468b486afab127c7",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 78,
"avg_line_length": 28.193548387096776,
"alnum_prop": 0.41762013729977115,
"repo_name": "luboid/ES5.Script",
"id": "e6e9b8a5efa1546f3e758b02165496911f3170e5",
"size": "874",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "TestScripts/sputniktests/tests/Implementation_Diagnostics/S14_D6_T2.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1728"
},
{
"name": "C#",
"bytes": "825380"
},
{
"name": "CSS",
"bytes": "15950"
},
{
"name": "HTML",
"bytes": "426289"
},
{
"name": "JavaScript",
"bytes": "9567963"
},
{
"name": "Python",
"bytes": "29140"
}
],
"symlink_target": ""
} |
package org.nirvanarico.devtest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
} | {
"content_hash": "fd077e013849662d9c372c8c3c852fa5",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 68,
"avg_line_length": 25.583333333333332,
"alnum_prop": 0.7882736156351792,
"repo_name": "nirvanarico/devtest",
"id": "94cd4d19644e69ae75185f40964a92a618fbb5bd",
"size": "307",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/nirvanarico/devtest/Application.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "6022"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.mq.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/mq-2017-11-27/ListUsers" target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListUsersResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* Required. The unique ID that Amazon MQ generates for the broker.
* </p>
*/
private String brokerId;
/**
* <p>
* Required. The maximum number of ActiveMQ users that can be returned per page (20 by default). This value must be
* an integer from 5 to 100.
* </p>
*/
private Integer maxResults;
/**
* <p>
* The token that specifies the next page of results Amazon MQ should return. To request the first page, leave
* nextToken empty.
* </p>
*/
private String nextToken;
/**
* <p>
* Required. The list of all ActiveMQ usernames for the specified broker. Does not apply to RabbitMQ brokers.
* </p>
*/
private java.util.List<UserSummary> users;
/**
* <p>
* Required. The unique ID that Amazon MQ generates for the broker.
* </p>
*
* @param brokerId
* Required. The unique ID that Amazon MQ generates for the broker.
*/
public void setBrokerId(String brokerId) {
this.brokerId = brokerId;
}
/**
* <p>
* Required. The unique ID that Amazon MQ generates for the broker.
* </p>
*
* @return Required. The unique ID that Amazon MQ generates for the broker.
*/
public String getBrokerId() {
return this.brokerId;
}
/**
* <p>
* Required. The unique ID that Amazon MQ generates for the broker.
* </p>
*
* @param brokerId
* Required. The unique ID that Amazon MQ generates for the broker.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListUsersResult withBrokerId(String brokerId) {
setBrokerId(brokerId);
return this;
}
/**
* <p>
* Required. The maximum number of ActiveMQ users that can be returned per page (20 by default). This value must be
* an integer from 5 to 100.
* </p>
*
* @param maxResults
* Required. The maximum number of ActiveMQ users that can be returned per page (20 by default). This value
* must be an integer from 5 to 100.
*/
public void setMaxResults(Integer maxResults) {
this.maxResults = maxResults;
}
/**
* <p>
* Required. The maximum number of ActiveMQ users that can be returned per page (20 by default). This value must be
* an integer from 5 to 100.
* </p>
*
* @return Required. The maximum number of ActiveMQ users that can be returned per page (20 by default). This value
* must be an integer from 5 to 100.
*/
public Integer getMaxResults() {
return this.maxResults;
}
/**
* <p>
* Required. The maximum number of ActiveMQ users that can be returned per page (20 by default). This value must be
* an integer from 5 to 100.
* </p>
*
* @param maxResults
* Required. The maximum number of ActiveMQ users that can be returned per page (20 by default). This value
* must be an integer from 5 to 100.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListUsersResult withMaxResults(Integer maxResults) {
setMaxResults(maxResults);
return this;
}
/**
* <p>
* The token that specifies the next page of results Amazon MQ should return. To request the first page, leave
* nextToken empty.
* </p>
*
* @param nextToken
* The token that specifies the next page of results Amazon MQ should return. To request the first page,
* leave nextToken empty.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* The token that specifies the next page of results Amazon MQ should return. To request the first page, leave
* nextToken empty.
* </p>
*
* @return The token that specifies the next page of results Amazon MQ should return. To request the first page,
* leave nextToken empty.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* The token that specifies the next page of results Amazon MQ should return. To request the first page, leave
* nextToken empty.
* </p>
*
* @param nextToken
* The token that specifies the next page of results Amazon MQ should return. To request the first page,
* leave nextToken empty.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListUsersResult withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* <p>
* Required. The list of all ActiveMQ usernames for the specified broker. Does not apply to RabbitMQ brokers.
* </p>
*
* @return Required. The list of all ActiveMQ usernames for the specified broker. Does not apply to RabbitMQ
* brokers.
*/
public java.util.List<UserSummary> getUsers() {
return users;
}
/**
* <p>
* Required. The list of all ActiveMQ usernames for the specified broker. Does not apply to RabbitMQ brokers.
* </p>
*
* @param users
* Required. The list of all ActiveMQ usernames for the specified broker. Does not apply to RabbitMQ brokers.
*/
public void setUsers(java.util.Collection<UserSummary> users) {
if (users == null) {
this.users = null;
return;
}
this.users = new java.util.ArrayList<UserSummary>(users);
}
/**
* <p>
* Required. The list of all ActiveMQ usernames for the specified broker. Does not apply to RabbitMQ brokers.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setUsers(java.util.Collection)} or {@link #withUsers(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param users
* Required. The list of all ActiveMQ usernames for the specified broker. Does not apply to RabbitMQ brokers.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListUsersResult withUsers(UserSummary... users) {
if (this.users == null) {
setUsers(new java.util.ArrayList<UserSummary>(users.length));
}
for (UserSummary ele : users) {
this.users.add(ele);
}
return this;
}
/**
* <p>
* Required. The list of all ActiveMQ usernames for the specified broker. Does not apply to RabbitMQ brokers.
* </p>
*
* @param users
* Required. The list of all ActiveMQ usernames for the specified broker. Does not apply to RabbitMQ brokers.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListUsersResult withUsers(java.util.Collection<UserSummary> users) {
setUsers(users);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getBrokerId() != null)
sb.append("BrokerId: ").append(getBrokerId()).append(",");
if (getMaxResults() != null)
sb.append("MaxResults: ").append(getMaxResults()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken()).append(",");
if (getUsers() != null)
sb.append("Users: ").append(getUsers());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListUsersResult == false)
return false;
ListUsersResult other = (ListUsersResult) obj;
if (other.getBrokerId() == null ^ this.getBrokerId() == null)
return false;
if (other.getBrokerId() != null && other.getBrokerId().equals(this.getBrokerId()) == false)
return false;
if (other.getMaxResults() == null ^ this.getMaxResults() == null)
return false;
if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
if (other.getUsers() == null ^ this.getUsers() == null)
return false;
if (other.getUsers() != null && other.getUsers().equals(this.getUsers()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getBrokerId() == null) ? 0 : getBrokerId().hashCode());
hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
hashCode = prime * hashCode + ((getUsers() == null) ? 0 : getUsers().hashCode());
return hashCode;
}
@Override
public ListUsersResult clone() {
try {
return (ListUsersResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| {
"content_hash": "0cc63ded2442eeec1136c813810c8b0f",
"timestamp": "",
"source": "github",
"line_count": 318,
"max_line_length": 142,
"avg_line_length": 33.216981132075475,
"alnum_prop": 0.6049417779040045,
"repo_name": "aws/aws-sdk-java",
"id": "00f51aa0089ed4140abdc4c3db1f526ba3ed0051",
"size": "11143",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-mq/src/main/java/com/amazonaws/services/mq/model/ListUsersResult.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title></title>
<link rel="Stylesheet" href="../css/analysis.css" />
<script type="text/javascript">
function init() {
if (window.location.hash) {
var parentDiv, nodes, i, helpInfo, helpId, helpInfoArr, helpEnvFilter, envContent, hideEnvClass, hideNodes;
helpInfo = window.location.hash.substring(1);
if(helpInfo.indexOf("-")) {
helpInfoArr = helpInfo.split("-");
helpId = helpInfoArr[0];
helpEnvFilter = helpInfoArr[1];
}
else {
helpId = helpInfo;
}
parentDiv = document.getElementById("topics");
nodes = parentDiv.children;
hideEnvClass = (helpEnvFilter === "OnlineOnly"? "PortalOnly": "OnlineOnly");
if(document.getElementsByClassName) {
hideNodes = document.getElementsByClassName(hideEnvClass);
}
else {
hideNodes = document.querySelectorAll(hideEnvClass);
}
for(i=0; i < nodes.length; i++) {
if(nodes[i].id !== helpId) {
nodes[i].style.display ="none";
}
}
for(i=0; i < hideNodes.length; i++) {
hideNodes[i].style.display ="none";
}
}
}
</script>
</head>
<body onload="init()">
<div id="topics">
<div id="toolDescription" class="largesize">
<h2>Encontrar Locais Semelhantes</h2><p/>
<h2><img src="../images/GUID-6262A84E-9087-4E48-930E-E9B89FECC836-web.png" alt="Encontrar Locais Semelhantes"></h2>
<hr/>
<p>Baseado nos critérios especificados, a ferramenta Encontrar Locais Semelhantes mede a semelhança dos locais na sua camada de pesquisa de candidatos para um ou mais locais de referência. Esta ferramenta pode responder perguntas, tais como
<ul>
<li>Qual de suas lojas são mais similares aos seus melhores performers no que se relaciona ao perfil do cliente?
</li>
<li>Baseado nas características de aldeias atingidas pela doença, quais outras aldeias estão em risco alto?
</li>
</ul>
Para responder perguntas, tais como estas, você fornece os locais de referência, os locais de pesquisa de candidatos e os campos representando os critérios que deseja atender. A primeira camada de entrada deve conter sua referência ou locais de referência. Por exemplo, esta pode ser uma camada contendo suas lojas de melhor desempenho ou as aldeias atingidas pela doença. Você então especifica a camada contendo seu local de pesquisa de candidato. Isto pode ser todas as suas lojas ou todas as outras aldeias. Finalmente, você identifica um ou mais campos para utilizar para medir a semelhança. A ferramenta Encontrar Locais Semelhantes irá então classificar todos os locais de pesquisa de candidatos em quão próximo eles correspondem aos seus locais de referência através de todos os campos que você selecionou.
</p>
</div>
<!--Parameter divs for each param-->
<div id="inputLayer">
<div><h2>Escolha a camada contendo os locais de referência</h2></div>
<hr/>
<div>
<p>A camada de ponto, linha ou área contendo os locais de referência para corresponder.
</p>
<p class="OnlineOnly">Além de escolher uma camada do seu mapa, você pode selecionar <b>Escolher Camada de Análise do Atlas em Tempo Real</b> ou <b>Escolher Camada de Análise</b> localizado na parte inferior da lista suspensa. Isto abre uma galeria contendo uma coleção de camadas útil para muitas análises.
</p>
</div>
</div>
<div id="inputLayerSel">
<div><h2>Você pode utilizar todos os locais ou criar uma seleção</h2></div>
<hr/>
<div>
<p>Utilize os botões de seleção para identificar os locais de referência, se necessário. Por exemplo, se a camada de entrada tiver todos os locais—os locais de referência, como também, os locais de pesquisa de candidatos—você precisará utilizar uma das ferramentas de seleção para identificar os locais de referência. Se você criar duas camadas separadas, uma com os locais de referência e outra com todos os locais de pesquisa de candidatos, você não precisará criar uma seleção.
</p>
<p>Se houver mais de um local de referência, um único local será criado calculando a média dos valores para cada um dos campos utilizados para analisar a semelhança.
</p>
</div>
</div>
<div id="searchLayer">
<div><h2>Pesquisar por locais semelhantes em</h2></div>
<hr/>
<div>
<p>Os locais de pesquisa de candidatos nesta camada serão classificados a partir do menos semelhante. A semelhança é baseada em quão próximo cada local corresponde ao local de referência através dos campos que você especifica.
</p>
<p class="OnlineOnly">Além de escolher uma camada do seu mapa, você pode selecionar <b>Escolher Camada de Análise do Atlas em Tempo Real</b> ou <b>Escolher Camada de Análise</b> localizado na parte inferior da lista suspensa. Isto abre uma galeria contendo uma coleção de camadas útil para muitas análises.
</p>
</div>
</div>
<div id="analysisFields">
<div><h2>Similaridade base em</h2></div>
<hr/>
<div>
<p>Os campos que você selecionar serão os critérios utilizados para avaliar a semelhança. Se você selecionar um campo de população e renda, por exemplo, os locais de pesquisa de candidatos com a classificação mais baixa (melhor) serão aqueles que têm população semelhante e valores de renda para seus locais de referência.
</p>
</div>
</div>
<div id="numberOfResults">
<div><h2>Mostre-me</h2></div>
<hr/>
<div>
<p>Você pode consultar todos os locais de pesquisa de candidatos classificados a partir do mais até o menos semelhante ou você pode especificar o número de resultados que você gostaria de consultar.
<ul>
<li> <b>todos os locais a partir do mais até o menos semelhante</b>—todas as feições na camada de pesquisa de candidatos serão incluídas na ordem de classificação na camada resultante
</li>
<li> <b>o número </b> <code>1</code>—você determina quantos dos principais candidatos semelhantes devem ser incluídos na camada resultante.
</li>
</ul>
</p>
</div>
</div>
<div id="OutputName">
<div><h2>Nome da camada resultante</h2></div>
<hr/>
<div>
<p>Forneça um nome para a camada que será criada em <b>Meu Conteúdo</b> e adicionada no mapa. Esta camada resultante conterá os locais de referência e o número de locais de pesquisa de candidatos classificados que você especificou. Se o nome da camada resultante já existir você será avisado para renomeá-lo.
</p>
<p>Ao utilizar a caixa suspensa <b>Salvar resultado em</b>, é possível especificar o nome de uma pasta em <b>Meu Conteúdo</b> onde o resultado será salvo.
</p>
</div>
</div>
</div>
</html>
| {
"content_hash": "34baab62a658712f5e9fa934c8cee3b9",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 933,
"avg_line_length": 69.10655737704919,
"alnum_prop": 0.6336140434112205,
"repo_name": "darklilium/Factigis_2",
"id": "0e7e3e07c1a60bf21068a01b2f8ff028e3ac8089",
"size": "8435",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "arcgis_js_api/library/3.17/3.17compact/esri/dijit/analysis/help/pt-BR/FindSimilarLocations.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "39908"
},
{
"name": "Batchfile",
"bytes": "3178"
},
{
"name": "CSS",
"bytes": "1885995"
},
{
"name": "HTML",
"bytes": "21011190"
},
{
"name": "JavaScript",
"bytes": "1065201"
},
{
"name": "PHP",
"bytes": "76208"
},
{
"name": "Ruby",
"bytes": "1264"
},
{
"name": "Shell",
"bytes": "2052"
},
{
"name": "XSLT",
"bytes": "94766"
}
],
"symlink_target": ""
} |
package com.daviancorp.android.ui.detail;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.view.*;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.*;
import android.widget.AdapterView.AdapterContextMenuInfo;
import com.daviancorp.android.data.classes.WishlistComponent;
import com.daviancorp.android.data.database.DataManager;
import com.daviancorp.android.data.database.WishlistComponentCursor;
import com.daviancorp.android.loader.WishlistComponentListCursorLoader;
import com.daviancorp.android.mh4udatabase.R;
import com.daviancorp.android.ui.dialog.WishlistComponentEditDialogFragment;
public class WishlistDataComponentFragment extends ListFragment implements
LoaderCallbacks<Cursor> {
public static final String EXTRA_COMPONENT_REFRESH =
"com.daviancorp.android.ui.general.wishlist_component_refresh";
private static final String ARG_ID = "ID";
private static final String DIALOG_WISHLIST_COMPONENT_EDIT = "wishlist_component_edit";
private static final int REQUEST_REFRESH = 0;
private static final int REQUEST_EDIT = 1;
private long wishlistId;
private ListView mListView;
private TextView mHeaderTextView, mItemTypeTextView, mQuantityTypeTextView, mExtraTypeTextView;
private ActionMode mActionMode;
private boolean started, fromOtherTab;
public static WishlistDataComponentFragment newInstance(long id) {
Bundle args = new Bundle();
args.putLong(ARG_ID, id);
WishlistDataComponentFragment f = new WishlistDataComponentFragment();
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// Initialize the loader to load the list of runs
getLoaderManager().initLoader(R.id.wishlist_data_component_fragment, getArguments(), this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_wishlist_component_list, container, false);
mListView = (ListView) v.findViewById(android.R.id.list);
mHeaderTextView = (TextView) v.findViewById(R.id.header);
mItemTypeTextView = (TextView) v.findViewById(R.id.item_type);
mQuantityTypeTextView = (TextView) v.findViewById(R.id.quantity_type);
mExtraTypeTextView = (TextView) v.findViewById(R.id.extra_type);
mItemTypeTextView.setText("Item");
mQuantityTypeTextView.setText("Required");
mExtraTypeTextView.setText("Have");
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
// Use floating context menus on Froyo and Gingerbread
registerForContextMenu(mListView);
} else {
// Use contextual action bar on Honeycomb and higher
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (mActionMode != null) {
return false;
}
mActionMode = getActivity().startActionMode(new mActionModeCallback());
mActionMode.setTag(position);
mListView.setItemChecked(position, true);
return true;
}
});
}
return v;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_wishlist_edit, menu);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
MenuItem item_down = menu.findItem(R.id.wishlist_edit);
item_down.setVisible(false);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.wishlist_edit:
if (mListView.getAdapter().getCount() > 0) {
mActionMode = getActivity().startActionMode(new mActionModeCallback());
mActionMode.setTag(0);
mListView.setItemChecked(0, true);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
getActivity().getMenuInflater().inflate(R.menu.context_wishlist_data_component, menu);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) return;
if (requestCode == REQUEST_EDIT) {
if (data.getBooleanExtra(WishlistComponentEditDialogFragment.EXTRA_EDIT, false)) {
updateUI();
}
} else if (requestCode == REQUEST_REFRESH) {
if (data.getBooleanExtra(WishlistDataDetailFragment.EXTRA_DETAIL_REFRESH, false)) {
updateUI();
}
}
}
private void updateUI() {
if (started) {
getLoaderManager().getLoader(R.id.wishlist_data_component_fragment).forceLoad();
WishlistComponentCursorAdapter adapter = (WishlistComponentCursorAdapter) getListAdapter();
adapter.notifyDataSetChanged();
if (!fromOtherTab) {
sendResult(Activity.RESULT_OK, true);
} else {
fromOtherTab = false;
}
}
}
@Override
public void onResume() {
super.onResume();
updateUI();
}
private void sendResult(int resultCode, boolean refresh) {
if (getTargetFragment() == null) {
return;
}
Intent i = new Intent();
i.putExtra(EXTRA_COMPONENT_REFRESH, refresh);
getTargetFragment()
.onActivityResult(getTargetRequestCode(), resultCode, i);
}
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
int position = info.position;
boolean temp = onItemSelected(item, position);
if (temp) {
return true;
} else {
return super.onContextItemSelected(item);
}
}
private boolean onItemSelected(MenuItem item, int position) {
WishlistComponentCursorAdapter adapter = (WishlistComponentCursorAdapter) getListAdapter();
WishlistComponent wishlistComponent = ((WishlistComponentCursor) adapter.getItem(position)).getWishlistComponent();
long id = wishlistComponent.getId();
String name = wishlistComponent.getItem().getName();
FragmentManager fm = getActivity().getSupportFragmentManager();
switch (item.getItemId()) {
case R.id.menu_item_edit_wishlist_data:
WishlistComponentEditDialogFragment dialogEdit = WishlistComponentEditDialogFragment.newInstance(id, name);
dialogEdit.setTargetFragment(WishlistDataComponentFragment.this, REQUEST_EDIT);
dialogEdit.show(fm, DIALOG_WISHLIST_COMPONENT_EDIT);
return true;
default:
return false;
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// The id argument will be the Item ID; CursorAdapter gives us this
// for free
if (mActionMode == null) {
mListView.setItemChecked(position, false);
Intent i = null;
long mId = (long) v.getTag();
String itemtype;
WishlistComponent component;
WishlistComponentCursor mycursor = (WishlistComponentCursor) l.getItemAtPosition(position);
component = mycursor.getWishlistComponent();
itemtype = component.getItem().getType();
// if (mId < S.SECTION_ARMOR) {
// i = new Intent(getActivity(), ItemDetailActivity.class);
// i.putExtra(ItemDetailActivity.EXTRA_ITEM_ID, mId);
// }
// else if (mId < S.SECTION_WEAPON) {
// i = new Intent(getActivity(), ArmorDetailActivity.class);
// i.putExtra(ArmorDetailActivity.EXTRA_ARMOR_ID, mId);
// }
// else {
// i = new Intent(getActivity(), WeaponDetailActivity.class);
// i.putExtra(WeaponDetailActivity.EXTRA_WEAPON_ID, mId);
// }
switch (itemtype) {
case "Weapon":
i = new Intent(getActivity(), WeaponDetailActivity.class);
i.putExtra(WeaponDetailActivity.EXTRA_WEAPON_ID, mId);
break;
case "Armor":
i = new Intent(getActivity(), ArmorDetailActivity.class);
i.putExtra(ArmorDetailActivity.EXTRA_ARMOR_ID, mId);
break;
case "Decoration":
i = new Intent(getActivity(), DecorationDetailActivity.class);
i.putExtra(DecorationDetailActivity.EXTRA_DECORATION_ID, mId);
break;
default:
i = new Intent(getActivity(), ItemDetailActivity.class);
i.putExtra(ItemDetailActivity.EXTRA_ITEM_ID, mId);
}
startActivity(i);
}
// Contextual action bar options
else {
mActionMode.setTag(position);
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// You only ever load the runs, so assume this is the case
wishlistId = -1;
if (args != null) {
wishlistId = args.getLong(ARG_ID);
}
return new WishlistComponentListCursorLoader(getActivity(), wishlistId);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
// Create an adapter to point at this cursor
WishlistComponentCursorAdapter adapter = new WishlistComponentCursorAdapter(
getActivity(), (WishlistComponentCursor) cursor);
setListAdapter(adapter);
started = true;
// Show the total price
int totalPrice = DataManager.get(getActivity()).queryWishlistPrice(wishlistId);
mHeaderTextView.setText("Total Cost: " + totalPrice + "z");
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
// Stop using the cursor (via the adapter)
setListAdapter(null);
}
private static class WishlistComponentCursorAdapter extends CursorAdapter {
private WishlistComponentCursor mWishlistComponentCursor;
public WishlistComponentCursorAdapter(Context context, WishlistComponentCursor cursor) {
super(context, cursor, 0);
mWishlistComponentCursor = cursor;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// Use a layout inflater to get a row view
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return inflater.inflate(R.layout.fragment_wishlist_data_listitem,
parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Get the skill for the current row
WishlistComponent component = mWishlistComponentCursor.getWishlistComponent();
// Set up the text view
LinearLayout root = (LinearLayout) view.findViewById(R.id.listitem);
ImageView itemImageView = (ImageView) view.findViewById(R.id.item_image);
TextView itemTextView = (TextView) view.findViewById(R.id.item);
TextView amtTextView = (TextView) view.findViewById(R.id.amt);
TextView extraTextView = (TextView) view.findViewById(R.id.extra);
long id = component.getItem().getId();
int quantity = component.getQuantity();
int notes = component.getNotes();
String nameText = component.getItem().getName();
String amtText = "" + quantity;
String extraText = "" + notes;
itemTextView.setText(nameText);
amtTextView.setText(amtText);
extraTextView.setText(extraText);
itemTextView.setTextColor(Color.BLACK);
if (notes >= quantity) {
itemTextView.setTextColor(Color.RED);
}
Drawable i = null;
String cellImage = "";
String cellRare = "" + component.getItem().getRarity();
String sub_type = component.getItem().getSubType();
switch (sub_type) {
case "Head":
cellImage = "icons_armor/icons_head/head" + cellRare + ".png";
break;
case "Body":
cellImage = "icons_armor/icons_body/body" + cellRare + ".png";
break;
case "Arms":
cellImage = "icons_armor/icons_body/body" + cellRare + ".png";
break;
case "Waist":
cellImage = "icons_armor/icons_waist/waist" + cellRare + ".png";
break;
case "Legs":
cellImage = "icons_armor/icons_legs/legs" + cellRare + ".png";
break;
case "Great Sword":
cellImage = "icons_weapons/icons_great_sword/great_sword" + cellRare + ".png";
break;
case "Long Sword":
cellImage = "icons_weapons/icons_long_sword/long_sword" + cellRare + ".png";
break;
case "Sword and Shield":
cellImage = "icons_weapons/icons_sword_and_shield/sword_and_shield" + cellRare + ".png";
break;
case "Dual Blades":
cellImage = "icons_weapons/icons_dual_blades/dual_blades" + cellRare + ".png";
break;
case "Hammer":
cellImage = "icons_weapons/icons_hammer/hammer" + cellRare + ".png";
break;
case "Hunting Horn":
cellImage = "icons_weapons/icons_hunting_horn/hunting_horn" + cellRare + ".png";
break;
case "Lance":
cellImage = "icons_weapons/icons_hammer/hammer" + cellRare + ".png";
break;
case "Gunlance":
cellImage = "icons_weapons/icons_gunlance/gunlance" + cellRare + ".png";
break;
case "Switch Axe":
cellImage = "icons_weapons/icons_switch_axe/switch_axe" + cellRare + ".png";
break;
case "Charge Blade":
cellImage = "icons_weapons/icons_charge_blade/charge_blade" + cellRare + ".png";
break;
case "Insect Glaive":
cellImage = "icons_weapons/icons_insect_glaive/insect_glaive" + cellRare + ".png";
break;
case "Light Bowgun":
cellImage = "icons_weapons/icons_light_bowgun/light_bowgun" + cellRare + ".png";
break;
case "Heavy Bowgun":
cellImage = "icons_weapons/icons_heavy_bowgun/heavy_bowgun" + cellRare + ".png";
break;
case "Bow":
cellImage = "icons_weapons/icons_bow/bow" + cellRare + ".png";
break;
default:
cellImage = "icons_items/" + component.getItem().getFileLocation();
}
try {
i = Drawable.createFromStream(
context.getAssets().open(cellImage), null);
} catch (IOException e) {
e.printStackTrace();
}
itemImageView.setImageDrawable(i);
root.setTag(id);
}
}
private class mActionModeCallback implements ActionMode.Callback {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_wishlist_data_component, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
int position = Integer.parseInt(mode.getTag().toString());
mode.finish();
return onItemSelected(item, position);
}
@Override
public void onDestroyActionMode(ActionMode mode) {
for (int i = 0; i < mListView.getCount(); i++) {
mListView.setItemChecked(i, false);
}
mActionMode = null;
}
}
}
| {
"content_hash": "717dfd8b0612643360f82c71d92872f5",
"timestamp": "",
"source": "github",
"line_count": 456,
"max_line_length": 123,
"avg_line_length": 38.99780701754386,
"alnum_prop": 0.5977056739582748,
"repo_name": "zachdayz/MonsterHunter4UDatabase",
"id": "ae33166e92d500c464799cc8c51432b482886b87",
"size": "17783",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/daviancorp/android/ui/detail/WishlistDataComponentFragment.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "148"
},
{
"name": "Java",
"bytes": "1091955"
},
{
"name": "Python",
"bytes": "6563"
}
],
"symlink_target": ""
} |
package com.example.android.basicimmersivemode;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.MenuItem;
import android.view.View;
import com.example.android.common.logger.Log;
public class BasicImmersiveModeFragment extends Fragment {
public static final String TAG = "BasicImmersiveModeFragment";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final View decorView = getActivity().getWindow().getDecorView();
decorView.setOnSystemUiVisibilityChangeListener(
new View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int i) {
int height = decorView.getHeight();
Log.i(TAG, "Current height: " + height);
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.sample_action) {
toggleHideyBar();
}
return true;
}
/**
* Detects and toggles immersive mode.
*/
public void toggleHideyBar() {
// BEGIN_INCLUDE (get_current_ui_flags)
// The UI options currently enabled are represented by a bitfield.
// getSystemUiVisibility() gives us that bitfield.
int uiOptions = getActivity().getWindow().getDecorView().getSystemUiVisibility();
int newUiOptions = uiOptions;
// END_INCLUDE (get_current_ui_flags)
// BEGIN_INCLUDE (toggle_ui_flags)
boolean isImmersiveModeEnabled =
((uiOptions | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) == uiOptions);
if (isImmersiveModeEnabled) {
Log.i(TAG, "Turning immersive mode mode off. ");
} else {
Log.i(TAG, "Turning immersive mode mode on.");
}
// Immersive mode: Backward compatible to KitKat (API 19).
// Note that this flag doesn't do anything by itself, it only augments the behavior
// of HIDE_NAVIGATION and FLAG_FULLSCREEN. For the purposes of this sample
// all three flags are being toggled together.
// This sample uses the "sticky" form of immersive mode, which will let the user swipe
// the bars back in again, but will automatically make them disappear a few seconds later.
newUiOptions ^= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
newUiOptions ^= View.SYSTEM_UI_FLAG_FULLSCREEN;
newUiOptions ^= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
getActivity().getWindow().getDecorView().setSystemUiVisibility(newUiOptions);
//END_INCLUDE (set_ui_flags)
}
}
| {
"content_hash": "ed6ca5f071ba7c8ae2eca52e201c410f",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 98,
"avg_line_length": 39.12162162162162,
"alnum_prop": 0.6459412780656304,
"repo_name": "blois/AndroidSDKCloneMin",
"id": "a675e05bed7ba0900ba98e5e933b302a8a1f931a",
"size": "3500",
"binary": false,
"copies": "15",
"ref": "refs/heads/master",
"path": "sdk/samples/android-20/ui/BasicImmersiveMode/BasicImmersiveModeSample/src/main/java/com/example/android/basicimmersivemode/BasicImmersiveModeFragment.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AppleScript",
"bytes": "0"
},
{
"name": "Assembly",
"bytes": "39964"
},
{
"name": "Awk",
"bytes": "50821"
},
{
"name": "C",
"bytes": "65602656"
},
{
"name": "C++",
"bytes": "32706569"
},
{
"name": "CSS",
"bytes": "301711"
},
{
"name": "Component Pascal",
"bytes": "110"
},
{
"name": "Emacs Lisp",
"bytes": "4737"
},
{
"name": "Groovy",
"bytes": "82931"
},
{
"name": "IDL",
"bytes": "11244"
},
{
"name": "Java",
"bytes": "102765797"
},
{
"name": "JavaScript",
"bytes": "27699"
},
{
"name": "Objective-C",
"bytes": "138688"
},
{
"name": "Perl",
"bytes": "20900909"
},
{
"name": "Prolog",
"bytes": "2842768"
},
{
"name": "Python",
"bytes": "17241370"
},
{
"name": "Rust",
"bytes": "9919"
},
{
"name": "Shell",
"bytes": "806338"
},
{
"name": "Visual Basic",
"bytes": "481"
},
{
"name": "XC",
"bytes": "200153"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using LowercaseRoutesMVC4;
namespace Framework.Web
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRouteLowercase(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
} | {
"content_hash": "5682a240454b6945a005a1aaa10a7486",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 99,
"avg_line_length": 27.193548387096776,
"alnum_prop": 0.5776986951364176,
"repo_name": "sagroskin/Playground",
"id": "14be95edc58c86019301bff9613788f0d24b29d4",
"size": "845",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Framework.Web/App_Start/RouteConfig.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "104"
},
{
"name": "C#",
"bytes": "53003"
},
{
"name": "JavaScript",
"bytes": "816840"
}
],
"symlink_target": ""
} |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Observation.send'
db.add_column('notification_observation', 'send',
self.gf('django.db.models.fields.BooleanField')(default=True),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Observation.send'
db.delete_column('notification_observation', 'send')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'notification.notice': {
'Meta': {'ordering': "['-added']", 'object_name': 'Notice'},
'added': ('django.db.models.fields.DateTimeField', [], {}),
'archived': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'data': ('picklefield.fields.PickledObjectField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'notice_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['notification.NoticeType']"}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'recipient': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'unseen': ('django.db.models.fields.BooleanField', [], {'default': 'True'})
},
'notification.noticesetting': {
'Meta': {'unique_together': "(('user', 'notice_type', 'medium'),)", 'object_name': 'NoticeSetting'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'medium': ('django.db.models.fields.CharField', [], {'max_length': '1'}),
'notice_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['notification.NoticeType']"}),
'send': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'notification.noticetype': {
'Meta': {'object_name': 'NoticeType'},
'default': ('django.db.models.fields.IntegerField', [], {}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'display': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'label': ('django.db.models.fields.CharField', [], {'max_length': '40'})
},
'notification.observation': {
'Meta': {'ordering': "['-added']", 'object_name': 'Observation'},
'added': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'notice_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['notification.NoticeType']"}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'send': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
}
}
complete_apps = ['notification'] | {
"content_hash": "138c7c3721bed5e83b416b306c19626e",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 182,
"avg_line_length": 67.79591836734694,
"alnum_prop": 0.5552378085490668,
"repo_name": "arctelix/django-notification-automated",
"id": "c6692ba46cdb9f13fa36d0e69095a9a9e6aafa84",
"size": "6668",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "notification/migrations/0003_auto__add_field_observation_send.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "108807"
}
],
"symlink_target": ""
} |
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#ifndef DCFMTSYM_H
#define DCFMTSYM_H
#include "unicode/utypes.h"
#include "unicode/uchar.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/uobject.h"
#include "unicode/locid.h"
#include "unicode/numsys.h"
#include "unicode/unum.h"
#include "unicode/unistr.h"
/**
* \file
* \brief C++ API: Symbols for formatting numbers.
*/
U_NAMESPACE_BEGIN
/**
* This class represents the set of symbols needed by DecimalFormat
* to format numbers. DecimalFormat creates for itself an instance of
* DecimalFormatSymbols from its locale data. If you need to change any
* of these symbols, you can get the DecimalFormatSymbols object from
* your DecimalFormat and modify it.
* <P>
* Here are the special characters used in the parts of the
* subpattern, with notes on their usage.
* <pre>
* \code
* Symbol Meaning
* 0 a digit
* # a digit, zero shows as absent
* . placeholder for decimal separator
* , placeholder for grouping separator.
* ; separates formats.
* - default negative prefix.
* % divide by 100 and show as percentage
* X any other characters can be used in the prefix or suffix
* ' used to quote special characters in a prefix or suffix.
* \endcode
* </pre>
* [Notes]
* <P>
* If there is no explicit negative subpattern, - is prefixed to the
* positive form. That is, "0.00" alone is equivalent to "0.00;-0.00".
* <P>
* The grouping separator is commonly used for thousands, but in some
* countries for ten-thousands. The interval is a constant number of
* digits between the grouping characters, such as 100,000,000 or 1,0000,0000.
* If you supply a pattern with multiple grouping characters, the interval
* between the last one and the end of the integer is the one that is
* used. So "#,##,###,####" == "######,####" == "##,####,####".
*/
class U_I18N_API DecimalFormatSymbols : public UObject {
public:
/**
* Constants for specifying a number format symbol.
* @stable ICU 2.0
*/
enum ENumberFormatSymbol {
/** The decimal separator */
kDecimalSeparatorSymbol,
/** The grouping separator */
kGroupingSeparatorSymbol,
/** The pattern separator */
kPatternSeparatorSymbol,
/** The percent sign */
kPercentSymbol,
/** Zero*/
kZeroDigitSymbol,
/** Character representing a digit in the pattern */
kDigitSymbol,
/** The minus sign */
kMinusSignSymbol,
/** The plus sign */
kPlusSignSymbol,
/** The currency symbol */
kCurrencySymbol,
/** The international currency symbol */
kIntlCurrencySymbol,
/** The monetary separator */
kMonetarySeparatorSymbol,
/** The exponential symbol */
kExponentialSymbol,
/** Per mill symbol - replaces kPermillSymbol */
kPerMillSymbol,
/** Escape padding character */
kPadEscapeSymbol,
/** Infinity symbol */
kInfinitySymbol,
/** Nan symbol */
kNaNSymbol,
/** Significant digit symbol
* @stable ICU 3.0 */
kSignificantDigitSymbol,
/** The monetary grouping separator
* @stable ICU 3.6
*/
kMonetaryGroupingSeparatorSymbol,
/** One
* @stable ICU 4.6
*/
kOneDigitSymbol,
/** Two
* @stable ICU 4.6
*/
kTwoDigitSymbol,
/** Three
* @stable ICU 4.6
*/
kThreeDigitSymbol,
/** Four
* @stable ICU 4.6
*/
kFourDigitSymbol,
/** Five
* @stable ICU 4.6
*/
kFiveDigitSymbol,
/** Six
* @stable ICU 4.6
*/
kSixDigitSymbol,
/** Seven
* @stable ICU 4.6
*/
kSevenDigitSymbol,
/** Eight
* @stable ICU 4.6
*/
kEightDigitSymbol,
/** Nine
* @stable ICU 4.6
*/
kNineDigitSymbol,
/** Multiplication sign.
* @stable ICU 54
*/
kExponentMultiplicationSymbol,
/** count symbol constants */
kFormatSymbolCount = kNineDigitSymbol + 2
};
/**
* Create a DecimalFormatSymbols object for the given locale.
*
* @param locale The locale to get symbols for.
* @param status Input/output parameter, set to success or
* failure code upon return.
* @stable ICU 2.0
*/
DecimalFormatSymbols(const Locale& locale, UErrorCode& status);
/**
* Creates a DecimalFormatSymbols instance for the given locale with digits and symbols
* corresponding to the given NumberingSystem.
*
* This constructor behaves equivalently to the normal constructor called with a locale having a
* "numbers=xxxx" keyword specifying the numbering system by name.
*
* In this constructor, the NumberingSystem argument will be used even if the locale has its own
* "numbers=xxxx" keyword.
*
* @param locale The locale to get symbols for.
* @param ns The numbering system.
* @param status Input/output parameter, set to success or
* failure code upon return.
* @stable ICU 60
*/
DecimalFormatSymbols(const Locale& locale, const NumberingSystem& ns, UErrorCode& status);
/**
* Create a DecimalFormatSymbols object for the default locale.
* This constructor will not fail. If the resource file data is
* not available, it will use hard-coded last-resort data and
* set status to U_USING_FALLBACK_ERROR.
*
* @param status Input/output parameter, set to success or
* failure code upon return.
* @stable ICU 2.0
*/
DecimalFormatSymbols(UErrorCode& status);
/**
* Creates a DecimalFormatSymbols object with last-resort data.
* Intended for callers who cache the symbols data and
* set all symbols on the resulting object.
*
* The last-resort symbols are similar to those for the root data,
* except that the grouping separators are empty,
* the NaN symbol is U+FFFD rather than "NaN",
* and the CurrencySpacing patterns are empty.
*
* @param status Input/output parameter, set to success or
* failure code upon return.
* @return last-resort symbols
* @stable ICU 52
*/
static DecimalFormatSymbols* createWithLastResortData(UErrorCode& status);
/**
* Copy constructor.
* @stable ICU 2.0
*/
DecimalFormatSymbols(const DecimalFormatSymbols&);
/**
* Assignment operator.
* @stable ICU 2.0
*/
DecimalFormatSymbols& operator=(const DecimalFormatSymbols&);
/**
* Destructor.
* @stable ICU 2.0
*/
virtual ~DecimalFormatSymbols();
/**
* Return true if another object is semantically equal to this one.
*
* @param other the object to be compared with.
* @return true if another object is semantically equal to this one.
* @stable ICU 2.0
*/
UBool operator==(const DecimalFormatSymbols& other) const;
/**
* Return true if another object is semantically unequal to this one.
*
* @param other the object to be compared with.
* @return true if another object is semantically unequal to this one.
* @stable ICU 2.0
*/
UBool operator!=(const DecimalFormatSymbols& other) const { return !operator==(other); }
/**
* Get one of the format symbols by its enum constant.
* Each symbol is stored as a string so that graphemes
* (characters with modifier letters) can be used.
*
* @param symbol Constant to indicate a number format symbol.
* @return the format symbols by the param 'symbol'
* @stable ICU 2.0
*/
inline UnicodeString getSymbol(ENumberFormatSymbol symbol) const;
/**
* Set one of the format symbols by its enum constant.
* Each symbol is stored as a string so that graphemes
* (characters with modifier letters) can be used.
*
* @param symbol Constant to indicate a number format symbol.
* @param value value of the format symbol
* @param propogateDigits If false, setting the zero digit will not automatically set 1-9.
* The default behavior is to automatically set 1-9 if zero is being set and the value
* it is being set to corresponds to a known Unicode zero digit.
* @stable ICU 2.0
*/
void setSymbol(ENumberFormatSymbol symbol, const UnicodeString &value, const UBool propogateDigits);
/**
* Returns the locale for which this object was constructed.
* @stable ICU 2.6
*/
inline Locale getLocale() const;
/**
* Returns the locale for this object. Two flavors are available:
* valid and actual locale.
* @stable ICU 2.8
*/
Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const;
/**
* Get pattern string for 'CurrencySpacing' that can be applied to
* currency format.
* This API gets the CurrencySpacing data from ResourceBundle. The pattern can
* be empty if there is no data from current locale and its parent locales.
*
* @param type : UNUM_CURRENCY_MATCH, UNUM_CURRENCY_SURROUNDING_MATCH or UNUM_CURRENCY_INSERT.
* @param beforeCurrency : true if the pattern is for before currency symbol.
* false if the pattern is for after currency symbol.
* @param status: Input/output parameter, set to success or
* failure code upon return.
* @return pattern string for currencyMatch, surroundingMatch or spaceInsert.
* Return empty string if there is no data for this locale and its parent
* locales.
* @stable ICU 4.8
*/
const UnicodeString& getPatternForCurrencySpacing(UCurrencySpacing type,
UBool beforeCurrency,
UErrorCode& status) const;
/**
* Set pattern string for 'CurrencySpacing' that can be applied to
* currency format.
*
* @param type : UNUM_CURRENCY_MATCH, UNUM_CURRENCY_SURROUNDING_MATCH or UNUM_CURRENCY_INSERT.
* @param beforeCurrency : true if the pattern is for before currency symbol.
* false if the pattern is for after currency symbol.
* @param pattern : pattern string to override current setting.
* @stable ICU 4.8
*/
void setPatternForCurrencySpacing(UCurrencySpacing type,
UBool beforeCurrency,
const UnicodeString& pattern);
/**
* ICU "poor man's RTTI", returns a UClassID for the actual class.
*
* @stable ICU 2.2
*/
virtual UClassID getDynamicClassID() const;
/**
* ICU "poor man's RTTI", returns a UClassID for this class.
*
* @stable ICU 2.2
*/
static UClassID U_EXPORT2 getStaticClassID();
private:
DecimalFormatSymbols();
/**
* Initializes the symbols from the LocaleElements resource bundle.
* Note: The organization of LocaleElements badly needs to be
* cleaned up.
*
* @param locale The locale to get symbols for.
* @param success Input/output parameter, set to success or
* failure code upon return.
* @param useLastResortData determine if use last resort data
* @param ns The NumberingSystem to use; otherwise, fall
* back to the locale.
*/
void initialize(const Locale& locale, UErrorCode& success,
UBool useLastResortData = FALSE, const NumberingSystem* ns = nullptr);
/**
* Initialize the symbols with default values.
*/
void initialize();
void setCurrencyForSymbols();
public:
#ifndef U_HIDE_INTERNAL_API
/**
* @internal For ICU use only
*/
inline UBool isCustomCurrencySymbol() const {
return fIsCustomCurrencySymbol;
}
/**
* @internal For ICU use only
*/
inline UBool isCustomIntlCurrencySymbol() const {
return fIsCustomIntlCurrencySymbol;
}
/**
* @internal For ICU use only
*/
inline UChar32 getCodePointZero() const {
return fCodePointZero;
}
#endif /* U_HIDE_INTERNAL_API */
/**
* _Internal_ function - more efficient version of getSymbol,
* returning a const reference to one of the symbol strings.
* The returned reference becomes invalid when the symbol is changed
* or when the DecimalFormatSymbols are destroyed.
* Note: moved \#ifndef U_HIDE_INTERNAL_API after this, since this is needed for inline in DecimalFormat
*
* This is not currently stable API, but if you think it should be stable,
* post a comment on the following ticket and the ICU team will take a look:
* http://bugs.icu-project.org/trac/ticket/13580
*
* @param symbol Constant to indicate a number format symbol.
* @return the format symbol by the param 'symbol'
* @internal
*/
inline const UnicodeString& getConstSymbol(ENumberFormatSymbol symbol) const;
#ifndef U_HIDE_INTERNAL_API
/**
* Returns the const UnicodeString reference, like getConstSymbol,
* corresponding to the digit with the given value. This is equivalent
* to accessing the symbol from getConstSymbol with the corresponding
* key, such as kZeroDigitSymbol or kOneDigitSymbol.
*
* This is not currently stable API, but if you think it should be stable,
* post a comment on the following ticket and the ICU team will take a look:
* http://bugs.icu-project.org/trac/ticket/13580
*
* @param digit The digit, an integer between 0 and 9 inclusive.
* If outside the range 0 to 9, the zero digit is returned.
* @return the format symbol for the given digit.
* @internal This API is currently for ICU use only.
*/
inline const UnicodeString& getConstDigitSymbol(int32_t digit) const;
/**
* Returns that pattern stored in currecy info. Internal API for use by NumberFormat API.
* @internal
*/
inline const char16_t* getCurrencyPattern(void) const;
#endif /* U_HIDE_INTERNAL_API */
private:
/**
* Private symbol strings.
* They are either loaded from a resource bundle or otherwise owned.
* setSymbol() clones the symbol string.
* Readonly aliases can only come from a resource bundle, so that we can always
* use fastCopyFrom() with them.
*
* If DecimalFormatSymbols becomes subclassable and the status of fSymbols changes
* from private to protected,
* or when fSymbols can be set any other way that allows them to be readonly aliases
* to non-resource bundle strings,
* then regular UnicodeString copies must be used instead of fastCopyFrom().
*
* @internal
*/
UnicodeString fSymbols[kFormatSymbolCount];
/**
* Non-symbol variable for getConstSymbol(). Always empty.
* @internal
*/
UnicodeString fNoSymbol;
/**
* Dealing with code points is faster than dealing with strings when formatting. Because of
* this, we maintain a value containing the zero code point that is used whenever digitStrings
* represents a sequence of ten code points in order.
*
* <p>If the value stored here is positive, it means that the code point stored in this value
* corresponds to the digitStrings array, and codePointZero can be used instead of the
* digitStrings array for the purposes of efficient formatting; if -1, then digitStrings does
* *not* contain a sequence of code points, and it must be used directly.
*
* <p>It is assumed that codePointZero always shadows the value in digitStrings. codePointZero
* should never be set directly; rather, it should be updated only when digitStrings mutates.
* That is, the flow of information is digitStrings -> codePointZero, not the other way.
*/
UChar32 fCodePointZero;
Locale locale;
char actualLocale[ULOC_FULLNAME_CAPACITY];
char validLocale[ULOC_FULLNAME_CAPACITY];
const char16_t* currPattern;
UnicodeString currencySpcBeforeSym[UNUM_CURRENCY_SPACING_COUNT];
UnicodeString currencySpcAfterSym[UNUM_CURRENCY_SPACING_COUNT];
UBool fIsCustomCurrencySymbol;
UBool fIsCustomIntlCurrencySymbol;
};
// -------------------------------------
inline UnicodeString
DecimalFormatSymbols::getSymbol(ENumberFormatSymbol symbol) const {
const UnicodeString *strPtr;
if(symbol < kFormatSymbolCount) {
strPtr = &fSymbols[symbol];
} else {
strPtr = &fNoSymbol;
}
return *strPtr;
}
// See comments above for this function. Not hidden with #ifdef U_HIDE_INTERNAL_API
inline const UnicodeString &
DecimalFormatSymbols::getConstSymbol(ENumberFormatSymbol symbol) const {
const UnicodeString *strPtr;
if(symbol < kFormatSymbolCount) {
strPtr = &fSymbols[symbol];
} else {
strPtr = &fNoSymbol;
}
return *strPtr;
}
#ifndef U_HIDE_INTERNAL_API
inline const UnicodeString& DecimalFormatSymbols::getConstDigitSymbol(int32_t digit) const {
if (digit < 0 || digit > 9) {
digit = 0;
}
if (digit == 0) {
return fSymbols[kZeroDigitSymbol];
}
ENumberFormatSymbol key = static_cast<ENumberFormatSymbol>(kOneDigitSymbol + digit - 1);
return fSymbols[key];
}
#endif /* U_HIDE_INTERNAL_API */
// -------------------------------------
inline void
DecimalFormatSymbols::setSymbol(ENumberFormatSymbol symbol, const UnicodeString &value, const UBool propogateDigits = TRUE) {
if (symbol == kCurrencySymbol) {
fIsCustomCurrencySymbol = TRUE;
}
else if (symbol == kIntlCurrencySymbol) {
fIsCustomIntlCurrencySymbol = TRUE;
}
if(symbol<kFormatSymbolCount) {
fSymbols[symbol]=value;
}
// If the zero digit is being set to a known zero digit according to Unicode,
// then we automatically set the corresponding 1-9 digits
// Also record updates to fCodePointZero. Be conservative if in doubt.
if (symbol == kZeroDigitSymbol) {
UChar32 sym = value.char32At(0);
if ( propogateDigits && u_charDigitValue(sym) == 0 && value.countChar32() == 1 ) {
fCodePointZero = sym;
for ( int8_t i = 1 ; i<= 9 ; i++ ) {
sym++;
fSymbols[(int)kOneDigitSymbol+i-1] = UnicodeString(sym);
}
} else {
fCodePointZero = -1;
}
} else if (symbol >= kOneDigitSymbol && symbol <= kNineDigitSymbol) {
fCodePointZero = -1;
}
}
// -------------------------------------
inline Locale
DecimalFormatSymbols::getLocale() const {
return locale;
}
#ifndef U_HIDE_INTERNAL_API
inline const char16_t*
DecimalFormatSymbols::getCurrencyPattern() const {
return currPattern;
}
#endif /* U_HIDE_INTERNAL_API */
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif // _DCFMTSYM
//eof
| {
"content_hash": "3eec16337aeaa8877e966616ac53783a",
"timestamp": "",
"source": "github",
"line_count": 564,
"max_line_length": 125,
"avg_line_length": 34.551418439716315,
"alnum_prop": 0.6302663314004208,
"repo_name": "wiltonlazary/arangodb",
"id": "55e3d8a6b3b5ec8436d5f4f3488b493dfe481af5",
"size": "20584",
"binary": false,
"copies": "7",
"ref": "refs/heads/devel",
"path": "3rdParty/V8/v7.9.317/third_party/icu/source/i18n/unicode/dcfmtsym.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "61827"
},
{
"name": "C",
"bytes": "309788"
},
{
"name": "C++",
"bytes": "34723629"
},
{
"name": "CMake",
"bytes": "383904"
},
{
"name": "CSS",
"bytes": "210549"
},
{
"name": "EJS",
"bytes": "231166"
},
{
"name": "HTML",
"bytes": "23114"
},
{
"name": "JavaScript",
"bytes": "33741286"
},
{
"name": "LLVM",
"bytes": "14975"
},
{
"name": "NASL",
"bytes": "269512"
},
{
"name": "NSIS",
"bytes": "47138"
},
{
"name": "Pascal",
"bytes": "75391"
},
{
"name": "Perl",
"bytes": "9811"
},
{
"name": "PowerShell",
"bytes": "7869"
},
{
"name": "Python",
"bytes": "184352"
},
{
"name": "SCSS",
"bytes": "255542"
},
{
"name": "Shell",
"bytes": "134504"
},
{
"name": "TypeScript",
"bytes": "179074"
},
{
"name": "Yacc",
"bytes": "79620"
}
],
"symlink_target": ""
} |
/**
* @class strange.extensions.mediation.impl.Mediator
*
* Base class for all Mediators.
*
* @see strange.extensions.mediation.api.IMediationBinder
*/
using strange.extensions.context.api;
using strange.extensions.mediation.api;
using UnityEngine;
namespace strange.extensions.mediation.impl
{
public class Mediator : MonoBehaviour, IMediator
{
[Inject(ContextKeys.CONTEXT_VIEW)]
public GameObject contextView{get;set;}
public Mediator ()
{
}
/**
* Fires directly after creation and before injection
*/
virtual public void PreRegister()
{
}
/**
* Fires after all injections satisifed.
*
* Override and place your initialization code here.
*/
virtual public void OnRegister()
{
}
/**
* Fires on removal of view.
*
* Override and place your cleanup code here
*/
virtual public void OnRemove()
{
}
/**
* Fires on enabling of view.
*/
virtual public void OnEnabled()
{
}
/**
* Fires on disabling of view.
*/
virtual public void OnDisabled()
{
}
}
}
| {
"content_hash": "c9c49e939fac29a7bcf7731247988247",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 57,
"avg_line_length": 15.835820895522389,
"alnum_prop": 0.6606974552309143,
"repo_name": "miccl/VisualiseR",
"id": "7ee9c6ebaa6e9ef7b5b128bad72e13516a95ecc1",
"size": "1663",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "Assets/Community_Assets/StrangeIoC/scripts/strange/extensions/mediation/impl/Mediator.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "3193371"
},
{
"name": "HLSL",
"bytes": "4329"
},
{
"name": "Python",
"bytes": "6257"
},
{
"name": "ShaderLab",
"bytes": "20057"
},
{
"name": "Smalltalk",
"bytes": "3046"
}
],
"symlink_target": ""
} |
#include "LinkedListAPI.h"
#include "testharness.h"
#include "testcases.h"
#include <string.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/wait.h>
//data management functions for string data
void testDestroy(void *data){
free(data);
}
char * testPrint(void *toBePrinted){
if(toBePrinted!=NULL){
return strdup((char *)toBePrinted);
}
return NULL;
}
int testCompare(const void * one, const void * two)
{
return strcmp((char*)one, (char*)two);
}
char * createData(char * input)
{
char * dup = malloc(sizeof(char)*(strlen(input))+1);
strcpy(dup,input);
return dup;
}
//manual list creation to test insertions separately
List * emptyList()
{
List * list = malloc(sizeof(List));
list->head = NULL;
list->tail = NULL;
list->compare = &testCompare;
list->deleteData = &testDestroy;
list->printData = &testPrint;
return list;
}
List * twoList()
{
List * list = emptyList();
Node * n = malloc(sizeof(Node));
n->data = createData("kilroy");
n->previous = NULL;
n->next = NULL;
list->head = n;
n=malloc(sizeof(Node));
n->data = createData("zappa");
n->next = NULL;
list->head->next = n;
n->previous = list->head;
list->tail = n;
return list;
}
List * threeList()
{
List * list = emptyList();
Node * n1 = malloc(sizeof(Node));
n1->data = createData("kilroy");
Node * n2 = malloc(sizeof(Node));
n2->data = createData("leeroy");
Node * n3 =malloc(sizeof(Node));
n3->data = createData("zappa");
list->head = n1;
list->head->next = n2;
list->head->previous = NULL;
n2->next = n3;
n2->previous = n1;
list->tail = n3;
list->tail->previous = n2;
list->tail->next = NULL;
return list;
}
/*---------------------------------
List creation
--------------------------------*/
/*--------
subtest 1: initial values of List Variables
---------*/
SubTestRec initListTest1(int testNum, int subTest){
List test;
SubTestRec result;
char feedback[300];
test = initializeList(testPrint, testDestroy, testCompare);
// reusing test variable from previous subtest
if(test.head == NULL){
if(test.tail == NULL){
sprintf(feedback, "Subtest %d.%d: head and tail both NULL",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}else{
sprintf(feedback, "Subtest %d.%d: List tail is not NULL on initialization.",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}else if (test.tail != NULL){
sprintf(feedback, "Subtest %d.%d: List head and tail are not NULL on initialization.",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}else{
sprintf(feedback, "Subtest %d.%d: List head is not NULL on initialization.",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
/*--------
subtest 2: function pointer initialization
---------*/
SubTestRec initListTest2(int testNum, int subTest){
List test;
SubTestRec result;
char feedback[300];
test = initializeList(testPrint, testDestroy, testCompare);
if(test.deleteData != testDestroy || test.compare !=testCompare || test.printData !=testPrint){
sprintf(feedback, "Subtest %d.%d: At least one function pointer is incorrectly assigned.",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}else{
sprintf(feedback, "Subtest %d.%d: Function pointers are correctly assigned.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
}
testRec* initListTest(int testNum){
const int numSubs = 2; //doesn't need to be a variable but its a handy place to keep it
int subTest = 1;
char feedback[300];
sprintf(feedback, "Test %d: List Initialization Test", testNum);
testRec* rec = initRec(testNum, numSubs, feedback);
runSubTest(testNum, subTest, rec, &initListTest1);
subTest++;
runSubTest(testNum, subTest, rec, &initListTest2);
return rec;
}
/******************************************************************/
/*---------------------------------
Node creation
--------------------------------*/
/*--------
subtest 1: initializeNode
---------*/
SubTestRec initNodeTest1(int testNum, int subTest){
char * data = createData("test1");
Node* n = initializeNode(data);
char feedback[300];
SubTestRec result;
if(n == NULL){
sprintf(feedback, "Subtest %d.%d: initializeNode() returned null. Cannot continue node creation tests.",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}else{
sprintf(feedback, "Subtest %d.%d: initializeNode() was not null.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
}
/*--------
subtest 2: check node data
---------*/
SubTestRec initNodeTest2(int testNum, int subTest){
char * data = createData("test1");
Node* n = initializeNode(data);
char feedback[300];
SubTestRec result;
if(n->data != NULL)
{
if(testCompare((char *)(n->data),data)==0)
{
sprintf(feedback, "Subtest %d.%d: Node has correct data.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
else
{
sprintf(feedback, "Subtest %d.%d: Node data does not match test data",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
else
{
sprintf(feedback, "Subtest %d.%d: Node data is NULL",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
testRec* initNodeTest(int testNum){
const int numSubs = 2; //doesn't need to be a variable but its a handy place to keep it
int subTest = 1;
char feedback[300];
sprintf(feedback, "Test %d: Node Initialization Test", testNum);
testRec * rec = initRec(testNum, numSubs, feedback);
runSubTest(testNum, subTest, rec, &initNodeTest1);
subTest++;
runSubTest(testNum, subTest, rec, &initNodeTest2);
return rec;
}
/******************************************************************/
/********************* Insert Front and Back **********************/
/*--------
subtest 1: insert Front empty list
---------*/
SubTestRec insertTest1(int testNum, int subTest){
char feedback[300];
SubTestRec result;
List* test = emptyList();
char* data = createData("sally");
insertFront(test, data);
if(test->head->data != NULL &&
testCompare(test->head->data,data) == 0 &&
testCompare(test->tail->data,data) == 0 &&
test->head == test->tail &&
test->head->previous == NULL &&
test->head->next == NULL)
{
sprintf(feedback, "Subtest %d.%d: correctly inserted front on empty list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
else
{
sprintf(feedback, "Subtest %d.%d: Data not correctly inserted at front of list",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
/*--------
subtest 2: insert Front existing List
---------*/
SubTestRec insertTest2(int testNum, int subTest){
char feedback[300];
SubTestRec result;
List* test = twoList();
Node* oldHead = test->head;
char* data = createData("sally");
insertFront(test, data);
printf("butthole\n");
if(test->head->data != NULL && testCompare(test->head->data,data)==0)
// if(test->head->previous->data != NULL && testCompare(test->head->data,data)==0)
{
printf("buttholeeeeee\n");
if(testCompare(test->head->next->data,"kilroy")==0 &&
testCompare(oldHead->previous->data, data) == 0)
{
sprintf(feedback, "Subtest %d.%d: correctly inserted front on populated list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
else
{
sprintf(feedback, "Subtest %d.%d: List order destroyed on insert",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
else
{
sprintf(feedback, "Subtest %d.%d: Data not correctly inserted at front of populated list",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
/*--------
subtest 3: insert Back empty list
---------*/
SubTestRec insertTest3(int testNum, int subTest){
char* data;
char feedback[300];
SubTestRec result;
List* test = emptyList();
data = createData("sally");
insertBack(test, data);
if(test->head->data!=NULL && testCompare(test->tail->data,data)==0)
{
sprintf(feedback, "Subtest %d.%d: correctly inserted back on empty list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
else
{
sprintf(feedback, "Subtest %d.%d: Data not correctly inserted at back of list",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
/*--------
subtest 4: insert Back existing List
---------*/
SubTestRec insertTest4(int testNum, int subTest){
char* data;
char feedback[300];
SubTestRec result;
List* test = twoList();
Node* oldTail = test->tail;
data = createData("sally");
insertBack(test, data);
if(test->tail->data!=NULL && testCompare(test->tail->data,data) == 0)
{
if(testCompare(test->tail->previous->data,"zappa") == 0 &&
testCompare(oldTail->next->data, data) == 0)
{
sprintf(feedback, "Subtest %d.%d: correctly inserted back on populated list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
else
{
sprintf(feedback, "Subtest %d.%d: List order destroyed on insert back",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
else
{
sprintf(feedback, "Subtest %d.%d: Data not correctly inserted at back of populated list",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
/*--------
subtest 5: insert Back NULL list
---------*/
SubTestRec insertTest5(int testNum, int subTest){
char* data;
char feedback[300];
SubTestRec result;
List* test = NULL;
data = createData("sally");
insertBack(test, data);
//if it doesn't segfault
sprintf(feedback, "Subtest %d.%d: insertBack handled NULL list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
/*--------
subtest 6: insert Front NULL list
---------*/
SubTestRec insertTest6(int testNum, int subTest){
char* data;
char feedback[300];
SubTestRec result;
List* test = NULL;
data = createData("sally");
insertFront(test, data);
//if it doesn't segfault
sprintf(feedback, "Subtest %d.%d: insertFront handled NULL list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
testRec* insertTest(int testNum){
const int numSubs = 6; //doesn't need to be a variable but its a handy place to keep it
int subTest = 1;
char feedback[300];
sprintf(feedback, "Test %d: insertFront() and insertBack() test", testNum);
testRec * rec = initRec(testNum, numSubs, feedback);
runSubTest(testNum, subTest, rec, &insertTest1);
subTest++;
runSubTest(testNum, subTest, rec, &insertTest2);
subTest++;
runSubTest(testNum, subTest, rec, &insertTest3);
subTest++;
runSubTest(testNum, subTest, rec, &insertTest4);
subTest++;
runSubTest(testNum, subTest, rec, &insertTest5);
subTest++;
runSubTest(testNum, subTest, rec, &insertTest6);
return rec;
}
/******************************************************************/
/********************** getFront and getBack **********************/
/*--------
subtest 1: getFront populated list
---------*/
SubTestRec getTest1(int testNum, int subTest){
char feedback[300];
SubTestRec result;
List* test = twoList();
char* retrieved = (char *)getFromFront(*test);
if(testCompare(retrieved, "kilroy")==0)
{
sprintf(feedback, "Subtest %d.%d: correctly retrieved data from populated list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
else
{
sprintf(feedback, "Subtest %d.%d: Data not correctly retrieve from populated list",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
return result;
}
/*--------
subtest 2: getBack populated list
---------*/
SubTestRec getTest2(int testNum, int subTest){
char feedback[300];
SubTestRec result;
List* test = twoList();
char* retrieved = (char *)getFromBack(*test);
if(testCompare(retrieved, "zappa")==0)
{
sprintf(feedback, "Subtest %d.%d: correctly retrieved data from populated list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
else
{
sprintf(feedback, "Subtest %d.%d: Data not correctly retrieve from populated list",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
/*--------
subtest 3: getFront empty
---------*/
SubTestRec getTest3(int testNum, int subTest){
char feedback[300];
SubTestRec result;
List* test = emptyList();
char* retrieved = (char *)getFromFront(*test);
if(retrieved == NULL)
{
sprintf(feedback, "Subtest %d.%d: getFront correctly handled empty list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
else
{
sprintf(feedback, "Subtest %d.%d: getFront did not handle empty list correctly",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
/*--------
subtest 4: getBack emptylist
---------*/
SubTestRec getTest4(int testNum, int subTest){
char feedback[300];
SubTestRec result;
List* test = emptyList();
char * ret = (char *)getFromBack(*test);
if(ret == NULL)
{
sprintf(feedback, "Subtest %d.%d: getBack correctly handled empty list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
else
{
sprintf(feedback, "Subtest %d.%d: getBack did not handle empty list correctly",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
testRec* getTest(int testNum){
const int numSubs = 4; //doesn't need to be a variable but its a handy place to keep it
int subTest = 1;
char feedback[300];
sprintf(feedback, "Test %d: getFront() and getBack() test", testNum);
testRec * rec = initRec(testNum, numSubs, feedback);
runSubTest(testNum, subTest, rec, &getTest1);
subTest++;
runSubTest(testNum, subTest, rec, &getTest2);
subTest++;
runSubTest(testNum, subTest, rec, &getTest3);
subTest++;
runSubTest(testNum, subTest, rec, &getTest4);
return rec;
}
/******************************************************************/
/************************* insert Sorted **************************/
/*--------
subtest 1: insert to middle of sorted list.
---------*/
SubTestRec insertSTest1(int testNum, int subTest){
char feedback[300];
SubTestRec result;
List* test = twoList();
char * data = createData("ming");
insertSorted(test, data);
if(testCompare(test->head->next->data, data) == 0)
{
if (testCompare(test->tail->previous->data, data) == 0 &&
test->head->next->previous == test->head && test->tail->previous->next == test->tail){
sprintf(feedback, "Subtest %d.%d: inserted to middle of sorted list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}else{
sprintf(feedback, "Subtest %d.%d: List order destroyed on insert",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
else
{
sprintf(feedback, "Subtest %d.%d: Did not insert sorted to middle of list",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
/*--------
subtest 2: insert to back of sorted list
---------*/
SubTestRec insertSTest2(int testNum, int subTest){
char feedback[300];
SubTestRec result;
List* test = twoList();
char* data = createData("zyrg");
Node* oldTail = test->tail;
insertSorted(test, data);
if(testCompare(test->tail->data, data) == 0)
{
if (testCompare(oldTail->next->data, data) == 0 &&
testCompare(test->tail->previous->data, oldTail->data) == 0 &&
test->tail->next == NULL){
sprintf(feedback, "Subtest %d.%d: inserted to back of sorted list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}else{
sprintf(feedback, "Subtest %d.%d: List order destroyed on insert",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
else
{
sprintf(feedback, "Subtest %d.%d: Did not insert sorted to back of list",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
/*--------
subtest 3: insert to front of sorted list
---------*/
SubTestRec insertSTest3(int testNum, int subTest){
char feedback[300];
SubTestRec result;
List* test = twoList();
Node* oldHead = test->head;
char* data = createData("abbott");
insertSorted(test, data);
if(testCompare((char*)(test->head->data), data) == 0)
{
if (testCompare(oldHead->previous->data, data) == 0 &&
testCompare(test->head->next->data, oldHead->data) == 0 &&
test->head->previous == NULL){
//printf("%s %s\n", (char*)data, (char*)oldHead->previous->data);
sprintf(feedback, "Subtest %d.%d: inserted to front of sorted list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}else{
sprintf(feedback, "Subtest %d.%d: List order destroyed on insert",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
else
{
sprintf(feedback, "Subtest %d.%d: Did not insert sorted to front of list",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
/*--------
subtest 4: insert sorted with empty list
---------*/
SubTestRec insertSTest4(int testNum, int subTest){
char feedback[300];
SubTestRec result;
List* test = emptyList();
char* data = createData("abbott");
insertSorted(test, data);
if(testCompare(test->head->data, data) == 0 &&
testCompare(test->tail->data, data) == 0 &&
test->head->previous == NULL && test->tail->next == NULL &&
test->head == test->tail
)
{
sprintf(feedback, "Subtest %d.%d: inserted single element to sorted list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
else
{
sprintf(feedback, "Subtest %d.%d: insert sorted failed on empty list",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
/*--------
subtest 5: insertSorted NULL list
---------*/
SubTestRec insertSTest5(int testNum, int subTest){
char feedback[300];
SubTestRec result;
List* test = NULL;
char* data = createData("sally");
insertSorted(test, data);
//if it doesn't segfault
sprintf(feedback, "Subtest %d.%d: insertSorted handled NULL list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
testRec * insertSortedTest(int testNum)
{
const int numSubs = 5; //doesn't need to be a variable but its a handy place to keep it
int subTest = 1;
char feedback[300];
sprintf(feedback, "Test %d: insertSorted() test", testNum);
testRec * rec = initRec(testNum, numSubs, feedback);
runSubTest(testNum, subTest, rec, &insertSTest1);
subTest++;
runSubTest(testNum, subTest, rec, &insertSTest2);
subTest++;
runSubTest(testNum, subTest, rec, &insertSTest3);
subTest++;
runSubTest(testNum, subTest, rec, &insertSTest4);
subTest++;
runSubTest(testNum, subTest, rec, &insertSTest5);
return rec;
}
/******************************************************************/
/**************************** Delete ******************************/
/*--------
subtest 1: delete existing data test (front)
---------*/
SubTestRec deleteTest1(int testNum, int subTest){
char feedback[300];
SubTestRec result;
List* test = threeList();
char * retrieved = (char *)deleteDataFromList(test, "kilroy");
if(testCompare(retrieved, "kilroy")==0)
{
if(testCompare(test->head->data, "leeroy") == 0 &&
test->head->previous == NULL)
{
sprintf(feedback, "Subtest %d.%d: correctly retrieved data from the front of a populated list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
else
{
sprintf(feedback, "Subtest %d.%d: did not remove element from list",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
else
{
sprintf(feedback, "Subtest %d.%d: Data not returned after being removed from list",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
/*--------
subtest 2: delete existing data test (back)
---------*/
SubTestRec deleteTest2(int testNum, int subTest){
char feedback[300];
SubTestRec result;
List* test = threeList();
char* retrieved = (char *)deleteDataFromList(test, "zappa");
if(testCompare(retrieved, "zappa")==0)
{
if(testCompare(test->tail->data, "leeroy") == 0 &&
test->tail->next == NULL)
{
sprintf(feedback, "Subtest %d.%d: correctly retrieved data from the back of a populated list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
else
{
sprintf(feedback, "Subtest %d.%d: did not remove element from list",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
else
{
sprintf(feedback, "Subtest %d.%d: Data not returned after being removed from list",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
/*--------
subtest 3: delete existing data test (middle)
---------*/
SubTestRec deleteTest3(int testNum, int subTest){
char feedback[300];
SubTestRec result;
List* test = threeList();
char* retrieved = (char *)deleteDataFromList(test, "leeroy");
if(testCompare(retrieved, "leeroy")==0)
{
if(testCompare(test->tail->data, "zappa") == 0 &&
testCompare(test->head->data, "kilroy") == 0 &&
testCompare(test->head->next->data,"zappa") == 0 &&
testCompare(test->tail->previous->data, "kilroy") == 0)
{
sprintf(feedback, "Subtest %d.%d: correctly retrieved data from the middle of a populated list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
else
{
sprintf(feedback, "Subtest %d.%d: did not remove element from list",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
else
{
sprintf(feedback, "Subtest %d.%d: Data not returned after being removed from list",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
/*--------
subtest 4: delete data that doesn't exist
---------*/
SubTestRec deleteTest4(int testNum, int subTest){
char feedback[300];
SubTestRec result;
List* test;
char* retrieved;
test = twoList();
retrieved = (char *)deleteDataFromList(test, "beth");
if(retrieved == NULL)
{
sprintf(feedback, "Subtest %d.%d: correctly handled invalid data.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
else
{
sprintf(feedback, "Subtest %d.%d: failed on invalid data",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
/*--------
subtest 5: delete null data
---------*/
SubTestRec deleteTest5(int testNum, int subTest){
char feedback[300];
SubTestRec result;
List* test;
char* retrieved;
test = twoList();
retrieved = (char *)deleteDataFromList(test, NULL);
//if did not seg fault
sprintf(feedback, "Subtest %d.%d: correctly handled NULL parameter.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
/*--------
subtest 6: delete populated list
---------*/
SubTestRec deleteTest6(int testNum, int subTest){
char feedback[300];
SubTestRec result;
List* test;
test = twoList();
clearList(test);
if(test->head == NULL && test->tail == NULL)
{
sprintf(feedback, "Subtest %d.%d: clearList functioned correctly.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
else
{
sprintf(feedback, "Subtest %d.%d: did not correctly clear List",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
/*--------
subtest 7: delete empty list
---------*/
SubTestRec deleteTest7(int testNum, int subTest){
char feedback[300];
SubTestRec result;
List* test;
test = emptyList();
clearList(test);
if(test->head == NULL && test->tail == NULL)
{
sprintf(feedback, "Subtest %d.%d: correctly handled empty list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
else
{
sprintf(feedback, "Subtest %d.%d: failed on empty list",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
/*--------
subtest 8: delete NULL list
---------*/
SubTestRec deleteTest8(int testNum, int subTest){
char feedback[300];
SubTestRec result;
List* test;
test = NULL;
clearList(test);
if(test == NULL)
{
sprintf(feedback, "Subtest %d.%d: correctly handled NULL list.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
return result;
}
else
{
sprintf(feedback, "Subtest %d.%d: failed on NULL list",testNum,subTest);
result = createSubResult(FAIL, feedback);
return result;
}
}
testRec* deleteTest(int testNum)
{
const int numSubs = 8; //doesn't need to be a variable but its a handy place to keep it
int subTest = 1;
char feedback[300];
sprintf(feedback, "Test %d: insertSorted() test", testNum);
testRec * rec = initRec(testNum, numSubs, feedback);
runSubTest(testNum, subTest, rec, &deleteTest1);
subTest++;
runSubTest(testNum, subTest, rec, &deleteTest2);
subTest++;
runSubTest(testNum, subTest, rec, &deleteTest3);
subTest++;
runSubTest(testNum, subTest, rec, &deleteTest4);
subTest++;
runSubTest(testNum, subTest, rec, &deleteTest5);
subTest++;
runSubTest(testNum, subTest, rec, &deleteTest6);
subTest++;
runSubTest(testNum, subTest, rec, &deleteTest7);
subTest++;
runSubTest(testNum, subTest, rec, &deleteTest8);
return rec;
}
/******************************************************************/
/***************************** Print ******************************/
/*--------
subtest 1: print forwards
---------*/
SubTestRec printTest1(int testNum, int subTest){
char feedback[300];
SubTestRec result;
char * one = NULL;
char * two = NULL;
char * printed;
List * test = twoList();
printed = toString(*test);
one = strstr(printed, "k");
two = strstr(printed, "z");
if(one != NULL && two != NULL)
{
if((int)(one-printed) < (int)(two-printed))
{
sprintf(feedback, "Subtest %d.%d: List printed forwards in correct order.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
}
else
{
sprintf(feedback, "Subtest %d.%d: List did not print in correct order.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
}
}
else
{
sprintf(feedback, "Subtest %d.%d: List did not print correctly",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
}
free(printed);
return result;
}
/*--------
subtest 2: print empty List
---------*/
SubTestRec printTest2(int testNum, int subTest){
char feedback[300];
SubTestRec result;
char* printed;
List* test = emptyList();
printed = feedback; //to get a value other than NULL
printed = toString(*test);
if(printed == NULL || printed != NULL )
{
sprintf(feedback, "Subtest %d.%d: Empty list handled correctly.",testNum,subTest);
result = createSubResult(SUCCESS, feedback);
}
else
{
sprintf(feedback, "Subtest %d.%d: List did not handle empty list correctly",testNum,subTest);
result = createSubResult(FAIL, feedback);
}
return result;
}
testRec * printTest(int testNum)
{
const int numSubs = 2; //doesn't need to be a variable but its a handy place to keep it
int subTest = 1;
char feedback[300];
sprintf(feedback, "Test %d: print test", testNum);
testRec * rec = initRec(testNum, numSubs, feedback);
runSubTest(testNum, subTest, rec, &printTest1);
subTest++;
runSubTest(testNum, subTest, rec, &printTest2);
return rec;
}
| {
"content_hash": "67f3ee27017cadf16ce3aadc161ac981",
"timestamp": "",
"source": "github",
"line_count": 1046,
"max_line_length": 130,
"avg_line_length": 29.496175908221797,
"alnum_prop": 0.5905422487278384,
"repo_name": "dominickhera/PosaRepo",
"id": "f98804da0d7c0c18514b8963022bb825d3b653b0",
"size": "30853",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "year3/sem1/cis2750/A1TestHarness/src/testCases.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "8043"
},
{
"name": "C",
"bytes": "1727439"
},
{
"name": "C++",
"bytes": "75654"
},
{
"name": "COBOL",
"bytes": "4854"
},
{
"name": "CSS",
"bytes": "259311"
},
{
"name": "Fortran",
"bytes": "16927"
},
{
"name": "HTML",
"bytes": "931603"
},
{
"name": "JavaScript",
"bytes": "322808"
},
{
"name": "Makefile",
"bytes": "21000"
},
{
"name": "Perl",
"bytes": "22818"
},
{
"name": "Python",
"bytes": "55993"
},
{
"name": "R",
"bytes": "10512"
},
{
"name": "Shell",
"bytes": "2231"
}
],
"symlink_target": ""
} |
module Ebay # :nodoc:
module Types # :nodoc:
# == Attributes
# text_node :charity_name, 'CharityName', :optional => true
# numeric_node :charity_number, 'CharityNumber', :optional => true
# numeric_node :donation_percent, 'DonationPercent', :optional => true
# text_node :charity_id, 'CharityID', :optional => true
# text_node :mission, 'Mission', :optional => true
# text_node :logo_url, 'LogoURL', :optional => true
# text_node :status, 'Status', :optional => true
# boolean_node :charity_listing, 'CharityListing', 'true', 'false', :optional => true
class Charity
include XML::Mapping
include Initializer
root_element_name 'Charity'
text_node :charity_name, 'CharityName', :optional => true
numeric_node :charity_number, 'CharityNumber', :optional => true
numeric_node :donation_percent, 'DonationPercent', :optional => true
text_node :charity_id, 'CharityID', :optional => true
text_node :mission, 'Mission', :optional => true
text_node :logo_url, 'LogoURL', :optional => true
text_node :status, 'Status', :optional => true
boolean_node :charity_listing, 'CharityListing', 'true', 'false', :optional => true
end
end
end
| {
"content_hash": "0e1564ad39dad266cede1fac7705e27a",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 90,
"avg_line_length": 44.57142857142857,
"alnum_prop": 0.6434294871794872,
"repo_name": "joshm1/ebay",
"id": "e64527330d439d24613495fe4a4a8f832d855171",
"size": "1249",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "lib/ebay/types/charity.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1809"
},
{
"name": "Ruby",
"bytes": "1279206"
}
],
"symlink_target": ""
} |
.class final Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;
.super Ljava/lang/Object;
.source "AppWidgetServiceImpl.java"
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Lcom/android/server/appwidget/AppWidgetServiceImpl;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x12
name = "BackupRestoreController"
.end annotation
.annotation system Ldalvik/annotation/MemberClasses;
value = {
Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;
}
.end annotation
# static fields
.field private static final DEBUG:Z = true
.field private static final TAG:Ljava/lang/String; = "BackupRestoreController"
.field private static final WIDGET_STATE_VERSION:I = 0x2
# instance fields
.field private final mPrunedApps:Ljava/util/HashSet;
.annotation system Ldalvik/annotation/Signature;
value = {
"Ljava/util/HashSet",
"<",
"Ljava/lang/String;",
">;"
}
.end annotation
.end field
.field private final mUpdatesByHost:Ljava/util/HashMap;
.annotation system Ldalvik/annotation/Signature;
value = {
"Ljava/util/HashMap",
"<",
"Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;",
"Ljava/util/ArrayList",
"<",
"Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;",
">;>;"
}
.end annotation
.end field
.field private final mUpdatesByProvider:Ljava/util/HashMap;
.annotation system Ldalvik/annotation/Signature;
value = {
"Ljava/util/HashMap",
"<",
"Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;",
"Ljava/util/ArrayList",
"<",
"Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;",
">;>;"
}
.end annotation
.end field
.field final synthetic this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
# direct methods
.method private constructor <init>(Lcom/android/server/appwidget/AppWidgetServiceImpl;)V
.locals 1
.param p1, "this$0" # Lcom/android/server/appwidget/AppWidgetServiceImpl;
.prologue
.line 3584
iput-object p1, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
.line 3596
new-instance v0, Ljava/util/HashSet;
invoke-direct {v0}, Ljava/util/HashSet;-><init>()V
iput-object v0, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->mPrunedApps:Ljava/util/HashSet;
.line 3599
new-instance v0, Ljava/util/HashMap;
invoke-direct {v0}, Ljava/util/HashMap;-><init>()V
.line 3598
iput-object v0, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->mUpdatesByProvider:Ljava/util/HashMap;
.line 3601
new-instance v0, Ljava/util/HashMap;
invoke-direct {v0}, Ljava/util/HashMap;-><init>()V
.line 3600
iput-object v0, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->mUpdatesByHost:Ljava/util/HashMap;
.line 3584
return-void
.end method
.method synthetic constructor <init>(Lcom/android/server/appwidget/AppWidgetServiceImpl;Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;)V
.locals 0
.param p1, "this$0" # Lcom/android/server/appwidget/AppWidgetServiceImpl;
.prologue
invoke-direct {p0, p1}, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;-><init>(Lcom/android/server/appwidget/AppWidgetServiceImpl;)V
return-void
.end method
.method private alreadyStashed(Ljava/util/ArrayList;II)Z
.locals 4
.param p2, "oldId" # I
.param p3, "newId" # I
.annotation system Ldalvik/annotation/Signature;
value = {
"(",
"Ljava/util/ArrayList",
"<",
"Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;",
">;II)Z"
}
.end annotation
.prologue
.line 4038
.local p1, "stash":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;"
invoke-virtual {p1}, Ljava/util/ArrayList;->size()I
move-result v0
.line 4039
.local v0, "N":I
const/4 v1, 0x0
.local v1, "i":I
:goto_0
if-ge v1, v0, :cond_1
.line 4040
invoke-virtual {p1, v1}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;
move-result-object v2
check-cast v2, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;
.line 4041
.local v2, "r":Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;
iget v3, v2, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;->oldId:I
if-ne v3, p2, :cond_0
iget v3, v2, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;->newId:I
if-ne v3, p3, :cond_0
.line 4042
const/4 v3, 0x1
return v3
.line 4039
:cond_0
add-int/lit8 v1, v1, 0x1
goto :goto_0
.line 4045
.end local v2 # "r":Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;
:cond_1
const/4 v3, 0x0
return v3
.end method
.method private countPendingUpdates(Ljava/util/ArrayList;)I
.locals 5
.annotation system Ldalvik/annotation/Signature;
value = {
"(",
"Ljava/util/ArrayList",
"<",
"Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;",
">;)I"
}
.end annotation
.prologue
.line 4153
.local p1, "updates":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;"
const/4 v2, 0x0
.line 4154
.local v2, "pending":I
invoke-virtual {p1}, Ljava/util/ArrayList;->size()I
move-result v0
.line 4155
.local v0, "N":I
const/4 v1, 0x0
.local v1, "i":I
:goto_0
if-ge v1, v0, :cond_1
.line 4156
invoke-virtual {p1, v1}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;
move-result-object v3
check-cast v3, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;
.line 4157
.local v3, "r":Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;
iget-boolean v4, v3, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;->notified:Z
if-nez v4, :cond_0
.line 4158
add-int/lit8 v2, v2, 0x1
.line 4155
:cond_0
add-int/lit8 v1, v1, 0x1
goto :goto_0
.line 4161
.end local v3 # "r":Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;
:cond_1
return v2
.end method
.method private findProviderLocked(Landroid/content/ComponentName;I)Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.locals 4
.param p1, "componentName" # Landroid/content/ComponentName;
.param p2, "userId" # I
.prologue
.line 3958
iget-object v3, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v3}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get7(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/util/ArrayList;
move-result-object v3
invoke-virtual {v3}, Ljava/util/ArrayList;->size()I
move-result v2
.line 3959
.local v2, "providerCount":I
const/4 v0, 0x0
.local v0, "i":I
:goto_0
if-ge v0, v2, :cond_1
.line 3960
iget-object v3, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v3}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get7(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/util/ArrayList;
move-result-object v3
invoke-virtual {v3, v0}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;
move-result-object v1
check-cast v1, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.line 3961
.local v1, "provider":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
invoke-virtual {v1}, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->getUserId()I
move-result v3
if-ne v3, p2, :cond_0
.line 3962
iget-object v3, v1, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->id:Lcom/android/server/appwidget/AppWidgetServiceImpl$ProviderId;
iget-object v3, v3, Lcom/android/server/appwidget/AppWidgetServiceImpl$ProviderId;->componentName:Landroid/content/ComponentName;
invoke-virtual {v3, p1}, Landroid/content/ComponentName;->equals(Ljava/lang/Object;)Z
move-result v3
.line 3961
if-eqz v3, :cond_0
.line 3963
return-object v1
.line 3959
:cond_0
add-int/lit8 v0, v0, 0x1
goto :goto_0
.line 3966
.end local v1 # "provider":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
:cond_1
const/4 v3, 0x0
return-object v3
.end method
.method private findRestoredWidgetLocked(ILcom/android/server/appwidget/AppWidgetServiceImpl$Host;Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;)Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
.locals 7
.param p1, "restoredId" # I
.param p2, "host" # Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
.param p3, "p" # Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.prologue
const/4 v6, 0x0
.line 3971
const-string/jumbo v3, "BackupRestoreController"
new-instance v4, Ljava/lang/StringBuilder;
invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v5, "Find restored widget: id="
invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v4
invoke-virtual {v4, p1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v4
.line 3972
const-string/jumbo v5, " host="
.line 3971
invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v4
invoke-virtual {v4, p2}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;
move-result-object v4
.line 3972
const-string/jumbo v5, " provider="
.line 3971
invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v4
invoke-virtual {v4, p3}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;
move-result-object v4
invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v4
invoke-static {v3, v4}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
.line 3975
if-eqz p3, :cond_0
if-nez p2, :cond_1
.line 3976
:cond_0
return-object v6
.line 3979
:cond_1
iget-object v3, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v3}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get10(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/util/ArrayList;
move-result-object v3
invoke-virtual {v3}, Ljava/util/ArrayList;->size()I
move-result v0
.line 3980
.local v0, "N":I
const/4 v1, 0x0
.local v1, "i":I
:goto_0
if-ge v1, v0, :cond_3
.line 3981
iget-object v3, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v3}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get10(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/util/ArrayList;
move-result-object v3
invoke-virtual {v3, v1}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;
move-result-object v2
check-cast v2, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
.line 3982
.local v2, "widget":Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
iget v3, v2, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->restoredId:I
if-ne v3, p1, :cond_2
.line 3983
iget-object v3, v2, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->host:Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
iget-object v3, v3, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;->id:Lcom/android/server/appwidget/AppWidgetServiceImpl$HostId;
iget-object v4, p2, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;->id:Lcom/android/server/appwidget/AppWidgetServiceImpl$HostId;
invoke-virtual {v3, v4}, Lcom/android/server/appwidget/AppWidgetServiceImpl$HostId;->equals(Ljava/lang/Object;)Z
move-result v3
.line 3982
if-eqz v3, :cond_2
.line 3984
iget-object v3, v2, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->provider:Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
iget-object v3, v3, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->id:Lcom/android/server/appwidget/AppWidgetServiceImpl$ProviderId;
iget-object v4, p3, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->id:Lcom/android/server/appwidget/AppWidgetServiceImpl$ProviderId;
invoke-virtual {v3, v4}, Lcom/android/server/appwidget/AppWidgetServiceImpl$ProviderId;->equals(Ljava/lang/Object;)Z
move-result v3
.line 3982
if-eqz v3, :cond_2
.line 3986
const-string/jumbo v3, "BackupRestoreController"
new-instance v4, Ljava/lang/StringBuilder;
invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v5, " Found at "
invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v4
invoke-virtual {v4, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v4
const-string/jumbo v5, " : "
invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v4
invoke-virtual {v4, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;
move-result-object v4
invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v4
invoke-static {v3, v4}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
.line 3988
return-object v2
.line 3980
:cond_2
add-int/lit8 v1, v1, 0x1
goto :goto_0
.line 3991
.end local v2 # "widget":Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
:cond_3
return-object v6
.end method
.method private isProviderAndHostInUser(Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;I)Z
.locals 3
.param p1, "widget" # Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
.param p2, "userId" # I
.prologue
const/4 v0, 0x1
const/4 v1, 0x0
.line 4118
iget-object v2, p1, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->host:Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
invoke-virtual {v2}, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;->getUserId()I
move-result v2
if-ne v2, p2, :cond_2
iget-object v2, p1, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->provider:Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
if-eqz v2, :cond_0
.line 4119
iget-object v2, p1, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->provider:Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
invoke-virtual {v2}, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->getUserId()I
move-result v2
if-ne v2, p2, :cond_1
.line 4118
:cond_0
:goto_0
return v0
:cond_1
move v0, v1
.line 4119
goto :goto_0
:cond_2
move v0, v1
.line 4118
goto :goto_0
.end method
.method private packageNeedsWidgetBackupLocked(Ljava/lang/String;I)Z
.locals 6
.param p1, "packageName" # Ljava/lang/String;
.param p2, "userId" # I
.prologue
const/4 v5, 0x1
.line 3995
iget-object v4, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v4}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get10(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/util/ArrayList;
move-result-object v4
invoke-virtual {v4}, Ljava/util/ArrayList;->size()I
move-result v0
.line 3996
.local v0, "N":I
const/4 v1, 0x0
.local v1, "i":I
:goto_0
if-ge v1, v0, :cond_3
.line 3997
iget-object v4, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v4}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get10(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/util/ArrayList;
move-result-object v4
invoke-virtual {v4, v1}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;
move-result-object v3
check-cast v3, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
.line 4000
.local v3, "widget":Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
invoke-direct {p0, v3, p2}, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->isProviderAndHostInUser(Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;I)Z
move-result v4
if-nez v4, :cond_1
.line 3996
:cond_0
add-int/lit8 v1, v1, 0x1
goto :goto_0
.line 4004
:cond_1
iget-object v4, v3, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->host:Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
invoke-virtual {v4, p1, p2}, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;->isInPackageForUser(Ljava/lang/String;I)Z
move-result v4
if-eqz v4, :cond_2
.line 4006
return v5
.line 4009
:cond_2
iget-object v2, v3, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->provider:Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.line 4010
.local v2, "provider":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
if-eqz v2, :cond_0
invoke-virtual {v2, p1, p2}, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->isInPackageForUser(Ljava/lang/String;I)Z
move-result v4
if-eqz v4, :cond_0
.line 4012
return v5
.line 4015
.end local v2 # "provider":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.end local v3 # "widget":Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
:cond_3
const/4 v4, 0x0
return v4
.end method
.method private parseWidgetIdOptions(Lorg/xmlpull/v1/XmlPullParser;)Landroid/os/Bundle;
.locals 10
.param p1, "parser" # Lorg/xmlpull/v1/XmlPullParser;
.prologue
const/16 v9, 0x10
const/4 v8, 0x0
.line 4123
new-instance v5, Landroid/os/Bundle;
invoke-direct {v5}, Landroid/os/Bundle;-><init>()V
.line 4124
.local v5, "options":Landroid/os/Bundle;
const-string/jumbo v6, "min_width"
invoke-interface {p1, v8, v6}, Lorg/xmlpull/v1/XmlPullParser;->getAttributeValue(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
move-result-object v4
.line 4125
.local v4, "minWidthString":Ljava/lang/String;
if-eqz v4, :cond_0
.line 4126
const-string/jumbo v6, "appWidgetMinWidth"
.line 4127
invoke-static {v4, v9}, Ljava/lang/Integer;->parseInt(Ljava/lang/String;I)I
move-result v7
.line 4126
invoke-virtual {v5, v6, v7}, Landroid/os/Bundle;->putInt(Ljava/lang/String;I)V
.line 4129
:cond_0
const-string/jumbo v6, "min_height"
invoke-interface {p1, v8, v6}, Lorg/xmlpull/v1/XmlPullParser;->getAttributeValue(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
move-result-object v3
.line 4130
.local v3, "minHeightString":Ljava/lang/String;
if-eqz v3, :cond_1
.line 4131
const-string/jumbo v6, "appWidgetMinHeight"
.line 4132
invoke-static {v3, v9}, Ljava/lang/Integer;->parseInt(Ljava/lang/String;I)I
move-result v7
.line 4131
invoke-virtual {v5, v6, v7}, Landroid/os/Bundle;->putInt(Ljava/lang/String;I)V
.line 4134
:cond_1
const-string/jumbo v6, "max_width"
invoke-interface {p1, v8, v6}, Lorg/xmlpull/v1/XmlPullParser;->getAttributeValue(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
move-result-object v2
.line 4135
.local v2, "maxWidthString":Ljava/lang/String;
if-eqz v2, :cond_2
.line 4136
const-string/jumbo v6, "appWidgetMaxWidth"
.line 4137
invoke-static {v2, v9}, Ljava/lang/Integer;->parseInt(Ljava/lang/String;I)I
move-result v7
.line 4136
invoke-virtual {v5, v6, v7}, Landroid/os/Bundle;->putInt(Ljava/lang/String;I)V
.line 4139
:cond_2
const-string/jumbo v6, "max_height"
invoke-interface {p1, v8, v6}, Lorg/xmlpull/v1/XmlPullParser;->getAttributeValue(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
move-result-object v1
.line 4140
.local v1, "maxHeightString":Ljava/lang/String;
if-eqz v1, :cond_3
.line 4141
const-string/jumbo v6, "appWidgetMaxHeight"
.line 4142
invoke-static {v1, v9}, Ljava/lang/Integer;->parseInt(Ljava/lang/String;I)I
move-result v7
.line 4141
invoke-virtual {v5, v6, v7}, Landroid/os/Bundle;->putInt(Ljava/lang/String;I)V
.line 4144
:cond_3
const-string/jumbo v6, "host_category"
invoke-interface {p1, v8, v6}, Lorg/xmlpull/v1/XmlPullParser;->getAttributeValue(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
move-result-object v0
.line 4145
.local v0, "categoryString":Ljava/lang/String;
if-eqz v0, :cond_4
.line 4146
const-string/jumbo v6, "appWidgetCategory"
.line 4147
invoke-static {v0, v9}, Ljava/lang/Integer;->parseInt(Ljava/lang/String;I)I
move-result v7
.line 4146
invoke-virtual {v5, v6, v7}, Landroid/os/Bundle;->putInt(Ljava/lang/String;I)V
.line 4149
:cond_4
return-object v5
.end method
.method private pruneWidgetStateLocked(Ljava/lang/String;I)V
.locals 7
.param p1, "pkg" # Ljava/lang/String;
.param p2, "userId" # I
.prologue
.line 4087
iget-object v4, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->mPrunedApps:Ljava/util/HashSet;
invoke-virtual {v4, p1}, Ljava/util/HashSet;->contains(Ljava/lang/Object;)Z
move-result v4
if-nez v4, :cond_3
.line 4089
const-string/jumbo v4, "BackupRestoreController"
new-instance v5, Ljava/lang/StringBuilder;
invoke-direct {v5}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v6, "pruning widget state for restoring package "
invoke-virtual {v5, v6}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v5
invoke-virtual {v5, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v5
invoke-virtual {v5}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v5
invoke-static {v4, v5}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
.line 4091
iget-object v4, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v4}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get10(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/util/ArrayList;
move-result-object v4
invoke-virtual {v4}, Ljava/util/ArrayList;->size()I
move-result v4
add-int/lit8 v1, v4, -0x1
.local v1, "i":I
:goto_0
if-ltz v1, :cond_2
.line 4092
iget-object v4, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v4}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get10(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/util/ArrayList;
move-result-object v4
invoke-virtual {v4, v1}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;
move-result-object v3
check-cast v3, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
.line 4094
.local v3, "widget":Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
iget-object v0, v3, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->host:Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
.line 4095
.local v0, "host":Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
iget-object v2, v3, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->provider:Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.line 4097
.local v2, "provider":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
invoke-static {v0, p1, p2}, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;->-wrap0(Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;Ljava/lang/String;I)Z
move-result v4
if-nez v4, :cond_0
.line 4098
if-eqz v2, :cond_1
invoke-virtual {v2, p1, p2}, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->isInPackageForUser(Ljava/lang/String;I)Z
move-result v4
.line 4097
if-eqz v4, :cond_1
.line 4102
:cond_0
iget-object v4, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;->widgets:Ljava/util/ArrayList;
invoke-virtual {v4, v3}, Ljava/util/ArrayList;->remove(Ljava/lang/Object;)Z
.line 4103
iget-object v4, v2, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->widgets:Ljava/util/ArrayList;
invoke-virtual {v4, v3}, Ljava/util/ArrayList;->remove(Ljava/lang/Object;)Z
.line 4104
iget-object v4, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v4, v3}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-wrap18(Lcom/android/server/appwidget/AppWidgetServiceImpl;Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;)V
.line 4105
iget-object v4, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-virtual {v4, v3}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->removeWidgetLocked(Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;)V
.line 4091
:cond_1
add-int/lit8 v1, v1, -0x1
goto :goto_0
.line 4108
.end local v0 # "host":Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
.end local v2 # "provider":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.end local v3 # "widget":Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
:cond_2
iget-object v4, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->mPrunedApps:Ljava/util/HashSet;
invoke-virtual {v4, p1}, Ljava/util/HashSet;->add(Ljava/lang/Object;)Z
.line 4086
.end local v1 # "i":I
:goto_1
return-void
.line 4111
:cond_3
const-string/jumbo v4, "BackupRestoreController"
new-instance v5, Ljava/lang/StringBuilder;
invoke-direct {v5}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v6, "already pruned "
invoke-virtual {v5, v6}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v5
invoke-virtual {v5, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v5
const-string/jumbo v6, ", continuing normally"
invoke-virtual {v5, v6}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v5
invoke-virtual {v5}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v5
invoke-static {v4, v5}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
goto :goto_1
.end method
.method private sendWidgetRestoreBroadcastLocked(Ljava/lang/String;Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;[I[ILandroid/os/UserHandle;)V
.locals 3
.param p1, "action" # Ljava/lang/String;
.param p2, "provider" # Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.param p3, "host" # Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
.param p4, "oldIds" # [I
.param p5, "newIds" # [I
.param p6, "userHandle" # Landroid/os/UserHandle;
.prologue
const/4 v2, 0x0
.line 4067
new-instance v0, Landroid/content/Intent;
invoke-direct {v0, p1}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V
.line 4068
.local v0, "intent":Landroid/content/Intent;
const-string/jumbo v1, "appWidgetOldIds"
invoke-virtual {v0, v1, p4}, Landroid/content/Intent;->putExtra(Ljava/lang/String;[I)Landroid/content/Intent;
.line 4069
const-string/jumbo v1, "appWidgetIds"
invoke-virtual {v0, v1, p5}, Landroid/content/Intent;->putExtra(Ljava/lang/String;[I)Landroid/content/Intent;
.line 4070
if-eqz p2, :cond_0
.line 4071
iget-object v1, p2, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->info:Landroid/appwidget/AppWidgetProviderInfo;
iget-object v1, v1, Landroid/appwidget/AppWidgetProviderInfo;->provider:Landroid/content/ComponentName;
invoke-virtual {v0, v1}, Landroid/content/Intent;->setComponent(Landroid/content/ComponentName;)Landroid/content/Intent;
.line 4072
iget-object v1, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v1, v0, p6}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-wrap14(Lcom/android/server/appwidget/AppWidgetServiceImpl;Landroid/content/Intent;Landroid/os/UserHandle;)V
.line 4074
:cond_0
if-eqz p3, :cond_1
.line 4075
invoke-virtual {v0, v2}, Landroid/content/Intent;->setComponent(Landroid/content/ComponentName;)Landroid/content/Intent;
.line 4076
iget-object v1, p3, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;->id:Lcom/android/server/appwidget/AppWidgetServiceImpl$HostId;
iget-object v1, v1, Lcom/android/server/appwidget/AppWidgetServiceImpl$HostId;->packageName:Ljava/lang/String;
invoke-virtual {v0, v1}, Landroid/content/Intent;->setPackage(Ljava/lang/String;)Landroid/content/Intent;
.line 4077
const-string/jumbo v1, "hostId"
iget-object v2, p3, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;->id:Lcom/android/server/appwidget/AppWidgetServiceImpl$HostId;
iget v2, v2, Lcom/android/server/appwidget/AppWidgetServiceImpl$HostId;->hostId:I
invoke-virtual {v0, v1, v2}, Landroid/content/Intent;->putExtra(Ljava/lang/String;I)Landroid/content/Intent;
.line 4078
iget-object v1, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v1, v0, p6}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-wrap14(Lcom/android/server/appwidget/AppWidgetServiceImpl;Landroid/content/Intent;Landroid/os/UserHandle;)V
.line 4066
:cond_1
return-void
.end method
.method private stashHostRestoreUpdateLocked(Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;II)V
.locals 4
.param p1, "host" # Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
.param p2, "oldId" # I
.param p3, "newId" # I
.prologue
.line 4049
iget-object v1, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->mUpdatesByHost:Ljava/util/HashMap;
invoke-virtual {v1, p1}, Ljava/util/HashMap;->get(Ljava/lang/Object;)Ljava/lang/Object;
move-result-object v0
check-cast v0, Ljava/util/ArrayList;
.line 4050
.local v0, "r":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;"
if-nez v0, :cond_1
.line 4051
new-instance v0, Ljava/util/ArrayList;
.end local v0 # "r":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;"
invoke-direct {v0}, Ljava/util/ArrayList;-><init>()V
.line 4052
.restart local v0 # "r":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;"
iget-object v1, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->mUpdatesByHost:Ljava/util/HashMap;
invoke-virtual {v1, p1, v0}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
.line 4062
:cond_0
new-instance v1, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;
invoke-direct {v1, p0, p2, p3}, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;-><init>(Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;II)V
invoke-virtual {v0, v1}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z
.line 4048
return-void
.line 4054
:cond_1
invoke-direct {p0, v0, p2, p3}, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->alreadyStashed(Ljava/util/ArrayList;II)Z
move-result v1
if-eqz v1, :cond_0
.line 4056
const-string/jumbo v1, "BackupRestoreController"
new-instance v2, Ljava/lang/StringBuilder;
invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v3, "ID remap "
invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v2
invoke-virtual {v2, p2}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v2
const-string/jumbo v3, " -> "
invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v2
invoke-virtual {v2, p3}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v2
.line 4057
const-string/jumbo v3, " already stashed for "
.line 4056
invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v2
invoke-virtual {v2, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;
move-result-object v2
invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v2
invoke-static {v1, v2}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
.line 4059
return-void
.end method
.method private stashProviderRestoreUpdateLocked(Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;II)V
.locals 4
.param p1, "provider" # Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.param p2, "oldId" # I
.param p3, "newId" # I
.prologue
.line 4019
iget-object v1, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->mUpdatesByProvider:Ljava/util/HashMap;
invoke-virtual {v1, p1}, Ljava/util/HashMap;->get(Ljava/lang/Object;)Ljava/lang/Object;
move-result-object v0
check-cast v0, Ljava/util/ArrayList;
.line 4020
.local v0, "r":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;"
if-nez v0, :cond_1
.line 4021
new-instance v0, Ljava/util/ArrayList;
.end local v0 # "r":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;"
invoke-direct {v0}, Ljava/util/ArrayList;-><init>()V
.line 4022
.restart local v0 # "r":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;"
iget-object v1, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->mUpdatesByProvider:Ljava/util/HashMap;
invoke-virtual {v1, p1, v0}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
.line 4033
:cond_0
new-instance v1, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;
invoke-direct {v1, p0, p2, p3}, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;-><init>(Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;II)V
invoke-virtual {v0, v1}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z
.line 4018
return-void
.line 4025
:cond_1
invoke-direct {p0, v0, p2, p3}, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->alreadyStashed(Ljava/util/ArrayList;II)Z
move-result v1
if-eqz v1, :cond_0
.line 4027
const-string/jumbo v1, "BackupRestoreController"
new-instance v2, Ljava/lang/StringBuilder;
invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v3, "ID remap "
invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v2
invoke-virtual {v2, p2}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v2
const-string/jumbo v3, " -> "
invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v2
invoke-virtual {v2, p3}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v2
.line 4028
const-string/jumbo v3, " already stashed for "
.line 4027
invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v2
invoke-virtual {v2, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;
move-result-object v2
invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v2
invoke-static {v1, v2}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
.line 4030
return-void
.end method
# virtual methods
.method public getWidgetParticipants(I)Ljava/util/List;
.locals 8
.param p1, "userId" # I
.annotation system Ldalvik/annotation/Signature;
value = {
"(I)",
"Ljava/util/List",
"<",
"Ljava/lang/String;",
">;"
}
.end annotation
.prologue
.line 3605
const-string/jumbo v5, "BackupRestoreController"
new-instance v6, Ljava/lang/StringBuilder;
invoke-direct {v6}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v7, "Getting widget participants for user: "
invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v6
invoke-virtual {v6, p1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v6
invoke-virtual {v6}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v6
invoke-static {v5, v6}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
.line 3608
new-instance v2, Ljava/util/HashSet;
invoke-direct {v2}, Ljava/util/HashSet;-><init>()V
.line 3609
.local v2, "packages":Ljava/util/HashSet;, "Ljava/util/HashSet<Ljava/lang/String;>;"
iget-object v5, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v5}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get4(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/lang/Object;
move-result-object v6
monitor-enter v6
.line 3610
:try_start_0
iget-object v5, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v5}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get10(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/util/ArrayList;
move-result-object v5
invoke-virtual {v5}, Ljava/util/ArrayList;->size()I
move-result v0
.line 3611
.local v0, "N":I
const/4 v1, 0x0
.local v1, "i":I
:goto_0
if-ge v1, v0, :cond_2
.line 3612
iget-object v5, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v5}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get10(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/util/ArrayList;
move-result-object v5
invoke-virtual {v5, v1}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;
move-result-object v4
check-cast v4, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
.line 3615
.local v4, "widget":Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
invoke-direct {p0, v4, p1}, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->isProviderAndHostInUser(Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;I)Z
move-result v5
if-nez v5, :cond_1
.line 3611
:cond_0
:goto_1
add-int/lit8 v1, v1, 0x1
goto :goto_0
.line 3619
:cond_1
iget-object v5, v4, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->host:Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
iget-object v5, v5, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;->id:Lcom/android/server/appwidget/AppWidgetServiceImpl$HostId;
iget-object v5, v5, Lcom/android/server/appwidget/AppWidgetServiceImpl$HostId;->packageName:Ljava/lang/String;
invoke-virtual {v2, v5}, Ljava/util/HashSet;->add(Ljava/lang/Object;)Z
.line 3620
iget-object v3, v4, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->provider:Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.line 3621
.local v3, "provider":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
if-eqz v3, :cond_0
.line 3622
iget-object v5, v3, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->id:Lcom/android/server/appwidget/AppWidgetServiceImpl$ProviderId;
iget-object v5, v5, Lcom/android/server/appwidget/AppWidgetServiceImpl$ProviderId;->componentName:Landroid/content/ComponentName;
invoke-virtual {v5}, Landroid/content/ComponentName;->getPackageName()Ljava/lang/String;
move-result-object v5
invoke-virtual {v2, v5}, Ljava/util/HashSet;->add(Ljava/lang/Object;)Z
:try_end_0
.catchall {:try_start_0 .. :try_end_0} :catchall_0
goto :goto_1
.line 3609
.end local v0 # "N":I
.end local v1 # "i":I
.end local v3 # "provider":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.end local v4 # "widget":Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
:catchall_0
move-exception v5
monitor-exit v6
throw v5
.restart local v0 # "N":I
.restart local v1 # "i":I
:cond_2
monitor-exit v6
.line 3626
new-instance v5, Ljava/util/ArrayList;
invoke-direct {v5, v2}, Ljava/util/ArrayList;-><init>(Ljava/util/Collection;)V
return-object v5
.end method
.method public getWidgetState(Ljava/lang/String;I)[B
.locals 13
.param p1, "backedupPackage" # Ljava/lang/String;
.param p2, "userId" # I
.prologue
.line 3631
const-string/jumbo v9, "BackupRestoreController"
new-instance v10, Ljava/lang/StringBuilder;
invoke-direct {v10}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v11, "Getting widget state for user: "
invoke-virtual {v10, v11}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v10
invoke-virtual {v10, p2}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v10
invoke-virtual {v10}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v10
invoke-static {v9, v10}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
.line 3634
new-instance v7, Ljava/io/ByteArrayOutputStream;
invoke-direct {v7}, Ljava/io/ByteArrayOutputStream;-><init>()V
.line 3635
.local v7, "stream":Ljava/io/ByteArrayOutputStream;
iget-object v9, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v9}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get4(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/lang/Object;
move-result-object v10
monitor-enter v10
.line 3638
:try_start_0
invoke-direct {p0, p1, p2}, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->packageNeedsWidgetBackupLocked(Ljava/lang/String;I)Z
:try_end_0
.catchall {:try_start_0 .. :try_end_0} :catchall_0
move-result v9
if-nez v9, :cond_0
.line 3639
const/4 v9, 0x0
monitor-exit v10
return-object v9
.line 3643
:cond_0
:try_start_1
new-instance v5, Lcom/android/internal/util/FastXmlSerializer;
invoke-direct {v5}, Lcom/android/internal/util/FastXmlSerializer;-><init>()V
.line 3644
.local v5, "out":Lorg/xmlpull/v1/XmlSerializer;
sget-object v9, Ljava/nio/charset/StandardCharsets;->UTF_8:Ljava/nio/charset/Charset;
invoke-virtual {v9}, Ljava/nio/charset/Charset;->name()Ljava/lang/String;
move-result-object v9
invoke-interface {v5, v7, v9}, Lorg/xmlpull/v1/XmlSerializer;->setOutput(Ljava/io/OutputStream;Ljava/lang/String;)V
.line 3645
const/4 v9, 0x1
invoke-static {v9}, Ljava/lang/Boolean;->valueOf(Z)Ljava/lang/Boolean;
move-result-object v9
const/4 v11, 0x0
invoke-interface {v5, v11, v9}, Lorg/xmlpull/v1/XmlSerializer;->startDocument(Ljava/lang/String;Ljava/lang/Boolean;)V
.line 3646
const-string/jumbo v9, "ws"
const/4 v11, 0x0
invoke-interface {v5, v11, v9}, Lorg/xmlpull/v1/XmlSerializer;->startTag(Ljava/lang/String;Ljava/lang/String;)Lorg/xmlpull/v1/XmlSerializer;
.line 3647
const-string/jumbo v9, "version"
const/4 v11, 0x2
invoke-static {v11}, Ljava/lang/String;->valueOf(I)Ljava/lang/String;
move-result-object v11
const/4 v12, 0x0
invoke-interface {v5, v12, v9, v11}, Lorg/xmlpull/v1/XmlSerializer;->attribute(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/xmlpull/v1/XmlSerializer;
.line 3648
const-string/jumbo v9, "pkg"
const/4 v11, 0x0
invoke-interface {v5, v11, v9, p1}, Lorg/xmlpull/v1/XmlSerializer;->attribute(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/xmlpull/v1/XmlSerializer;
.line 3653
const/4 v4, 0x0
.line 3654
.local v4, "index":I
iget-object v9, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v9}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get7(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/util/ArrayList;
move-result-object v9
invoke-virtual {v9}, Ljava/util/ArrayList;->size()I
move-result v0
.line 3655
.local v0, "N":I
const/4 v3, 0x0
.local v3, "i":I
:goto_0
if-ge v3, v0, :cond_3
.line 3656
iget-object v9, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v9}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get7(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/util/ArrayList;
move-result-object v9
invoke-virtual {v9, v3}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;
move-result-object v6
check-cast v6, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.line 3658
.local v6, "provider":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
iget-object v9, v6, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->widgets:Ljava/util/ArrayList;
invoke-virtual {v9}, Ljava/util/ArrayList;->isEmpty()Z
move-result v9
if-nez v9, :cond_2
.line 3659
invoke-virtual {v6, p1, p2}, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->isInPackageForUser(Ljava/lang/String;I)Z
move-result v9
if-nez v9, :cond_1
.line 3660
invoke-virtual {v6, p1, p2}, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->hostedByPackageForUser(Ljava/lang/String;I)Z
move-result v9
.line 3658
if-eqz v9, :cond_2
.line 3661
:cond_1
iput v4, v6, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->tag:I
.line 3662
invoke-static {v5, v6}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-wrap17(Lorg/xmlpull/v1/XmlSerializer;Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;)V
.line 3663
add-int/lit8 v4, v4, 0x1
.line 3655
:cond_2
add-int/lit8 v3, v3, 0x1
goto :goto_0
.line 3667
.end local v6 # "provider":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
:cond_3
iget-object v9, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v9}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get3(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/util/ArrayList;
move-result-object v9
invoke-virtual {v9}, Ljava/util/ArrayList;->size()I
move-result v0
.line 3668
const/4 v4, 0x0
.line 3669
const/4 v3, 0x0
:goto_1
if-ge v3, v0, :cond_6
.line 3670
iget-object v9, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v9}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get3(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/util/ArrayList;
move-result-object v9
invoke-virtual {v9, v3}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;
move-result-object v2
check-cast v2, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
.line 3672
.local v2, "host":Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
iget-object v9, v2, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;->widgets:Ljava/util/ArrayList;
invoke-virtual {v9}, Ljava/util/ArrayList;->isEmpty()Z
move-result v9
if-nez v9, :cond_5
.line 3673
invoke-virtual {v2, p1, p2}, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;->isInPackageForUser(Ljava/lang/String;I)Z
move-result v9
if-nez v9, :cond_4
.line 3674
invoke-static {v2, p1, p2}, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;->-wrap0(Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;Ljava/lang/String;I)Z
move-result v9
.line 3672
if-eqz v9, :cond_5
.line 3675
:cond_4
iput v4, v2, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;->tag:I
.line 3676
invoke-static {v5, v2}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-wrap16(Lorg/xmlpull/v1/XmlSerializer;Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;)V
.line 3677
add-int/lit8 v4, v4, 0x1
.line 3669
:cond_5
add-int/lit8 v3, v3, 0x1
goto :goto_1
.line 3683
.end local v2 # "host":Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
:cond_6
iget-object v9, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v9}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get10(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/util/ArrayList;
move-result-object v9
invoke-virtual {v9}, Ljava/util/ArrayList;->size()I
move-result v0
.line 3684
const/4 v3, 0x0
:goto_2
if-ge v3, v0, :cond_9
.line 3685
iget-object v9, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v9}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get10(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/util/ArrayList;
move-result-object v9
invoke-virtual {v9, v3}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;
move-result-object v8
check-cast v8, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
.line 3687
.local v8, "widget":Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
iget-object v6, v8, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->provider:Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.line 3688
.restart local v6 # "provider":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
iget-object v9, v8, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->host:Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
invoke-virtual {v9, p1, p2}, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;->isInPackageForUser(Ljava/lang/String;I)Z
move-result v9
if-nez v9, :cond_7
.line 3689
if-eqz v6, :cond_8
.line 3690
invoke-virtual {v6, p1, p2}, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->isInPackageForUser(Ljava/lang/String;I)Z
move-result v9
.line 3688
if-eqz v9, :cond_8
.line 3691
:cond_7
invoke-static {v5, v8}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-wrap15(Lorg/xmlpull/v1/XmlSerializer;Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;)V
.line 3684
:cond_8
add-int/lit8 v3, v3, 0x1
goto :goto_2
.line 3695
.end local v6 # "provider":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.end local v8 # "widget":Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
:cond_9
const-string/jumbo v9, "ws"
const/4 v11, 0x0
invoke-interface {v5, v11, v9}, Lorg/xmlpull/v1/XmlSerializer;->endTag(Ljava/lang/String;Ljava/lang/String;)Lorg/xmlpull/v1/XmlSerializer;
.line 3696
invoke-interface {v5}, Lorg/xmlpull/v1/XmlSerializer;->endDocument()V
:try_end_1
.catch Ljava/io/IOException; {:try_start_1 .. :try_end_1} :catch_0
.catchall {:try_start_1 .. :try_end_1} :catchall_0
monitor-exit v10
.line 3703
invoke-virtual {v7}, Ljava/io/ByteArrayOutputStream;->toByteArray()[B
move-result-object v9
return-object v9
.line 3697
.end local v0 # "N":I
.end local v3 # "i":I
.end local v4 # "index":I
.end local v5 # "out":Lorg/xmlpull/v1/XmlSerializer;
:catch_0
move-exception v1
.line 3698
.local v1, "e":Ljava/io/IOException;
:try_start_2
const-string/jumbo v9, "BackupRestoreController"
new-instance v11, Ljava/lang/StringBuilder;
invoke-direct {v11}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v12, "Unable to save widget state for "
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
invoke-virtual {v11, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
invoke-virtual {v11}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v11
invoke-static {v9, v11}, Landroid/util/Slog;->w(Ljava/lang/String;Ljava/lang/String;)I
:try_end_2
.catchall {:try_start_2 .. :try_end_2} :catchall_0
.line 3699
const/4 v9, 0x0
monitor-exit v10
return-object v9
.line 3635
.end local v1 # "e":Ljava/io/IOException;
:catchall_0
move-exception v9
monitor-exit v10
throw v9
.end method
.method public restoreFinished(I)V
.locals 28
.param p1, "userId" # I
.prologue
.line 3881
const-string/jumbo v2, "BackupRestoreController"
new-instance v3, Ljava/lang/StringBuilder;
invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v5, "restoreFinished for "
invoke-virtual {v3, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v3
move/from16 v0, p1
invoke-virtual {v3, v0}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v3
invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v3
invoke-static {v2, v3}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
.line 3884
new-instance v8, Landroid/os/UserHandle;
move/from16 v0, p1
invoke-direct {v8, v0}, Landroid/os/UserHandle;-><init>(I)V
.line 3885
.local v8, "userHandle":Landroid/os/UserHandle;
move-object/from16 v0, p0
iget-object v2, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v2}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get4(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/lang/Object;
move-result-object v27
monitor-enter v27
.line 3888
:try_start_0
move-object/from16 v0, p0
iget-object v2, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->mUpdatesByProvider:Ljava/util/HashMap;
invoke-virtual {v2}, Ljava/util/HashMap;->entrySet()Ljava/util/Set;
move-result-object v24
.line 3889
.local v24, "providerEntries":Ljava/util/Set;, "Ljava/util/Set<Ljava/util/Map$Entry<Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;>;>;"
invoke-interface/range {v24 .. v24}, Ljava/lang/Iterable;->iterator()Ljava/util/Iterator;
move-result-object v19
.local v19, "e$iterator":Ljava/util/Iterator;
:cond_0
:goto_0
invoke-interface/range {v19 .. v19}, Ljava/util/Iterator;->hasNext()Z
move-result v2
if-eqz v2, :cond_3
invoke-interface/range {v19 .. v19}, Ljava/util/Iterator;->next()Ljava/lang/Object;
move-result-object v18
check-cast v18, Ljava/util/Map$Entry;
.line 3891
.local v18, "e":Ljava/util/Map$Entry;, "Ljava/util/Map$Entry<Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;>;"
invoke-interface/range {v18 .. v18}, Ljava/util/Map$Entry;->getKey()Ljava/lang/Object;
move-result-object v4
check-cast v4, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.line 3892
.local v4, "provider":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
invoke-interface/range {v18 .. v18}, Ljava/util/Map$Entry;->getValue()Ljava/lang/Object;
move-result-object v26
check-cast v26, Ljava/util/ArrayList;
.line 3893
.local v26, "updates":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;"
move-object/from16 v0, p0
move-object/from16 v1, v26
invoke-direct {v0, v1}, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->countPendingUpdates(Ljava/util/ArrayList;)I
move-result v23
.line 3895
.local v23, "pending":I
const-string/jumbo v2, "BackupRestoreController"
new-instance v3, Ljava/lang/StringBuilder;
invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v5, "Provider "
invoke-virtual {v3, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v3
invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;
move-result-object v3
const-string/jumbo v5, " pending: "
invoke-virtual {v3, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v3
move/from16 v0, v23
invoke-virtual {v3, v0}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v3
invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v3
invoke-static {v2, v3}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
.line 3897
if-lez v23, :cond_0
.line 3898
move/from16 v0, v23
new-array v6, v0, [I
.line 3899
.local v6, "oldIds":[I
move/from16 v0, v23
new-array v7, v0, [I
.line 3900
.local v7, "newIds":[I
invoke-virtual/range {v26 .. v26}, Ljava/util/ArrayList;->size()I
move-result v16
.line 3901
.local v16, "N":I
const/16 v22, 0x0
.line 3902
.local v22, "nextPending":I
const/16 v21, 0x0
.local v21, "i":I
:goto_1
move/from16 v0, v21
move/from16 v1, v16
if-ge v0, v1, :cond_2
.line 3903
move-object/from16 v0, v26
move/from16 v1, v21
invoke-virtual {v0, v1}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;
move-result-object v25
check-cast v25, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;
.line 3904
.local v25, "r":Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;
move-object/from16 v0, v25
iget-boolean v2, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;->notified:Z
if-nez v2, :cond_1
.line 3905
const/4 v2, 0x1
move-object/from16 v0, v25
iput-boolean v2, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;->notified:Z
.line 3906
move-object/from16 v0, v25
iget v2, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;->oldId:I
aput v2, v6, v22
.line 3907
move-object/from16 v0, v25
iget v2, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;->newId:I
aput v2, v7, v22
.line 3908
add-int/lit8 v22, v22, 0x1
.line 3910
const-string/jumbo v2, "BackupRestoreController"
new-instance v3, Ljava/lang/StringBuilder;
invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v5, " "
invoke-virtual {v3, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v3
move-object/from16 v0, v25
iget v5, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;->oldId:I
invoke-virtual {v3, v5}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v3
const-string/jumbo v5, " => "
invoke-virtual {v3, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v3
move-object/from16 v0, v25
iget v5, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;->newId:I
invoke-virtual {v3, v5}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v3
invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v3
invoke-static {v2, v3}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
.line 3902
:cond_1
add-int/lit8 v21, v21, 0x1
goto :goto_1
.line 3915
.end local v25 # "r":Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;
:cond_2
const-string/jumbo v3, "android.appwidget.action.APPWIDGET_RESTORED"
.line 3916
const/4 v5, 0x0
move-object/from16 v2, p0
.line 3914
invoke-direct/range {v2 .. v8}, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->sendWidgetRestoreBroadcastLocked(Ljava/lang/String;Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;[I[ILandroid/os/UserHandle;)V
:try_end_0
.catchall {:try_start_0 .. :try_end_0} :catchall_0
goto/16 :goto_0
.line 3885
.end local v4 # "provider":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.end local v6 # "oldIds":[I
.end local v7 # "newIds":[I
.end local v16 # "N":I
.end local v18 # "e":Ljava/util/Map$Entry;, "Ljava/util/Map$Entry<Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;>;"
.end local v19 # "e$iterator":Ljava/util/Iterator;
.end local v21 # "i":I
.end local v22 # "nextPending":I
.end local v23 # "pending":I
.end local v24 # "providerEntries":Ljava/util/Set;, "Ljava/util/Set<Ljava/util/Map$Entry<Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;>;>;"
.end local v26 # "updates":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;"
:catchall_0
move-exception v2
monitor-exit v27
throw v2
.line 3922
.restart local v19 # "e$iterator":Ljava/util/Iterator;
.restart local v24 # "providerEntries":Ljava/util/Set;, "Ljava/util/Set<Ljava/util/Map$Entry<Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;>;>;"
:cond_3
:try_start_1
move-object/from16 v0, p0
iget-object v2, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->mUpdatesByHost:Ljava/util/HashMap;
invoke-virtual {v2}, Ljava/util/HashMap;->entrySet()Ljava/util/Set;
move-result-object v20
.line 3923
.local v20, "hostEntries":Ljava/util/Set;, "Ljava/util/Set<Ljava/util/Map$Entry<Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;>;>;"
invoke-interface/range {v20 .. v20}, Ljava/lang/Iterable;->iterator()Ljava/util/Iterator;
move-result-object v19
:cond_4
:goto_2
invoke-interface/range {v19 .. v19}, Ljava/util/Iterator;->hasNext()Z
move-result v2
if-eqz v2, :cond_7
invoke-interface/range {v19 .. v19}, Ljava/util/Iterator;->next()Ljava/lang/Object;
move-result-object v17
check-cast v17, Ljava/util/Map$Entry;
.line 3924
.local v17, "e":Ljava/util/Map$Entry;, "Ljava/util/Map$Entry<Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;>;"
invoke-interface/range {v17 .. v17}, Ljava/util/Map$Entry;->getKey()Ljava/lang/Object;
move-result-object v12
check-cast v12, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
.line 3925
.local v12, "host":Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
iget-object v2, v12, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;->id:Lcom/android/server/appwidget/AppWidgetServiceImpl$HostId;
iget v2, v2, Lcom/android/server/appwidget/AppWidgetServiceImpl$HostId;->uid:I
const/4 v3, -0x1
if-eq v2, v3, :cond_4
.line 3926
invoke-interface/range {v17 .. v17}, Ljava/util/Map$Entry;->getValue()Ljava/lang/Object;
move-result-object v26
check-cast v26, Ljava/util/ArrayList;
.line 3927
.restart local v26 # "updates":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;"
move-object/from16 v0, p0
move-object/from16 v1, v26
invoke-direct {v0, v1}, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->countPendingUpdates(Ljava/util/ArrayList;)I
move-result v23
.line 3929
.restart local v23 # "pending":I
const-string/jumbo v2, "BackupRestoreController"
new-instance v3, Ljava/lang/StringBuilder;
invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v5, "Host "
invoke-virtual {v3, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v3
invoke-virtual {v3, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;
move-result-object v3
const-string/jumbo v5, " pending: "
invoke-virtual {v3, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v3
move/from16 v0, v23
invoke-virtual {v3, v0}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v3
invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v3
invoke-static {v2, v3}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
.line 3931
if-lez v23, :cond_4
.line 3932
move/from16 v0, v23
new-array v6, v0, [I
.line 3933
.restart local v6 # "oldIds":[I
move/from16 v0, v23
new-array v7, v0, [I
.line 3934
.restart local v7 # "newIds":[I
invoke-virtual/range {v26 .. v26}, Ljava/util/ArrayList;->size()I
move-result v16
.line 3935
.restart local v16 # "N":I
const/16 v22, 0x0
.line 3936
.restart local v22 # "nextPending":I
const/16 v21, 0x0
.restart local v21 # "i":I
:goto_3
move/from16 v0, v21
move/from16 v1, v16
if-ge v0, v1, :cond_6
.line 3937
move-object/from16 v0, v26
move/from16 v1, v21
invoke-virtual {v0, v1}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;
move-result-object v25
check-cast v25, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;
.line 3938
.restart local v25 # "r":Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;
move-object/from16 v0, v25
iget-boolean v2, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;->notified:Z
if-nez v2, :cond_5
.line 3939
const/4 v2, 0x1
move-object/from16 v0, v25
iput-boolean v2, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;->notified:Z
.line 3940
move-object/from16 v0, v25
iget v2, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;->oldId:I
aput v2, v6, v22
.line 3941
move-object/from16 v0, v25
iget v2, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;->newId:I
aput v2, v7, v22
.line 3942
add-int/lit8 v22, v22, 0x1
.line 3944
const-string/jumbo v2, "BackupRestoreController"
new-instance v3, Ljava/lang/StringBuilder;
invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v5, " "
invoke-virtual {v3, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v3
move-object/from16 v0, v25
iget v5, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;->oldId:I
invoke-virtual {v3, v5}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v3
const-string/jumbo v5, " => "
invoke-virtual {v3, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v3
move-object/from16 v0, v25
iget v5, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;->newId:I
invoke-virtual {v3, v5}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v3
invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v3
invoke-static {v2, v3}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
.line 3936
:cond_5
add-int/lit8 v21, v21, 0x1
goto :goto_3
.line 3949
.end local v25 # "r":Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;
:cond_6
const-string/jumbo v10, "android.appwidget.action.APPWIDGET_HOST_RESTORED"
.line 3950
const/4 v11, 0x0
move-object/from16 v9, p0
move-object v13, v6
move-object v14, v7
move-object v15, v8
.line 3948
invoke-direct/range {v9 .. v15}, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->sendWidgetRestoreBroadcastLocked(Ljava/lang/String;Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;[I[ILandroid/os/UserHandle;)V
:try_end_1
.catchall {:try_start_1 .. :try_end_1} :catchall_0
goto/16 :goto_2
.end local v6 # "oldIds":[I
.end local v7 # "newIds":[I
.end local v12 # "host":Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
.end local v16 # "N":I
.end local v17 # "e":Ljava/util/Map$Entry;, "Ljava/util/Map$Entry<Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;>;"
.end local v21 # "i":I
.end local v22 # "nextPending":I
.end local v23 # "pending":I
.end local v26 # "updates":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController$RestoreUpdateRecord;>;"
:cond_7
monitor-exit v27
.line 3879
return-void
.end method
.method public restoreStarting(I)V
.locals 3
.param p1, "userId" # I
.prologue
.line 3708
const-string/jumbo v0, "BackupRestoreController"
new-instance v1, Ljava/lang/StringBuilder;
invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v2, "Restore starting for user: "
invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v1
invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v1
invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v1
invoke-static {v0, v1}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
.line 3711
iget-object v0, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
invoke-static {v0}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get4(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/lang/Object;
move-result-object v1
monitor-enter v1
.line 3715
:try_start_0
iget-object v0, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->mPrunedApps:Ljava/util/HashSet;
invoke-virtual {v0}, Ljava/util/HashSet;->clear()V
.line 3716
iget-object v0, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->mUpdatesByProvider:Ljava/util/HashMap;
invoke-virtual {v0}, Ljava/util/HashMap;->clear()V
.line 3717
iget-object v0, p0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->mUpdatesByHost:Ljava/util/HashMap;
invoke-virtual {v0}, Ljava/util/HashMap;->clear()V
:try_end_0
.catchall {:try_start_0 .. :try_end_0} :catchall_0
monitor-exit v1
.line 3706
return-void
.line 3711
:catchall_0
move-exception v0
monitor-exit v1
throw v0
.end method
.method public restoreWidgetState(Ljava/lang/String;[BI)V
.locals 31
.param p1, "packageName" # Ljava/lang/String;
.param p2, "restoredState" # [B
.param p3, "userId" # I
.prologue
.line 3723
const-string/jumbo v27, "BackupRestoreController"
new-instance v28, Ljava/lang/StringBuilder;
invoke-direct/range {v28 .. v28}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v29, "Restoring widget state for user:"
invoke-virtual/range {v28 .. v29}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v28
move-object/from16 v0, v28
move/from16 v1, p3
invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v28
.line 3724
const-string/jumbo v29, " package: "
.line 3723
invoke-virtual/range {v28 .. v29}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v28
move-object/from16 v0, v28
move-object/from16 v1, p1
invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v28
invoke-virtual/range {v28 .. v28}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v28
invoke-static/range {v27 .. v28}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
.line 3727
new-instance v20, Ljava/io/ByteArrayInputStream;
move-object/from16 v0, v20
move-object/from16 v1, p2
invoke-direct {v0, v1}, Ljava/io/ByteArrayInputStream;-><init>([B)V
.line 3730
.local v20, "stream":Ljava/io/ByteArrayInputStream;
:try_start_0
new-instance v19, Ljava/util/ArrayList;
invoke-direct/range {v19 .. v19}, Ljava/util/ArrayList;-><init>()V
.line 3733
.local v19, "restoredProviders":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;>;"
new-instance v17, Ljava/util/ArrayList;
invoke-direct/range {v17 .. v17}, Ljava/util/ArrayList;-><init>()V
.line 3735
.local v17, "restoredHosts":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;>;"
invoke-static {}, Landroid/util/Xml;->newPullParser()Lorg/xmlpull/v1/XmlPullParser;
move-result-object v14
.line 3736
.local v14, "parser":Lorg/xmlpull/v1/XmlPullParser;
sget-object v27, Ljava/nio/charset/StandardCharsets;->UTF_8:Ljava/nio/charset/Charset;
invoke-virtual/range {v27 .. v27}, Ljava/nio/charset/Charset;->name()Ljava/lang/String;
move-result-object v27
move-object/from16 v0, v20
move-object/from16 v1, v27
invoke-interface {v14, v0, v1}, Lorg/xmlpull/v1/XmlPullParser;->setInput(Ljava/io/InputStream;Ljava/lang/String;)V
.line 3738
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
move-object/from16 v27, v0
invoke-static/range {v27 .. v27}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get4(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/lang/Object;
move-result-object v28
monitor-enter v28
:try_end_0
.catch Lorg/xmlpull/v1/XmlPullParserException; {:try_start_0 .. :try_end_0} :catch_0
.catch Ljava/io/IOException; {:try_start_0 .. :try_end_0} :catch_0
.catchall {:try_start_0 .. :try_end_0} :catchall_1
.line 3741
:cond_0
:try_start_1
invoke-interface {v14}, Lorg/xmlpull/v1/XmlPullParser;->next()I
move-result v22
.line 3742
.local v22, "type":I
const/16 v27, 0x2
move/from16 v0, v22
move/from16 v1, v27
if-ne v0, v1, :cond_4
.line 3743
invoke-interface {v14}, Lorg/xmlpull/v1/XmlPullParser;->getName()Ljava/lang/String;
move-result-object v21
.line 3744
.local v21, "tag":Ljava/lang/String;
const-string/jumbo v27, "ws"
move-object/from16 v0, v27
move-object/from16 v1, v21
invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v27
if-eqz v27, :cond_2
.line 3745
const-string/jumbo v27, "version"
const/16 v29, 0x0
move-object/from16 v0, v29
move-object/from16 v1, v27
invoke-interface {v14, v0, v1}, Lorg/xmlpull/v1/XmlPullParser;->getAttributeValue(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
move-result-object v24
.line 3747
.local v24, "version":Ljava/lang/String;
invoke-static/range {v24 .. v24}, Ljava/lang/Integer;->parseInt(Ljava/lang/String;)I
move-result v25
.line 3748
.local v25, "versionNumber":I
const/16 v27, 0x2
move/from16 v0, v25
move/from16 v1, v27
if-le v0, v1, :cond_1
.line 3749
const-string/jumbo v27, "BackupRestoreController"
new-instance v29, Ljava/lang/StringBuilder;
invoke-direct/range {v29 .. v29}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v30, "Unable to process state version "
invoke-virtual/range {v29 .. v30}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v29
move-object/from16 v0, v29
move-object/from16 v1, v24
invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v29
invoke-virtual/range {v29 .. v29}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v29
move-object/from16 v0, v27
move-object/from16 v1, v29
invoke-static {v0, v1}, Landroid/util/Slog;->w(Ljava/lang/String;Ljava/lang/String;)I
:try_end_1
.catchall {:try_start_1 .. :try_end_1} :catchall_0
:try_start_2
monitor-exit v28
:try_end_2
.catch Lorg/xmlpull/v1/XmlPullParserException; {:try_start_2 .. :try_end_2} :catch_0
.catch Ljava/io/IOException; {:try_start_2 .. :try_end_2} :catch_0
.catchall {:try_start_2 .. :try_end_2} :catchall_1
.line 3872
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
move-object/from16 v27, v0
move-object/from16 v0, v27
move/from16 v1, p3
invoke-static {v0, v1}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-wrap12(Lcom/android/server/appwidget/AppWidgetServiceImpl;I)V
.line 3750
return-void
.line 3754
:cond_1
:try_start_3
const-string/jumbo v27, "pkg"
const/16 v29, 0x0
move-object/from16 v0, v29
move-object/from16 v1, v27
invoke-interface {v14, v0, v1}, Lorg/xmlpull/v1/XmlPullParser;->getAttributeValue(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
move-result-object v15
.line 3755
.local v15, "pkg":Ljava/lang/String;
move-object/from16 v0, p1
invoke-virtual {v0, v15}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v27
if-nez v27, :cond_4
.line 3756
const-string/jumbo v27, "BackupRestoreController"
const-string/jumbo v29, "Package mismatch in ws"
move-object/from16 v0, v27
move-object/from16 v1, v29
invoke-static {v0, v1}, Landroid/util/Slog;->w(Ljava/lang/String;Ljava/lang/String;)I
:try_end_3
.catchall {:try_start_3 .. :try_end_3} :catchall_0
:try_start_4
monitor-exit v28
:try_end_4
.catch Lorg/xmlpull/v1/XmlPullParserException; {:try_start_4 .. :try_end_4} :catch_0
.catch Ljava/io/IOException; {:try_start_4 .. :try_end_4} :catch_0
.catchall {:try_start_4 .. :try_end_4} :catchall_1
.line 3872
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
move-object/from16 v27, v0
move-object/from16 v0, v27
move/from16 v1, p3
invoke-static {v0, v1}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-wrap12(Lcom/android/server/appwidget/AppWidgetServiceImpl;I)V
.line 3757
return-void
.line 3759
.end local v15 # "pkg":Ljava/lang/String;
.end local v24 # "version":Ljava/lang/String;
.end local v25 # "versionNumber":I
:cond_2
:try_start_5
const-string/jumbo v27, "p"
move-object/from16 v0, v27
move-object/from16 v1, v21
invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v27
if-eqz v27, :cond_5
.line 3760
const-string/jumbo v27, "pkg"
const/16 v29, 0x0
move-object/from16 v0, v29
move-object/from16 v1, v27
invoke-interface {v14, v0, v1}, Lorg/xmlpull/v1/XmlPullParser;->getAttributeValue(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
move-result-object v15
.line 3761
.restart local v15 # "pkg":Ljava/lang/String;
const-string/jumbo v27, "cl"
const/16 v29, 0x0
move-object/from16 v0, v29
move-object/from16 v1, v27
invoke-interface {v14, v0, v1}, Lorg/xmlpull/v1/XmlPullParser;->getAttributeValue(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
move-result-object v4
.line 3769
.local v4, "cl":Ljava/lang/String;
new-instance v5, Landroid/content/ComponentName;
invoke-direct {v5, v15, v4}, Landroid/content/ComponentName;-><init>(Ljava/lang/String;Ljava/lang/String;)V
.line 3771
.local v5, "componentName":Landroid/content/ComponentName;
move-object/from16 v0, p0
move/from16 v1, p3
invoke-direct {v0, v5, v1}, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->findProviderLocked(Landroid/content/ComponentName;I)Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
move-result-object v13
.line 3772
.local v13, "p":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
if-nez v13, :cond_3
.line 3773
new-instance v13, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.end local v13 # "p":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
const/16 v27, 0x0
move-object/from16 v0, v27
invoke-direct {v13, v0}, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;-><init>(Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;)V
.line 3774
.restart local v13 # "p":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
new-instance v27, Lcom/android/server/appwidget/AppWidgetServiceImpl$ProviderId;
const/16 v29, -0x1
const/16 v30, 0x0
move-object/from16 v0, v27
move/from16 v1, v29
move-object/from16 v2, v30
invoke-direct {v0, v1, v5, v2}, Lcom/android/server/appwidget/AppWidgetServiceImpl$ProviderId;-><init>(ILandroid/content/ComponentName;Lcom/android/server/appwidget/AppWidgetServiceImpl$ProviderId;)V
move-object/from16 v0, v27
iput-object v0, v13, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->id:Lcom/android/server/appwidget/AppWidgetServiceImpl$ProviderId;
.line 3775
new-instance v27, Landroid/appwidget/AppWidgetProviderInfo;
invoke-direct/range {v27 .. v27}, Landroid/appwidget/AppWidgetProviderInfo;-><init>()V
move-object/from16 v0, v27
iput-object v0, v13, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->info:Landroid/appwidget/AppWidgetProviderInfo;
.line 3776
iget-object v0, v13, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->info:Landroid/appwidget/AppWidgetProviderInfo;
move-object/from16 v27, v0
move-object/from16 v0, v27
iput-object v5, v0, Landroid/appwidget/AppWidgetProviderInfo;->provider:Landroid/content/ComponentName;
.line 3777
const/16 v27, 0x1
move/from16 v0, v27
iput-boolean v0, v13, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->zombie:Z
.line 3778
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
move-object/from16 v27, v0
invoke-static/range {v27 .. v27}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-get7(Lcom/android/server/appwidget/AppWidgetServiceImpl;)Ljava/util/ArrayList;
move-result-object v27
move-object/from16 v0, v27
invoke-virtual {v0, v13}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z
.line 3781
:cond_3
const-string/jumbo v27, "BackupRestoreController"
new-instance v29, Ljava/lang/StringBuilder;
invoke-direct/range {v29 .. v29}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v30, " provider "
invoke-virtual/range {v29 .. v30}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v29
iget-object v0, v13, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->id:Lcom/android/server/appwidget/AppWidgetServiceImpl$ProviderId;
move-object/from16 v30, v0
invoke-virtual/range {v29 .. v30}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;
move-result-object v29
invoke-virtual/range {v29 .. v29}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v29
move-object/from16 v0, v27
move-object/from16 v1, v29
invoke-static {v0, v1}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
.line 3783
move-object/from16 v0, v19
invoke-virtual {v0, v13}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z
:try_end_5
.catchall {:try_start_5 .. :try_end_5} :catchall_0
.line 3860
.end local v4 # "cl":Ljava/lang/String;
.end local v5 # "componentName":Landroid/content/ComponentName;
.end local v13 # "p":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.end local v15 # "pkg":Ljava/lang/String;
.end local v21 # "tag":Ljava/lang/String;
:cond_4
:goto_0
const/16 v27, 0x1
move/from16 v0, v22
move/from16 v1, v27
if-ne v0, v1, :cond_0
:try_start_6
monitor-exit v28
:try_end_6
.catch Lorg/xmlpull/v1/XmlPullParserException; {:try_start_6 .. :try_end_6} :catch_0
.catch Ljava/io/IOException; {:try_start_6 .. :try_end_6} :catch_0
.catchall {:try_start_6 .. :try_end_6} :catchall_1
.line 3872
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
move-object/from16 v27, v0
move-object/from16 v0, v27
move/from16 v1, p3
invoke-static {v0, v1}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-wrap12(Lcom/android/server/appwidget/AppWidgetServiceImpl;I)V
.line 3721
.end local v14 # "parser":Lorg/xmlpull/v1/XmlPullParser;
.end local v17 # "restoredHosts":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;>;"
.end local v19 # "restoredProviders":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;>;"
.end local v22 # "type":I
:goto_1
return-void
.line 3784
.restart local v14 # "parser":Lorg/xmlpull/v1/XmlPullParser;
.restart local v17 # "restoredHosts":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;>;"
.restart local v19 # "restoredProviders":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;>;"
.restart local v21 # "tag":Ljava/lang/String;
.restart local v22 # "type":I
:cond_5
:try_start_7
const-string/jumbo v27, "h"
move-object/from16 v0, v27
move-object/from16 v1, v21
invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v27
if-eqz v27, :cond_6
.line 3788
const-string/jumbo v27, "pkg"
const/16 v29, 0x0
move-object/from16 v0, v29
move-object/from16 v1, v27
invoke-interface {v14, v0, v1}, Lorg/xmlpull/v1/XmlPullParser;->getAttributeValue(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
move-result-object v15
.line 3790
.restart local v15 # "pkg":Ljava/lang/String;
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
move-object/from16 v27, v0
move-object/from16 v0, v27
move/from16 v1, p3
invoke-static {v0, v15, v1}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-wrap1(Lcom/android/server/appwidget/AppWidgetServiceImpl;Ljava/lang/String;I)I
move-result v23
.line 3792
.local v23, "uid":I
const-string/jumbo v27, "id"
const/16 v29, 0x0
move-object/from16 v0, v29
move-object/from16 v1, v27
invoke-interface {v14, v0, v1}, Lorg/xmlpull/v1/XmlPullParser;->getAttributeValue(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
move-result-object v27
const/16 v29, 0x10
.line 3791
move-object/from16 v0, v27
move/from16 v1, v29
invoke-static {v0, v1}, Ljava/lang/Integer;->parseInt(Ljava/lang/String;I)I
move-result v9
.line 3794
.local v9, "hostId":I
new-instance v11, Lcom/android/server/appwidget/AppWidgetServiceImpl$HostId;
move/from16 v0, v23
invoke-direct {v11, v0, v9, v15}, Lcom/android/server/appwidget/AppWidgetServiceImpl$HostId;-><init>(IILjava/lang/String;)V
.line 3795
.local v11, "id":Lcom/android/server/appwidget/AppWidgetServiceImpl$HostId;
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
move-object/from16 v27, v0
move-object/from16 v0, v27
invoke-static {v0, v11}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-wrap0(Lcom/android/server/appwidget/AppWidgetServiceImpl;Lcom/android/server/appwidget/AppWidgetServiceImpl$HostId;)Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
move-result-object v7
.line 3796
.local v7, "h":Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
move-object/from16 v0, v17
invoke-virtual {v0, v7}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z
.line 3799
const-string/jumbo v27, "BackupRestoreController"
new-instance v29, Ljava/lang/StringBuilder;
invoke-direct/range {v29 .. v29}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v30, " host["
invoke-virtual/range {v29 .. v30}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v29
invoke-virtual/range {v17 .. v17}, Ljava/util/ArrayList;->size()I
move-result v30
invoke-virtual/range {v29 .. v30}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v29
.line 3800
const-string/jumbo v30, "]: {"
.line 3799
invoke-virtual/range {v29 .. v30}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v29
.line 3800
iget-object v0, v7, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;->id:Lcom/android/server/appwidget/AppWidgetServiceImpl$HostId;
move-object/from16 v30, v0
.line 3799
invoke-virtual/range {v29 .. v30}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;
move-result-object v29
.line 3800
const-string/jumbo v30, "}"
.line 3799
invoke-virtual/range {v29 .. v30}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v29
invoke-virtual/range {v29 .. v29}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v29
move-object/from16 v0, v27
move-object/from16 v1, v29
invoke-static {v0, v1}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
:try_end_7
.catchall {:try_start_7 .. :try_end_7} :catchall_0
goto/16 :goto_0
.line 3738
.end local v7 # "h":Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
.end local v9 # "hostId":I
.end local v11 # "id":Lcom/android/server/appwidget/AppWidgetServiceImpl$HostId;
.end local v15 # "pkg":Ljava/lang/String;
.end local v21 # "tag":Ljava/lang/String;
.end local v22 # "type":I
.end local v23 # "uid":I
:catchall_0
move-exception v27
:try_start_8
monitor-exit v28
throw v27
:try_end_8
.catch Lorg/xmlpull/v1/XmlPullParserException; {:try_start_8 .. :try_end_8} :catch_0
.catch Ljava/io/IOException; {:try_start_8 .. :try_end_8} :catch_0
.catchall {:try_start_8 .. :try_end_8} :catchall_1
.line 3869
.end local v14 # "parser":Lorg/xmlpull/v1/XmlPullParser;
.end local v17 # "restoredHosts":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;>;"
.end local v19 # "restoredProviders":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;>;"
:catch_0
move-exception v6
.line 3870
.local v6, "e":Ljava/lang/Exception;
:try_start_9
const-string/jumbo v27, "BackupRestoreController"
new-instance v28, Ljava/lang/StringBuilder;
invoke-direct/range {v28 .. v28}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v29, "Unable to restore widget state for "
invoke-virtual/range {v28 .. v29}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v28
move-object/from16 v0, v28
move-object/from16 v1, p1
invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v28
invoke-virtual/range {v28 .. v28}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v28
invoke-static/range {v27 .. v28}, Landroid/util/Slog;->w(Ljava/lang/String;Ljava/lang/String;)I
:try_end_9
.catchall {:try_start_9 .. :try_end_9} :catchall_1
.line 3872
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
move-object/from16 v27, v0
move-object/from16 v0, v27
move/from16 v1, p3
invoke-static {v0, v1}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-wrap12(Lcom/android/server/appwidget/AppWidgetServiceImpl;I)V
goto/16 :goto_1
.line 3802
.end local v6 # "e":Ljava/lang/Exception;
.restart local v14 # "parser":Lorg/xmlpull/v1/XmlPullParser;
.restart local v17 # "restoredHosts":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;>;"
.restart local v19 # "restoredProviders":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;>;"
.restart local v21 # "tag":Ljava/lang/String;
.restart local v22 # "type":I
:cond_6
:try_start_a
const-string/jumbo v27, "g"
move-object/from16 v0, v27
move-object/from16 v1, v21
invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v27
if-eqz v27, :cond_4
.line 3804
const-string/jumbo v27, "id"
const/16 v29, 0x0
move-object/from16 v0, v29
move-object/from16 v1, v27
invoke-interface {v14, v0, v1}, Lorg/xmlpull/v1/XmlPullParser;->getAttributeValue(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
move-result-object v27
const/16 v29, 0x10
.line 3803
move-object/from16 v0, v27
move/from16 v1, v29
invoke-static {v0, v1}, Ljava/lang/Integer;->parseInt(Ljava/lang/String;I)I
move-result v18
.line 3806
.local v18, "restoredId":I
const-string/jumbo v27, "h"
const/16 v29, 0x0
move-object/from16 v0, v29
move-object/from16 v1, v27
invoke-interface {v14, v0, v1}, Lorg/xmlpull/v1/XmlPullParser;->getAttributeValue(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
move-result-object v27
const/16 v29, 0x10
.line 3805
move-object/from16 v0, v27
move/from16 v1, v29
invoke-static {v0, v1}, Ljava/lang/Integer;->parseInt(Ljava/lang/String;I)I
move-result v10
.line 3807
.local v10, "hostIndex":I
move-object/from16 v0, v17
invoke-virtual {v0, v10}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;
move-result-object v8
check-cast v8, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
.line 3808
.local v8, "host":Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
const/4 v13, 0x0
.line 3809
.local v13, "p":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
const-string/jumbo v27, "p"
const/16 v29, 0x0
move-object/from16 v0, v29
move-object/from16 v1, v27
invoke-interface {v14, v0, v1}, Lorg/xmlpull/v1/XmlPullParser;->getAttributeValue(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
move-result-object v16
.line 3810
.local v16, "prov":Ljava/lang/String;
if-eqz v16, :cond_7
.line 3813
const/16 v27, 0x10
move-object/from16 v0, v16
move/from16 v1, v27
invoke-static {v0, v1}, Ljava/lang/Integer;->parseInt(Ljava/lang/String;I)I
move-result v26
.line 3814
.local v26, "which":I
move-object/from16 v0, v19
move/from16 v1, v26
invoke-virtual {v0, v1}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;
move-result-object v13
.end local v13 # "p":Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
check-cast v13, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.line 3820
.end local v26 # "which":I
:cond_7
iget-object v0, v8, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;->id:Lcom/android/server/appwidget/AppWidgetServiceImpl$HostId;
move-object/from16 v27, v0
move-object/from16 v0, v27
iget-object v0, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$HostId;->packageName:Ljava/lang/String;
move-object/from16 v27, v0
move-object/from16 v0, p0
move-object/from16 v1, v27
move/from16 v2, p3
invoke-direct {v0, v1, v2}, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->pruneWidgetStateLocked(Ljava/lang/String;I)V
.line 3821
if-eqz v13, :cond_8
.line 3822
iget-object v0, v13, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->id:Lcom/android/server/appwidget/AppWidgetServiceImpl$ProviderId;
move-object/from16 v27, v0
move-object/from16 v0, v27
iget-object v0, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$ProviderId;->componentName:Landroid/content/ComponentName;
move-object/from16 v27, v0
invoke-virtual/range {v27 .. v27}, Landroid/content/ComponentName;->getPackageName()Ljava/lang/String;
move-result-object v27
move-object/from16 v0, p0
move-object/from16 v1, v27
move/from16 v2, p3
invoke-direct {v0, v1, v2}, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->pruneWidgetStateLocked(Ljava/lang/String;I)V
.line 3827
:cond_8
move-object/from16 v0, p0
move/from16 v1, v18
invoke-direct {v0, v1, v8, v13}, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->findRestoredWidgetLocked(ILcom/android/server/appwidget/AppWidgetServiceImpl$Host;Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;)Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
move-result-object v12
.line 3828
.local v12, "id":Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
if-nez v12, :cond_a
.line 3829
new-instance v12, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
.end local v12 # "id":Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
const/16 v27, 0x0
move-object/from16 v0, v27
invoke-direct {v12, v0}, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;-><init>(Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;)V
.line 3830
.restart local v12 # "id":Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
move-object/from16 v27, v0
move-object/from16 v0, v27
move/from16 v1, p3
invoke-static {v0, v1}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-wrap2(Lcom/android/server/appwidget/AppWidgetServiceImpl;I)I
move-result v27
move/from16 v0, v27
iput v0, v12, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->appWidgetId:I
.line 3831
move/from16 v0, v18
iput v0, v12, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->restoredId:I
.line 3832
move-object/from16 v0, p0
invoke-direct {v0, v14}, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->parseWidgetIdOptions(Lorg/xmlpull/v1/XmlPullParser;)Landroid/os/Bundle;
move-result-object v27
move-object/from16 v0, v27
iput-object v0, v12, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->options:Landroid/os/Bundle;
.line 3833
iput-object v8, v12, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->host:Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
.line 3834
iget-object v0, v12, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->host:Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
move-object/from16 v27, v0
move-object/from16 v0, v27
iget-object v0, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;->widgets:Ljava/util/ArrayList;
move-object/from16 v27, v0
move-object/from16 v0, v27
invoke-virtual {v0, v12}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z
.line 3835
iput-object v13, v12, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->provider:Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
.line 3836
iget-object v0, v12, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->provider:Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
move-object/from16 v27, v0
if-eqz v27, :cond_9
.line 3837
iget-object v0, v12, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->provider:Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
move-object/from16 v27, v0
move-object/from16 v0, v27
iget-object v0, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->widgets:Ljava/util/ArrayList;
move-object/from16 v27, v0
move-object/from16 v0, v27
invoke-virtual {v0, v12}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z
.line 3840
:cond_9
const-string/jumbo v27, "BackupRestoreController"
new-instance v29, Ljava/lang/StringBuilder;
invoke-direct/range {v29 .. v29}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v30, "New restored id "
invoke-virtual/range {v29 .. v30}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v29
move-object/from16 v0, v29
move/from16 v1, v18
invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v29
.line 3841
const-string/jumbo v30, " now "
.line 3840
invoke-virtual/range {v29 .. v30}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v29
move-object/from16 v0, v29
invoke-virtual {v0, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;
move-result-object v29
invoke-virtual/range {v29 .. v29}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v29
move-object/from16 v0, v27
move-object/from16 v1, v29
invoke-static {v0, v1}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
.line 3843
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
move-object/from16 v27, v0
move-object/from16 v0, v27
invoke-virtual {v0, v12}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->addWidgetLocked(Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;)V
.line 3845
:cond_a
iget-object v0, v12, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->provider:Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
move-object/from16 v27, v0
move-object/from16 v0, v27
iget-object v0, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;->info:Landroid/appwidget/AppWidgetProviderInfo;
move-object/from16 v27, v0
if-eqz v27, :cond_b
.line 3846
iget-object v0, v12, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->provider:Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
move-object/from16 v27, v0
.line 3847
iget v0, v12, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->appWidgetId:I
move/from16 v29, v0
.line 3846
move-object/from16 v0, p0
move-object/from16 v1, v27
move/from16 v2, v18
move/from16 v3, v29
invoke-direct {v0, v1, v2, v3}, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->stashProviderRestoreUpdateLocked(Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;II)V
.line 3851
:goto_2
iget-object v0, v12, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->host:Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
move-object/from16 v27, v0
iget v0, v12, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->appWidgetId:I
move/from16 v29, v0
move-object/from16 v0, p0
move-object/from16 v1, v27
move/from16 v2, v18
move/from16 v3, v29
invoke-direct {v0, v1, v2, v3}, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->stashHostRestoreUpdateLocked(Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;II)V
.line 3854
const-string/jumbo v27, "BackupRestoreController"
new-instance v29, Ljava/lang/StringBuilder;
invoke-direct/range {v29 .. v29}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v30, " instance: "
invoke-virtual/range {v29 .. v30}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v29
move-object/from16 v0, v29
move/from16 v1, v18
invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v29
.line 3855
const-string/jumbo v30, " -> "
.line 3854
invoke-virtual/range {v29 .. v30}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v29
.line 3855
iget v0, v12, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->appWidgetId:I
move/from16 v30, v0
.line 3854
invoke-virtual/range {v29 .. v30}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v29
.line 3856
const-string/jumbo v30, " :: p="
.line 3854
invoke-virtual/range {v29 .. v30}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v29
.line 3856
iget-object v0, v12, Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;->provider:Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;
move-object/from16 v30, v0
.line 3854
invoke-virtual/range {v29 .. v30}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;
move-result-object v29
invoke-virtual/range {v29 .. v29}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v29
move-object/from16 v0, v27
move-object/from16 v1, v29
invoke-static {v0, v1}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
goto/16 :goto_0
.line 3849
:cond_b
const-string/jumbo v27, "BackupRestoreController"
new-instance v29, Ljava/lang/StringBuilder;
invoke-direct/range {v29 .. v29}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v30, "Missing provider for restored widget "
invoke-virtual/range {v29 .. v30}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v29
move-object/from16 v0, v29
invoke-virtual {v0, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;
move-result-object v29
invoke-virtual/range {v29 .. v29}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v29
move-object/from16 v0, v27
move-object/from16 v1, v29
invoke-static {v0, v1}, Landroid/util/Slog;->w(Ljava/lang/String;Ljava/lang/String;)I
:try_end_a
.catchall {:try_start_a .. :try_end_a} :catchall_0
goto :goto_2
.line 3871
.end local v8 # "host":Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;
.end local v10 # "hostIndex":I
.end local v12 # "id":Lcom/android/server/appwidget/AppWidgetServiceImpl$Widget;
.end local v14 # "parser":Lorg/xmlpull/v1/XmlPullParser;
.end local v16 # "prov":Ljava/lang/String;
.end local v17 # "restoredHosts":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$Host;>;"
.end local v18 # "restoredId":I
.end local v19 # "restoredProviders":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Lcom/android/server/appwidget/AppWidgetServiceImpl$Provider;>;"
.end local v21 # "tag":Ljava/lang/String;
.end local v22 # "type":I
:catchall_1
move-exception v27
.line 3872
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController;->this$0:Lcom/android/server/appwidget/AppWidgetServiceImpl;
move-object/from16 v28, v0
move-object/from16 v0, v28
move/from16 v1, p3
invoke-static {v0, v1}, Lcom/android/server/appwidget/AppWidgetServiceImpl;->-wrap12(Lcom/android/server/appwidget/AppWidgetServiceImpl;I)V
.line 3871
throw v27
.end method
| {
"content_hash": "1615d834e04545117a86a21892bc6fe7",
"timestamp": "",
"source": "github",
"line_count": 3701,
"max_line_length": 315,
"avg_line_length": 31.58389624425831,
"alnum_prop": 0.7153269684837286,
"repo_name": "libnijunior/patchrom_bullhead",
"id": "840a34967ab02df8fab13ba12bf8d46dc6400e10",
"size": "116892",
"binary": false,
"copies": "2",
"ref": "refs/heads/mtc20k",
"path": "services.jar.out/smali/com/android/server/appwidget/AppWidgetServiceImpl$BackupRestoreController.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "3334"
},
{
"name": "Groff",
"bytes": "8687"
},
{
"name": "Makefile",
"bytes": "2098"
},
{
"name": "Shell",
"bytes": "26769"
},
{
"name": "Smali",
"bytes": "172301453"
}
],
"symlink_target": ""
} |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Payrolls extends CI_Model {
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function get_search($limit, $start,$search_term)
{
$this->db->limit($limit, $start);
$this ->db->select('*');
$this ->db->from('account');
$this->db->like('L_name',$search_term);
$this->db->or_like('F_name',$search_term);
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
public function search_count($search_term)
{
$this->db->from('account');
$this->db->like('L_name',$search_term);
$this->db->or_like('F_name',$search_term);
return $this->db->count_all_results();
}
public function save($pay_record)
{
$this->db->insert('payroll',$pay_record);
}
public function pay_history($id)
{
$this->db->select('*');
$this->db->from('payroll');
$this->db->where('account_id',$id);
$this->db->order_by('date');
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
} | {
"content_hash": "18095ed1f990f891f76542c9b5f531ff",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 63,
"avg_line_length": 20.65573770491803,
"alnum_prop": 0.569047619047619,
"repo_name": "marjomlg/AdminTool",
"id": "3b276e6e7367007afa9d29510037532f699c53b4",
"size": "1260",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "phpmongodb/pai_sys/application/models/payrolls.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1231"
},
{
"name": "C",
"bytes": "2283"
},
{
"name": "CSS",
"bytes": "1310260"
},
{
"name": "HTML",
"bytes": "11775821"
},
{
"name": "JavaScript",
"bytes": "590379"
},
{
"name": "Makefile",
"bytes": "467"
},
{
"name": "PHP",
"bytes": "5489232"
}
],
"symlink_target": ""
} |
<?php
namespace app\modules\main\widgets\review;
use common\components\AssetBundle;
/**
* Class ReviewAsset
* Ассет для добавления отзыва
* @package app\modules\main\widgets\review
* @author Chernyavsky Denis <[email protected]>
*/
class ReviewAsset extends AssetBundle
{
/**
* @inheritdoc
*/
public $js = [
'js/script.js',
];
/**
* @inheritdoc
*/
public $jsMin = [
'js/script.min.js',
];
/**
* @inheritdoc
*/
public $depends = [
'yii\web\JqueryAsset',
];
/**
* @inheritdoc
*/
public function init()
{
$this->sourcePath = __DIR__ . "/assets";
parent::init();
}
} | {
"content_hash": "fe8e762629a9857c9af9cee425259f7f",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 53,
"avg_line_length": 14.022727272727273,
"alnum_prop": 0.6191247974068071,
"repo_name": "webadmin87/rzwebsys7",
"id": "fa5c3a71b22e3ba9f64d6ff4c0969bd33c6cbaef",
"size": "641",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/modules/main/widgets/review/ReviewAsset.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "436"
},
{
"name": "Batchfile",
"bytes": "1552"
},
{
"name": "CSS",
"bytes": "71552"
},
{
"name": "JavaScript",
"bytes": "80288"
},
{
"name": "PHP",
"bytes": "949988"
}
],
"symlink_target": ""
} |
template "/opt/local/etc/dhcp/dhcpd.conf" do
source "dhcpd.conf.erb"
user "root"
group "root"
mode 0644
end
manifest = "/opt/local/share/smf/isc-dhcpd/manifest.xml"
template manifest do
source "manifest.xml.erb"
user "root"
group "root"
mode 0644
notifies :run, "execute[dhcpd_manifest]"
end
execute "dhcpd_manifest" do
command "svccfg import #{manifest}"
action :nothing
notifies :restart, "service[dhcpd]"
end
service "dhcpd" do
service_name "dhcpd"
supports :restart => true, :reload => false, :status => true
action [:enable, :start]
end
| {
"content_hash": "886875f30f6da6d90e57bdfb2252f660",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 62,
"avg_line_length": 20.571428571428573,
"alnum_prop": 0.6979166666666666,
"repo_name": "AlainODea-cookbooks/hackish-dhcp",
"id": "82410fe9c85f43e559fbb37a0fa6dacff08e7b29",
"size": "1208",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "recipes/default.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ruby",
"bytes": "1492"
}
],
"symlink_target": ""
} |
package io.cdap.plugin.sfmc.source;
import com.exacttarget.fuelsdk.ETSdkException;
import com.google.common.annotations.VisibleForTesting;
import io.cdap.cdap.api.annotation.Description;
import io.cdap.cdap.api.annotation.Macro;
import io.cdap.cdap.api.annotation.Name;
import io.cdap.cdap.api.plugin.PluginConfig;
import io.cdap.cdap.etl.api.FailureCollector;
import io.cdap.plugin.common.Constants;
import io.cdap.plugin.common.IdUtils;
import io.cdap.plugin.sfmc.source.util.MarketingCloudConstants;
import io.cdap.plugin.sfmc.source.util.SourceObject;
import io.cdap.plugin.sfmc.source.util.SourceQueryMode;
import io.cdap.plugin.sfmc.source.util.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
/**
* Configuration for the {@link MarketingCloudSource}.
*/
public class MarketingCloudSourceConfig extends PluginConfig {
private static final Logger LOG = LoggerFactory.getLogger(MarketingCloudSourceConfig.class);
@Name(Constants.Reference.REFERENCE_NAME)
@Description("This will be used to uniquely identify this source for lineage, annotating metadata, etc.")
private String referenceName;
@Name(MarketingCloudConstants.PROPERTY_QUERY_MODE)
@Macro
@Description("Mode of data retrieval. The mode can be one of two values: "
+ "`Multi Object` - will allow user to fetch data for multiple data extensions, "
+ "`Single Object` - will allow user to fetch data for single data extension.")
private String queryMode;
@Name(MarketingCloudConstants.PROPERTY_OBJECT_NAME)
@Macro
@Nullable
@Description("Specify the object for which data to be fetched. This can be one of following values: " +
"`Data Extension` - will allow user to fetch data for a single Data Extension object, " +
"`Campaign` - will allow user to fetch data for Campaign object, " +
"`Email` - will allow user to fetch data for Email object, " +
"`Mailing List` - will allow user to fetch data for Mailing List object. " +
"Note, this value will be ignored if the Mode is set to `Multi Object`.")
private String objectName;
@Name(MarketingCloudConstants.PROPERTY_DATA_EXTENSION_KEY)
@Macro
@Nullable
@Description("Specify the data extension key from which data to be fetched. Note, this value will be ignored in " +
"following two cases: 1. If the Mode is set to `Multi Object`, 2. If the selected object name is other than " +
"`Data Extension`.")
private String dataExtensionKey;
@Name(MarketingCloudConstants.PROPERTY_OBJECT_LIST)
@Macro
@Nullable
@Description("Specify the comma-separated list of objects for which data to be fetched; for example: " +
"'Object1,Object2'. This can be one or more values from following possible values: " +
"`Data Extension` - will allow user to fetch data for a single Data Extension object, " +
"`Campaign` - will allow user to fetch data for Campaign object, " +
"`Email` - will allow user to fetch data for Email object, " +
"`Mailing List` - will allow user to fetch data for Mailing List object. " +
"Note, this value will be ignored if the Mode is set to `Single Object`.")
private String objectList;
@Name(MarketingCloudConstants.PROPERTY_DATA_EXTENSION_KEY_LIST)
@Macro
@Nullable
@Description("Specify the data extension keys from which data to be fetched; for example: 'Key1,Key2'. " +
"Note, this value will be ignored in following two cases: 1. If the Mode is set to `Single Object`, " +
"2. If the selected object list does not contain `Data Extension` as one of the objects.")
private String dataExtensionKeys;
@Name(MarketingCloudConstants.PROPERTY_TABLE_NAME_FIELD)
@Macro
@Nullable
@Description("The name of the field that holds the object name to which the data belongs to. Must not be the name " +
"of any column for any of the objects that will be read. Defaults to `tablename`. In case of `Data Extension` " +
"object, this field will have value in `dataextension_[Data Extension Key]` format. Note, the Table name field " +
"value will be ignored if the Mode is set to `Single Object`.")
private String tableNameField;
@Name(MarketingCloudConstants.PROPERTY_FILTER)
@Macro
@Nullable
@Description("The WHERE clause used to filter data from Marketing cloud objects.")
private String filter;
@Name(MarketingCloudConstants.PROPERTY_CLIENT_ID)
@Macro
@Description("OAuth2 client ID associated with an installed package in the Salesforce Marketing Cloud.")
private String clientId;
@Name(MarketingCloudConstants.PROPERTY_CLIENT_SECRET)
@Macro
@Description("OAuth2 client secret associated with an installed package in the Salesforce Marketing Cloud.")
private String clientSecret;
@Name(MarketingCloudConstants.PROPERTY_API_ENDPOINT)
@Macro
@Description("The REST API Base URL associated for the Server-to-Server API integration. " +
"For example, https://instance.rest.marketingcloudapis.com/")
private String restEndpoint;
@Name(MarketingCloudConstants.PROPERTY_AUTH_API_ENDPOINT)
@Macro
@Description("Authentication Base URL associated for the Server-to-Server API integration. " +
"For example, https://instance.auth.marketingcloudapis.com/")
private String authEndpoint;
@Name(MarketingCloudConstants.PROPERTY_SOAP_API_ENDPOINT)
@Macro
@Description("The SOAP Endpoint URL associated for the Server-to-Server API integration. " +
"For example, https://instance.soap.marketingcloudapis.com/Service.asmx")
private String soapEndpoint;
/**
* Constructor for MarketingCloudSourceConfig object.
*
* @param referenceName The reference name
* @param queryMode The query mode
* @param objectName The object name to be fetched from Salesforce Marketing Cloud
* @param dataExtensionKey The data extension key to be fetched from Salesforce Marketing Cloud
* @param objectList The list of objects to be fetched from Salesforce Marketing Cloud
* @param dataExtensionKeys The list of data extension keys to be fetched from Salesforce Marketing Cloud
* @param tableNameField The field name to hold the table name value
* @param clientId The Salesforce Marketing Cloud Client Id
* @param clientSecret The Salesforce Marketing Cloud Client Secret
* @param restEndpoint The REST API endpoint for Salesforce Marketing Cloud
* @param authEndpoint The AUTH API endpoint for Salesforce Marketing Cloud
* @param soapEndpoint The SOAP API endpoint for Salesforce Marketing Cloud
*/
public MarketingCloudSourceConfig(String referenceName, String queryMode, @Nullable String objectName,
@Nullable String dataExtensionKey, @Nullable String objectList,
@Nullable String dataExtensionKeys, @Nullable String tableNameField,
@Nullable String filter, String clientId, String clientSecret,
String restEndpoint, String authEndpoint, String soapEndpoint) {
this.referenceName = referenceName;
this.queryMode = queryMode;
this.objectName = objectName;
this.dataExtensionKey = dataExtensionKey;
this.objectList = objectList;
this.dataExtensionKeys = dataExtensionKeys;
this.tableNameField = tableNameField;
this.filter = filter;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.restEndpoint = restEndpoint;
this.authEndpoint = authEndpoint;
this.soapEndpoint = soapEndpoint;
}
public String getReferenceName() {
return referenceName;
}
/**
* Returns the query mode chosen.
*
* @param collector The failure collector to collect the errors
* @return An instance of SourceQueryMode
*/
public SourceQueryMode getQueryMode(FailureCollector collector) {
SourceQueryMode mode = getQueryMode();
if (mode != null) {
return mode;
}
collector.addFailure("Unsupported query mode value: " + queryMode,
String.format("Supported modes are: %s", SourceQueryMode.getSupportedModes()))
.withConfigProperty(MarketingCloudConstants.PROPERTY_QUERY_MODE);
collector.getOrThrowException();
return null;
}
/**
* Returns the query mode chosen.
*
* @return An instance of SourceQueryMode
*/
public SourceQueryMode getQueryMode() {
Optional<SourceQueryMode> sourceQueryMode = SourceQueryMode.fromValue(queryMode);
return sourceQueryMode.isPresent() ? sourceQueryMode.get() : null;
}
/**
* Returns selected object.
*
* @param collector The failure collector to collect the errors
* @return An instance of SourceObject
*/
public SourceObject getObject(FailureCollector collector) {
SourceObject sourceObject = getObject();
if (sourceObject != null) {
return sourceObject;
}
collector.addFailure("Unsupported object value: " + objectName,
String.format("Supported objects are: %s", SourceObject.getSupportedObjects()))
.withConfigProperty(MarketingCloudConstants.PROPERTY_OBJECT_NAME);
collector.getOrThrowException();
return null;
}
@Nullable
public SourceObject getObject() {
return getSourceObject(objectName, filter);
}
@Nullable
public String getDataExtensionKey() {
return dataExtensionKey;
}
/**
* Returns list of selected objects.
*
* @param collector The failure collector to collect the errors
* @return The list of SourceObject
*/
public List<SourceObject> getObjectList(FailureCollector collector) {
List<String> objects = Util.splitToList(objectList, ',');
List<SourceObject> sourceObjects = new ArrayList<>();
for (String object : objects) {
SourceObject sourceObject = getSourceObject(object, filter);
if (sourceObject == null) {
collector.addFailure("Unsupported object value: " + object,
String.format("Supported objects are: %s", SourceObject.getSupportedObjects()))
.withConfigProperty(MarketingCloudConstants.PROPERTY_OBJECT_LIST);
break;
}
sourceObjects.add(sourceObject);
}
return sourceObjects;
}
/**
* Returns list of selected objects.
*
* @return The list of SourceObject
*/
@Nullable
public List<SourceObject> getObjectList() {
List<String> objects = Util.splitToList(objectList, ',');
List<SourceObject> sourceObjects = new ArrayList<>();
for (String object : objects) {
SourceObject sourceObject = getSourceObject(object, filter);
if (sourceObject == null) {
continue;
}
sourceObjects.add(sourceObject);
}
return sourceObjects;
}
@Nullable
public String getDataExtensionKeys() {
return dataExtensionKeys;
}
@Nullable
public String getTableNameField() {
return tableNameField;
}
@Nullable
public String getFilter() {
return filter;
}
public String getClientId() {
return clientId;
}
public String getClientSecret() {
return clientSecret;
}
public String getRestEndpoint() {
return restEndpoint;
}
public String getAuthEndpoint() {
return authEndpoint;
}
public String getSoapEndpoint() {
return soapEndpoint;
}
/**
* Validates {@link MarketingCloudSourceConfig} instance.
*/
public void validate(FailureCollector collector) {
//Validates the given referenceName to consists of characters allowed to represent a dataset.
IdUtils.validateReferenceName(referenceName, collector);
validateCredentials(collector);
validateQueryMode(collector);
validateFilter(collector);
}
private SourceObject getSourceObject(String objectName, String filter) {
Optional<SourceObject> sourceObject = SourceObject.fromValue(objectName);
if (sourceObject.isPresent()) {
SourceObject obj = sourceObject.get();
obj.setFilter(filter);
return obj;
} else {
return null;
}
}
private void validateCredentials(FailureCollector collector) {
if (!shouldConnect()) {
return;
}
if (Util.isNullOrEmpty(clientId)) {
collector.addFailure("Client ID must be specified.", null)
.withConfigProperty(MarketingCloudConstants.PROPERTY_CLIENT_ID);
}
if (Util.isNullOrEmpty(clientSecret)) {
collector.addFailure("Client Secret must be specified.", null)
.withConfigProperty(MarketingCloudConstants.PROPERTY_CLIENT_SECRET);
}
if (Util.isNullOrEmpty(restEndpoint)) {
collector.addFailure(" REST Endpoint must be specified.", null)
.withConfigProperty(MarketingCloudConstants.PROPERTY_API_ENDPOINT);
}
if (Util.isNullOrEmpty(authEndpoint)) {
collector.addFailure("Auth Endpoint must be specified.", null)
.withConfigProperty(MarketingCloudConstants.PROPERTY_AUTH_API_ENDPOINT);
}
if (Util.isNullOrEmpty(soapEndpoint)) {
collector.addFailure("Soap Endpoint must be specified.", null)
.withConfigProperty(MarketingCloudConstants.PROPERTY_SOAP_API_ENDPOINT);
}
collector.getOrThrowException();
validateSalesforceConnection(collector);
}
@VisibleForTesting
void validateSalesforceConnection(FailureCollector collector) {
try {
MarketingCloudClient.create(clientId, clientSecret, authEndpoint, soapEndpoint);
} catch (ETSdkException e) {
collector.addFailure("Unable to connect to Salesforce Instance.",
"Ensure properties like Client ID, Client Secret, API Endpoint " +
", Soap Endpoint, Auth Endpoint are correct.")
.withConfigProperty(MarketingCloudConstants.PROPERTY_CLIENT_ID)
.withConfigProperty(MarketingCloudConstants.PROPERTY_CLIENT_SECRET)
.withConfigProperty(MarketingCloudConstants.PROPERTY_API_ENDPOINT)
.withConfigProperty(MarketingCloudConstants.PROPERTY_AUTH_API_ENDPOINT)
.withConfigProperty(MarketingCloudConstants.PROPERTY_SOAP_API_ENDPOINT)
.withStacktrace(e.getStackTrace());
}
}
private void validateQueryMode(FailureCollector collector) {
//according to query mode check if either object name / object list exists or not
if (containsMacro(MarketingCloudConstants.PROPERTY_QUERY_MODE)) {
return;
}
SourceQueryMode mode = getQueryMode(collector);
if (mode == SourceQueryMode.MULTI_OBJECT) {
validateMultiObjectQueryMode(collector);
} else {
validateSingleObjectQueryMode(collector);
}
}
private void validateMultiObjectQueryMode(FailureCollector collector) {
if (containsMacro(MarketingCloudConstants.PROPERTY_OBJECT_LIST)
|| containsMacro(MarketingCloudConstants.PROPERTY_DATA_EXTENSION_KEY_LIST)
|| containsMacro(MarketingCloudConstants.PROPERTY_TABLE_NAME_FIELD)) {
return;
}
List<SourceObject> objects = getObjectList(collector);
collector.getOrThrowException();
if (objects.isEmpty()) {
collector.addFailure("At least 1 Object must be specified.", null)
.withConfigProperty(MarketingCloudConstants.PROPERTY_OBJECT_LIST);
}
if (objects.contains(SourceObject.DATA_EXTENSION)) {
List<String> dataExtensionKeyList = Util.splitToList(getDataExtensionKeys(), ',');
if (dataExtensionKeyList.isEmpty()) {
collector.addFailure("At least 1 Data Extension Key must be specified.", null)
.withConfigProperty(MarketingCloudConstants.PROPERTY_DATA_EXTENSION_KEY_LIST);
}
}
if (Util.isNullOrEmpty(tableNameField)) {
collector.addFailure("Table name field must be specified.", null)
.withConfigProperty(MarketingCloudConstants.PROPERTY_TABLE_NAME_FIELD);
}
}
private void validateSingleObjectQueryMode(FailureCollector collector) {
if (containsMacro(MarketingCloudConstants.PROPERTY_OBJECT_NAME)
|| containsMacro(MarketingCloudConstants.PROPERTY_DATA_EXTENSION_KEY)) {
return;
}
SourceObject object = getObject(collector);
if (object == SourceObject.DATA_EXTENSION && Util.isNullOrEmpty(dataExtensionKey)) {
collector.addFailure("Data Extension Key must be specified.", null)
.withConfigProperty(MarketingCloudConstants.PROPERTY_DATA_EXTENSION_KEY);
}
}
private void validateFilter(FailureCollector collector) {
if (containsMacro(MarketingCloudConstants.PROPERTY_FILTER) || Util.isNullOrEmpty(filter)) {
return;
}
try {
MarketingCloudClient.validateFilter(filter);
} catch (ETSdkException e) {
collector.addFailure("Filter string is not valid.",
"Check syntax to confirm.")
.withConfigProperty(MarketingCloudConstants.PROPERTY_FILTER)
.withStacktrace(e.getStackTrace());
}
}
/**
* Returns true if Salesforce can be connected to.
*/
public boolean shouldConnect() {
return !containsMacro(MarketingCloudConstants.PROPERTY_CLIENT_ID) &&
!containsMacro(MarketingCloudConstants.PROPERTY_CLIENT_SECRET) &&
!containsMacro(MarketingCloudConstants.PROPERTY_API_ENDPOINT) &&
!containsMacro(MarketingCloudConstants.PROPERTY_AUTH_API_ENDPOINT) &&
!containsMacro(MarketingCloudConstants.PROPERTY_SOAP_API_ENDPOINT);
}
}
| {
"content_hash": "3b1287d1cb9bf49ca6463e4631f0f0eb",
"timestamp": "",
"source": "github",
"line_count": 462,
"max_line_length": 119,
"avg_line_length": 37.55194805194805,
"alnum_prop": 0.7183699348665629,
"repo_name": "data-integrations/salesforce-marketing",
"id": "804de77d66a148bbcff685ba57998020b0bff7ba",
"size": "17946",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/main/java/io/cdap/plugin/sfmc/source/MarketingCloudSourceConfig.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Gherkin",
"bytes": "65789"
},
{
"name": "Java",
"bytes": "313767"
}
],
"symlink_target": ""
} |
namespace Nancy.Tests.Unit.Diagnostics
{
using System;
using System.Collections.Generic;
using System.Linq;
using Nancy.Bootstrapper;
using Nancy.Configuration;
using Nancy.Cryptography;
using Nancy.Culture;
using Nancy.Diagnostics;
using Nancy.Helpers;
using Nancy.Localization;
using Nancy.ModelBinding;
using Nancy.Responses.Negotiation;
using Nancy.Routing;
using Nancy.Routing.Constraints;
using Nancy.Testing;
using Xunit;
//While this directive is redundant, it's required to build on mono 2.x to allow it to resolve the Should* extension methods
public class CustomInteractiveDiagnosticsHookFixture
{
private const string DiagsCookieName = "__ncd";
private readonly CryptographyConfiguration cryptoConfig;
private readonly IObjectSerializer objectSerializer;
public CustomInteractiveDiagnosticsHookFixture()
{
this.cryptoConfig = CryptographyConfiguration.Default;
this.objectSerializer = new DefaultObjectSerializer();
}
private class FakeDiagnostics : IDiagnostics
{
private readonly IEnumerable<IDiagnosticsProvider> diagnosticProviders;
private readonly IRootPathProvider rootPathProvider;
private readonly IRequestTracing requestTracing;
private readonly NancyInternalConfiguration configuration;
private readonly IModelBinderLocator modelBinderLocator;
private readonly IEnumerable<IResponseProcessor> responseProcessors;
private readonly IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints;
private readonly ICultureService cultureService;
private readonly IRequestTraceFactory requestTraceFactory;
private readonly IEnumerable<IRouteMetadataProvider> routeMetadataProviders;
private readonly ITextResource textResource;
private readonly INancyEnvironment environment;
public FakeDiagnostics(
IRootPathProvider rootPathProvider,
IRequestTracing requestTracing,
NancyInternalConfiguration configuration,
IModelBinderLocator modelBinderLocator,
IEnumerable<IResponseProcessor> responseProcessors,
IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints,
ICultureService cultureService,
IRequestTraceFactory requestTraceFactory,
IEnumerable<IRouteMetadataProvider> routeMetadataProviders,
ITextResource textResource,
INancyEnvironment environment)
{
this.diagnosticProviders = (new IDiagnosticsProvider[] { new FakeDiagnosticsProvider() }).ToArray();
this.rootPathProvider = rootPathProvider;
this.requestTracing = requestTracing;
this.configuration = configuration;
this.modelBinderLocator = modelBinderLocator;
this.responseProcessors = responseProcessors;
this.routeSegmentConstraints = routeSegmentConstraints;
this.cultureService = cultureService;
this.requestTraceFactory = requestTraceFactory;
this.routeMetadataProviders = routeMetadataProviders;
this.textResource = textResource;
this.environment = environment;
}
public void Initialize(IPipelines pipelines)
{
DiagnosticsHook.Enable(
pipelines,
this.diagnosticProviders,
this.rootPathProvider,
this.requestTracing,
this.configuration,
this.modelBinderLocator,
this.responseProcessors,
this.routeSegmentConstraints,
this.cultureService,
this.requestTraceFactory,
this.routeMetadataProviders,
this.textResource,
this.environment);
}
}
private class FakeDiagnosticsProvider : IDiagnosticsProvider
{
public string Name
{
get { return "Fake testing provider"; }
}
public string Description
{
get { return "Fake testing provider"; }
}
public object DiagnosticObject
{
get { return this; }
}
}
[Fact]
public void Should_return_main_page_with_valid_auth_cookie()
{
// Given
var bootstrapper = new ConfigurableBootstrapper(with =>
{
with.Configure(env =>
{
env.Diagnostics(
password: "password",
cryptographyConfiguration: this.cryptoConfig);
});
with.EnableAutoRegistration();
with.Diagnostics<FakeDiagnostics>();
});
var browser = new Browser(bootstrapper);
// When
var result = browser.Get(DiagnosticsConfiguration.Default.Path + "/interactive/providers/", with =>
{
with.Cookie(DiagsCookieName, this.GetSessionCookieValue("password"));
});
// Then should see our fake provider and not the default testing provider
result.Body.AsString().ShouldContain("Fake testing provider");
result.Body.AsString().ShouldNotContain("Testing Diagnostic Provider");
}
private string GetSessionCookieValue(string password, DateTime? expiry = null)
{
var salt = DiagnosticsSession.GenerateRandomSalt();
var hash = DiagnosticsSession.GenerateSaltedHash(password, salt);
var session = new DiagnosticsSession
{
Hash = hash,
Salt = salt,
Expiry = expiry.HasValue ? expiry.Value : DateTime.Now.AddMinutes(15),
};
var serializedSession = this.objectSerializer.Serialize(session);
var encryptedSession = this.cryptoConfig.EncryptionProvider.Encrypt(serializedSession);
var hmacBytes = this.cryptoConfig.HmacProvider.GenerateHmac(encryptedSession);
var hmacString = Convert.ToBase64String(hmacBytes);
return string.Format("{1}{0}", encryptedSession, hmacString);
}
}
}
| {
"content_hash": "3cf80a20bc4cabd27e1913d3e54ce287",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 124,
"avg_line_length": 40.8855421686747,
"alnum_prop": 0.5949609547664653,
"repo_name": "wtilton/Nancy",
"id": "123850e68d76011099069be686eff1a9c6534232",
"size": "6789",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Nancy.Tests/Unit/Diagnostics/CustomInteractiveDiagnosticsFixture.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "3767141"
},
{
"name": "CSS",
"bytes": "16121"
},
{
"name": "HTML",
"bytes": "100650"
},
{
"name": "JavaScript",
"bytes": "94374"
},
{
"name": "Liquid",
"bytes": "22091"
},
{
"name": "PowerShell",
"bytes": "3723"
},
{
"name": "Ruby",
"bytes": "14116"
},
{
"name": "Visual Basic",
"bytes": "381"
}
],
"symlink_target": ""
} |
..
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
.. _process:
=================
Nova team process
=================
Nova is always evolving its processes, but it's important to explain why we
have them: so we can all work to ensure that the interactions we need to
happen do happen. The process exists to make productive communication between
all members of our community easier.
OpenStack Wide Patterns
=======================
Nova follows most of the generally adopted norms for OpenStack projects.
You can get more details here:
* https://docs.openstack.org/infra/manual/developers.html
* https://docs.openstack.org/project-team-guide/
If you are new to Nova, please read this first: :ref:`getting_involved`.
Dates overview
==============
For Rocky, please see:
https://wiki.openstack.org/wiki/Nova/Rocky_Release_Schedule
.. note: Throughout this document any link which references the name of a
release cycle in the link can usually be changed to the name of the
current cycle to get up to date information.
Feature Freeze
~~~~~~~~~~~~~~
Feature freeze primarily provides a window of time to help the horizontal
teams prepare their items for release, while giving developers time to
focus on stabilising what is currently in master, and encouraging users
and packagers to perform tests (automated, and manual) on the release, to
spot any major bugs.
The Nova release process is aligned with the `development cycle schedule
<https://docs.openstack.org/project-team-guide/release-management.html#typical-development-cycle-schedule>`_
used by many OpenStack projects, including the following steps.
- Feature Proposal Freeze
- make sure all code is up for review
- so we can optimise for completed features, not lots of half
completed features
- Feature Freeze
- make sure all feature code is merged
- String Freeze
- give translators time to translate all our strings
.. note::
debug logs are no longer translated
- Dependency Freeze
- time to co-ordinate the final list of dependencies, and give packagers
time to package them
- generally it is also quite destabilising to take upgrades (beyond
bug fixes) this late
As with all processes here, there are exceptions. The exceptions at
this stage need to be discussed with the horizontal teams that might be
affected by changes beyond this point, and as such are discussed with
one of the OpenStack release managers.
Spec and Blueprint Approval Freeze
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This is a (mostly) Nova specific process.
Why we have a Spec Freeze:
- specs take a long time to review and reviewing specs throughout the cycle
distracts from code reviews
- keeping specs "open" and being slow at reviewing them (or just
ignoring them) annoys the spec submitters
- we generally have more code submitted that we can review, this time
bounding is a useful way to limit the number of submissions
By the freeze date, we expect all blueprints that will be approved for the
cycle to be listed on launchpad and all relevant specs to be merged.
For Rocky, blueprints can be found at
https://blueprints.launchpad.net/nova/rocky and specs at
https://specs.openstack.org/openstack/nova-specs/specs/rocky/index.html
Starting with Liberty, we are keeping a backlog open for submission at all
times.
.. note::
The focus is on accepting and agreeing problem statements as being in scope,
rather than queueing up work items for the next release. We are still
working on a new lightweight process to get out of the backlog and approved
for a particular release. For more details on backlog specs, please see:
http://specs.openstack.org/openstack/nova-specs/specs/backlog/index.html
There can be exceptions, usually it's an urgent feature request that
comes up after the initial deadline. These will generally be discussed
at the weekly Nova meeting, by adding the spec or blueprint to discuss
in the appropriate place in the meeting agenda here (ideally make
yourself available to discuss the blueprint, or alternatively make your
case on the ML before the meeting):
https://wiki.openstack.org/wiki/Meetings/Nova#Agenda_for_next_meeting
Non-priority Feature Freeze
~~~~~~~~~~~~~~~~~~~~~~~~~~~
This is a Nova specific process.
This only applies to low priority blueprints in this list:
https://blueprints.launchpad.net/nova/rocky
We currently have a very finite amount of review bandwidth. In order to
make code review time for the agreed community wide priorities, we have
to not do some other things. In each cycle, milestones are used to bound
when certain types of work will be active and reviewed and to avoid crushing
the gate with too much code near the end of the cycle.
For example, in the Liberty cycle, we reserved the liberty-3 milestone for
priority features and bug fixes and did not merge any non-priority things
during liberty-3. This meant that liberty-2 was the "Feature Freeze" for
blueprints that were not a priority for the Liberty cycle.
You can see the list of priorities for each release:
http://specs.openstack.org/openstack/nova-specs/#priorities
For things that are very close to merging, it's possible to request an
exception for one week after the freeze date, given the patches get
enough +2s from the core team to get the code merged. But we expect this
list to be zero, if everything goes to plan (no massive gate failures,
etc). For history of the process see:
http://lists.openstack.org/pipermail/openstack-dev/2015-July/070920.html
Exception process:
- Please add request in here:
https://etherpad.openstack.org/p/rocky-nova-non-priority-feature-freeze
(ideally with core reviewers to sponsor your patch, normally the
folks who have already viewed those patches)
- make sure you make your request before the end of the feature freeze
exception period
- nova-drivers will meet to decide what gets an exception (for some history
see:
http://lists.openstack.org/pipermail/openstack-dev/2015-February/056208.html)
- an initial list of exceptions (probably just a PTL compiled list at
that point) will be available for discussion during the next Nova meeting
- the aim is to merge the code for all exceptions early in the following week
Alternatives:
- It was hoped to make this a continuous process using "slots" to
control what gets reviewed, but this was rejected by the community
when it was last discussed. There is hope this can be resurrected to
avoid the "lumpy" nature of this process.
- Currently the runways/kanban ideas are blocked on us adopting
something like phabricator that could support such workflows
String Freeze
~~~~~~~~~~~~~
String Freeze provides an opportunity for translators to translate user-visible
messages to a variety of languages. By not changing strings after the date of
the string freeze, the job of the translators is made a bit easier. For more
information on string and other OpenStack-wide release processes see `the
release management docs
<http://docs.openstack.org/project-team-guide/release-management.html>`_.
How do I get my code merged?
============================
OK, so you are new to Nova, and you have been given a feature to
implement. How do I make that happen?
You can get most of your questions answered here:
- https://docs.openstack.org/infra/manual/developers.html
But let's put a Nova specific twist on things...
Overview
~~~~~~~~
.. image:: /_static/images/nova-spec-process.svg
:alt: Flow chart showing the Nova bug/feature process
Where do you track bugs?
~~~~~~~~~~~~~~~~~~~~~~~~
We track bugs here:
- https://bugs.launchpad.net/nova
If you fix an issue, please raise a bug so others who spot that issue
can find the fix you kindly created for them.
Also before submitting your patch it's worth checking to see if someone
has already fixed it for you (Launchpad helps you with that, at little,
when you create the bug report).
When do I need a blueprint vs a spec?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For more details see:
- https://docs.openstack.org/nova/latest/contributor/blueprints.html
To understand this question, we need to understand why blueprints and
specs are useful.
But here is the rough idea:
- if it needs a spec, it will need a blueprint.
- if it's an API change, it needs a spec.
- if it's a single small patch that touches a small amount of code,
with limited deployer and doc impact, it probably doesn't need a
spec.
If you are unsure, please ask johnthetubaguy on IRC, or one of the other
nova-drivers.
How do I get my blueprint approved?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
So you need your blueprint approved? Here is how:
- if you don't need a spec, please add a link to your blueprint to the
agenda for the next nova meeting:
https://wiki.openstack.org/wiki/Meetings/Nova
- be sure your blueprint description has enough context for the
review in that meeting.
- if you need a spec, then please submit a nova-spec for review, see:
https://docs.openstack.org/infra/manual/developers.html
Got any more questions? Contact johnthetubaguy or one of the other
nova-specs-core who are awake at the same time as you. IRC is best as
you will often get an immediate response, if they are too busy send
him/her an email.
How do I get a procedural -2 removed from my patch?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When feature freeze hits, any patches for blueprints that are still in review
get a procedural -2 to stop them merging. In Nova a blueprint is only approved
for a single release. To have the -2 removed, you need to get the blueprint
approved for the current release (see `How do I get my blueprint approved?`_).
Why are the reviewers being mean to me?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Code reviews take intense concentration and a lot of time. This tends to
lead to terse responses with very little preamble or nicety. That said,
there's no excuse for being actively rude or mean. OpenStack has a Code
of Conduct (https://www.openstack.org/legal/community-code-of-conduct/)
and if you feel this has been breached please raise the matter
privately. Either with the relevant parties, the PTL or failing those,
the OpenStack Foundation.
That said, there are many objective reasons for applying a -1 or -2 to a
patch:
- Firstly and simply, patches must address their intended purpose
successfully.
- Patches must not have negative side-effects like wiping the database
or causing a functional regression. Usually removing anything,
however tiny, requires a deprecation warning be issued for a cycle.
- Code must be maintainable, that is it must adhere to coding standards
and be as readable as possible for an average OpenStack developer
(we acknowledge that this person is not easy to define).
- Patches must respect the direction of the project, for example they
should not make approved specs substantially more difficult to
implement.
- Release coordinators need the correct process to be followed so scope
can be tracked accurately. Bug fixes require bugs, features require
blueprints and all but the simplest features require specs. If there
is a blueprint, it must be approved for the release/milestone the
patch is attempting to merge into.
Please particularly bear in mind that a -2 does not mean "never ever"
nor does it mean "your idea is bad and you are dumb". It simply means
"do not merge today". You may need to wait some time, rethink your
approach or even revisit the problem definition but there is almost
always some way forward. The core who applied the -2 should tell you
what you need to do.
My code review seems stuck, what can I do?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
First and foremost - address any -1s and -2s! The review load on Nova is
high enough that patches with negative reviews often get filtered out
entirely. A few tips:
- Be precise. Ensure you're not talking at cross purposes.
- Try to understand where the reviewer is coming from. They may have a
very different perspective and/or use-case to you.
- If you don't understand the problem, ask them to explain - this is
common and helpful behaviour.
- Be positive. Everyone's patches have issues, including core
reviewers. No-one cares once the issues are fixed.
- Try not to flip-flop. When two reviewers are pulling you in different
directions, stop pushing code and negotiate the best way forward.
- If the reviewer does not respond to replies left on the patchset,
reach out to them on IRC or email. If they still don't respond, you
can try to ask their colleagues if they're on holiday (or simply
wait). Finally, you can ask for mediation in the Nova meeting by
adding it to the agenda
(https://wiki.openstack.org/wiki/Meetings/Nova). This is also what
you should do if you are unable to negotiate a resolution to an
issue.
Secondly, Nova is a big project, be aware of the average wait times:
http://russellbryant.net/openstack-stats/nova-openreviews.html
Eventually you should get some +1s from people working through the
review queue. Expect to get -1s as well. You can ask for reviews within
your company, 1-2 are useful (not more), especially if those reviewers
are known to give good reviews. You can spend some time while you wait
reviewing other people's code - they may reciprocate and you may learn
something (:ref:`Why do code reviews when I'm not core? <why_plus1>`).
If you've waited an appropriate amount of time and you haven't had any
+1s, you can ask on IRC for reviews. Please don't ask for core review
straight away, especially not directly (IRC or email). Core reviewer
time is very valuable and gaining some +1s is a good way to show your
patch meets basic quality standards.
Once you have a few +1s, be patient. Remember the average wait times.
You can ask for reviews each week in IRC, it helps to ask when cores are
awake.
Bugs
^^^^
It helps to apply correct tracking information.
- Put "Closes-Bug", "Partial-Bug" or "Related-Bug" in the commit
message tags as necessary.
- If you have to raise a bug in Launchpad first, do it - this helps
someone else find your fix.
- Make sure the bug has the correct priority and tag set:
https://wiki.openstack.org/wiki/Nova/BugTriage#Step_2:_Triage_Tagged_Bugs
Features
^^^^^^^^
Again, it helps to apply correct tracking information. For
blueprint-only features:
- Put your blueprint in the commit message, EG "blueprint
simple-feature".
- Mark the blueprint as NeedsCodeReview if you are finished.
- Maintain the whiteboard on the blueprint so it's easy to understand
which patches need reviews.
- Use a single topic for all related patches. All patches for one
blueprint should share a topic.
For blueprint and spec features, do everything for blueprint-only
features and also:
- If it's a project or subteam priority, add it to:
https://etherpad.openstack.org/p/rocky-nova-priorities-tracking
- Ensure your spec is approved for the current release cycle.
If your code is a project or subteam priority, the cores interested in
that priority might not mind a ping after it has sat with +1s for a
week. If you abuse this privilege, you'll lose respect.
If it's not a priority, your blueprint/spec has been approved for the
cycle and you have been patient, you can raise it during the Nova
meeting. The outcome may be that your spec gets unapproved for the
cycle, so that priority items can take focus. If this happens to you,
sorry - it should not have been approved in the first place, Nova team
bit off more than they could chew, it is their mistake not yours. You
can re-propose it for the next cycle.
If it's not a priority and your spec has not been approved, your code
will not merge this cycle. Please re-propose your spec for the next
cycle.
Nova Process Mission
====================
This section takes a high level look at the guiding principles behind
the Nova process.
Open
~~~~
Our mission is to have:
- Open Source
- Open Design
- Open Development
- Open Community
We have to work out how to keep communication open in all areas. We need
to be welcoming and mentor new people, and make it easy for them to
pickup the knowledge they need to get involved with OpenStack. For more
info on Open, please see: https://wiki.openstack.org/wiki/Open
Interoperable API, supporting a vibrant ecosystem
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
An interoperable API that gives users on-demand access to compute
resources is at the heart of Nova's mission:
https://docs.openstack.org/nova/latest/contributor/project-scope.html#mission
Nova has a vibrant ecosystem of tools built on top of the current Nova
API. All features should be designed to work with all technology
combinations, so the feature can be adopted by our ecosystem. If a new
feature is not adopted by the ecosystem, it will make it hard for your
users to make use of those features, defeating most of the reason to add
the feature in the first place. The microversion system allows users to
isolate themselves
This is a very different aim to being "pluggable" or wanting to expose
all capabilities to end users. At the same time, it is not just a
"lowest common denominator" set of APIs. It should be discoverable which
features are available, and while no implementation details should leak
to the end users, purely admin concepts may need to understand
technology specific details that back the interoperable and more
abstract concepts that are exposed to the end user. This is a hard goal,
and one area we currently don't do well is isolating image creators from
these technology specific details.
Smooth Upgrades
~~~~~~~~~~~~~~~
As part of our mission for a vibrant ecosystem around our APIs, we want
to make it easy for those deploying Nova to upgrade with minimal impact
to their users. Here is the scope of Nova's upgrade support:
- upgrade from any commit, to any future commit, within the same major
release
- only support upgrades between N and N+1 major versions, to reduce
technical debt relating to upgrades
Here are some of the things we require developers to do, to help with
upgrades:
- when replacing an existing feature or configuration option, make it
clear how to transition to any replacement
- deprecate configuration options and features before removing them
- i.e. continue to support and test features for at least one
release before they are removed
- this gives time for operator feedback on any removals
- End User API will always be kept backwards compatible
Interaction goals
~~~~~~~~~~~~~~~~~
When thinking about the importance of process, we should take a look at:
http://agilemanifesto.org
With that in mind, let's look at how we want different members of the
community to interact. Let's start with looking at issues we have tried
to resolve in the past (currently in no particular order). We must:
- have a way for everyone to review blueprints and designs, including
allowing for input from operators and all types of users (keep it
open)
- take care to not expand Nova's scope any more than absolutely
necessary
- ensure we get sufficient focus on the core of Nova so that we can
maintain or improve the stability and flexibility of the overall
codebase
- support any API we release approximately forever. We currently
release every commit, so we're motivated to get the API right the first
time
- avoid low priority blueprints that slow work on high priority work,
without blocking those forever
- focus on a consistent experience for our users, rather than ease of
development
- optimise for completed blueprints, rather than more half completed
blueprints, so we get maximum value for our users out of our review
bandwidth
- focus efforts on a subset of patches to allow our core reviewers to
be more productive
- set realistic expectations on what can be reviewed in a particular
cycle, to avoid sitting in an expensive rebase loop
- be aware of users that do not work on the project full time
- be aware of users that are only able to work on the project at
certain times that may not align with the overall community cadence
- discuss designs for non-trivial work before implementing it, to avoid
the expense of late-breaking design issues
FAQs
====
Why bother with all this process?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We are a large community, spread across multiple timezones, working with
several horizontal teams. Good communication is a challenge and the
processes we have are mostly there to try and help fix some
communication challenges.
If you have a problem with a process, please engage with the community,
discover the reasons behind our current process, and help fix the issues
you are experiencing.
Why don't you remove old process?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We do! For example, in Liberty we stopped trying to predict the
milestones when a feature will land.
As we evolve, it is important to unlearn new habits and explore if
things get better if we choose to optimise for a different set of
issues.
Why are specs useful?
~~~~~~~~~~~~~~~~~~~~~
Spec reviews allow anyone to step up and contribute to reviews, just
like with code. Before we used gerrit, it was a very messy review
process, that felt very "closed" to most people involved in that
process.
As Nova has grown in size, it can be hard to work out how to modify Nova
to meet your needs. Specs are a great way of having that discussion with
the wider Nova community.
For Nova to be a success, we need to ensure we don't break our existing
users. The spec template helps focus the mind on the impact your change
might have on existing users and gives an opportunity to discuss the
best way to deal with those issues.
However, there are some pitfalls with the process. Here are some top
tips to avoid them:
- keep it simple. Shorter, simpler, more decomposed specs are quicker
to review and merge much quicker (just like code patches).
- specs can help with documentation but they are only intended to
document the design discussion rather than document the final code.
- don't add details that are best reviewed in code, it's better to
leave those things for the code review.
If we have specs, why still have blueprints?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We use specs to record the design agreement, we use blueprints to track
progress on the implementation of the spec.
Currently, in Nova, specs are only approved for one release, and must be
re-submitted for each release you want to merge the spec, although that
is currently under review.
Why do we have priorities?
~~~~~~~~~~~~~~~~~~~~~~~~~~
To be clear, there is no "nova dev team manager", we are an open team of
professional software developers, that all work for a variety of (mostly
competing) companies that collaborate to ensure the Nova project is a
success.
Over time, a lot of technical debt has accumulated, because there was a
lack of collective ownership to solve those cross-cutting concerns.
Before the Kilo release, it was noted that progress felt much slower,
because we were unable to get appropriate attention on the architectural
evolution of Nova. This was important, partly for major concerns like
upgrades and stability. We agreed it's something we all care about and
it needs to be given priority to ensure that these things get fixed.
Since Kilo, priorities have been discussed at the summit. This turns in
to a spec review which eventually means we get a list of priorities
here: http://specs.openstack.org/openstack/nova-specs/#priorities
Allocating our finite review bandwidth to these efforts means we have to
limit the reviews we do on non-priority items. This is mostly why we now
have the non-priority Feature Freeze. For more on this, see below.
Blocking a priority effort is one of the few widely acceptable reasons
to block someone adding a feature. One of the great advantages of being
more explicit about that relationship is that people can step up to help
review and/or implement the work that is needed to unblock the feature
they want to get landed. This is a key part of being an Open community.
Why is there a Feature Freeze (and String Freeze) in Nova?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The main reason Nova has a feature freeze is that it allows people
working on docs and translations to sync up with the latest code.
Traditionally this happens at the same time across multiple projects, so
the docs are synced between what used to be called the "integrated
release".
We also use this time period as an excuse to focus our development
efforts on bug fixes, ideally lower risk bug fixes, and improving test
coverage.
In theory, with a waterfall hat on, this would be a time for testing and
stabilisation of the product. In Nova we have a much stronger focus on
keeping every commit stable, by making use of extensive continuous
testing. In reality, we frequently see the biggest influx of fixes in
the few weeks after the release, as distributions do final testing of
the released code.
It is hoped that the work on Feature Classification will lead us to
better understand the levels of testing of different Nova features, so
we will be able to reduce and dependency between Feature Freeze and
regression testing. It is also likely that the move away from
"integrated" releases will help find a more developer friendly approach
to keep the docs and translations in sync.
Why is there a non-priority Feature Freeze in Nova?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We have already discussed why we have priority features.
The rate at which code can be merged to Nova is primarily constrained by
the amount of time able to be spent reviewing code. Given this,
earmarking review time for priority items means depriving it from
non-priority items.
The simplest way to make space for the priority features is to stop
reviewing and merging non-priority features for a whole milestone. The
idea being developers should focus on bug fixes and priority features
during that milestone, rather than working on non-priority features.
A known limitation of this approach is developer frustration. Many
developers are not being given permission to review code, work on bug
fixes or work on priority features, and so feel very unproductive
upstream. An alternative approach of "slots" or "runways" has been
considered, that uses a kanban style approach to regulate the influx of
work onto the review queue. We are yet to get agreement on a more
balanced approach, so the existing system is being continued to ensure
priority items are more likely to get the attention they require.
Why do you still use Launchpad?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We are actively looking for an alternative to Launchpad's bugs and
blueprints.
Originally the idea was to create Storyboard. However development
stalled for a while so interest waned. The project has become more active
recently so it may be worth looking again:
https://storyboard.openstack.org/#!/page/about
When should I submit my spec?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Ideally we want to get all specs for a release merged before the summit.
For things that we can't get agreement on, we can then discuss those at
the summit. There will always be ideas that come up at the summit and
need to be finalised after the summit. This causes a rush which is best
avoided.
How can I get my code merged faster?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
So no-one is coming to review your code, how do you speed up that
process?
Firstly, make sure you are following the above process. If it's a
feature, make sure you have an approved blueprint. If it's a bug, make
sure it is triaged, has its priority set correctly, it has the correct
bug tag and is marked as in progress. If the blueprint has all the code
up for review, change it from Started into NeedsCodeReview so people
know only reviews are blocking you, make sure it hasn't accidentally got
marked as implemented.
Secondly, if you have a negative review (-1 or -2) and you responded to
that in a comment or uploading a new change with some updates, but that
reviewer hasn't come back for over a week, it's probably a good time to
reach out to the reviewer on IRC (or via email) to see if they could
look again now you have addressed their comments. If you can't get
agreement, and your review gets stuck (i.e. requires mediation), you can
raise your patch during the Nova meeting and we will try to resolve any
disagreement.
Thirdly, is it in merge conflict with master or are any of the CI tests
failing? Particularly any third-party CI tests that are relevant to the
code you are changing. If you're fixing something that only occasionally
failed before, maybe recheck a few times to prove the tests stay
passing. Without green tests, reviewers tend to move on and look at the
other patches that have the tests passing.
OK, so you have followed all the process (i.e. your patches are getting
advertised via the project's tracking mechanisms), and your patches
either have no reviews, or only positive reviews. Now what?
Have you considered reviewing other people's patches? Firstly,
participating in the review process is the best way for you to
understand what reviewers are wanting to see in the code you are
submitting. As you get more practiced at reviewing it will help you to
write "merge-ready" code. Secondly, if you help review other peoples
code and help get their patches ready for the core reviewers to add a
+2, it will free up a lot of non-core and core reviewer time, so they
are more likely to get time to review your code. For more details,
please see: :ref:`Why do code reviews when I'm not core? <why_plus1>`
Please note, I am not recommending you go to ask people on IRC or via
email for reviews. Please try to get your code reviewed using the above
process first. In many cases multiple direct pings generate frustration
on both sides and that tends to be counter productive.
Now you have got your code merged, lets make sure you don't need to fix
this bug again. The fact the bug exists means there is a gap in our
testing. Your patch should have included some good unit tests to stop
the bug coming back. But don't stop there, maybe its time to add tempest
tests, to make sure your use case keeps working? Maybe you need to set
up a third party CI so your combination of drivers will keep working?
Getting that extra testing in place should stop a whole heap of bugs,
again giving reviewers more time to get to the issues or features you
want to add in the future.
Process Evolution Ideas
=======================
We are always evolving our process as we try to improve and adapt to the
changing shape of the community. Here we discuss some of the ideas,
along with their pros and cons.
Splitting out the virt drivers (or other bits of code)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Currently, Nova doesn't have strong enough interfaces to split out the
virt drivers, scheduler or REST API. This is seen as the key blocker.
Let's look at both sides of the debate here.
Reasons for the split:
- can have separate core teams for each repo
- this leads to quicker turn around times, largely due to focused
teams
- splitting out things from core means less knowledge required to
become core in a specific area
Reasons against the split:
- loss of interoperability between drivers
- this is a core part of Nova's mission, to have a single API across
all deployments, and a strong ecosystem of tools and apps built on
that
- we can overcome some of this with stronger interfaces and
functional tests
- new features often need changes in the API and virt driver anyway
- the new "depends-on" can make these cross-repo dependencies easier
- loss of code style consistency across the code base
- fear of fragmenting the nova community, leaving few to work on the
core of the project
- could work in subteams within the main tree
TODO - need to complete analysis
Subteam recommendation as a +2
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are groups of people with great knowledge of particular bits of
the code base. It may be a good idea to give their recommendation of a
merge greater strength. In addition, having the subteam focus review efforts
on a subset of patches should help concentrate the nova-core reviews they
get, and increase the velocity of getting code merged.
The first part is for subgroups to show they can do a great job of
recommending patches. This is starting in here:
https://etherpad.openstack.org/p/rocky-nova-priorities-tracking
Ideally this would be done with gerrit user "tags" rather than an
etherpad. There are some investigations by sdague in how feasible it
would be to add tags to gerrit.
Stop having to submit a spec for each release
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As mentioned above, we use blueprints for tracking, and specs to record
design decisions. Targeting specs to a specific release is a heavyweight
solution and blurs the lines between specs and blueprints. At the same
time, we don't want to lose the opportunity to revise existing
blueprints. Maybe there is a better balance?
What about this kind of process:
- backlog has these folders:
- backlog/incomplete - merge a partial spec
- backlog/complete - merge complete specs (remove tracking details,
such as assignee part of the template)
- ?? backlog/expired - specs are moved here from incomplete or
complete when no longer seem to be given attention (after 1 year,
by default)
- /implemented - when a spec is complete it gets moved into the
release directory and possibly updated to reflect what actually
happened
- there will no longer be a per-release approved spec list
To get your blueprint approved:
- add it to the next nova meeting
- if a spec is required, update the URL to point to the spec merged
in a spec to the blueprint
- ensure there is an assignee in the blueprint
- a day before the meeting, a note is sent to the ML to review the list
before the meeting
- discuss any final objections in the nova-meeting
- this may result in a request to refine the spec, if things have
changed since it was merged
- trivial cases can be approved in advance by a nova-driver, so not all
folks need to go through the meeting
This still needs more thought, but should decouple the spec review from
the release process. It is also more compatible with a runway style
system, that might be less focused on milestones.
Runways
~~~~~~~
Runways are a form of Kanban, where we look at optimising the flow
through the system, by ensuring we focus our efforts on reviewing a
specific subset of patches.
The idea goes something like this:
- define some states, such as: design backlog, design review, code
backlog, code review, test+doc backlog, complete
- blueprints must be in one of the above state
- large or high priority bugs may also occupy a code review slot
- core reviewer member moves item between the slots
- must not violate the rules on the number of items in each state
- states have a limited number of slots, to ensure focus
- certain percentage of slots are dedicated to priorities, depending
on point in the cycle, and the type of the cycle, etc
Reasons for:
- more focused review effort, get more things merged more quickly
- more upfront about when your code is likely to get reviewed
- smooth out current "lumpy" non-priority feature freeze system
Reasons against:
- feels like more process overhead
- control is too centralised
Replacing Milestones with SemVer Releases
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can deploy any commit of Nova and upgrade to a later commit in that
same release. Making our milestones versioned more like an official
release would help signal to our users that people can use the
milestones in production, and get a level of upgrade support.
It could go something like this:
- 14.0.0 is milestone 1
- 14.0.1 is milestone 2 (maybe, because we add features, it should be
14.1.0?)
- 14.0.2 is milestone 3
- we might do other releases (once a critical bug is fixed?), as it
makes sense, but we will always be the time bound ones
- 14.0.3 two weeks after milestone 3, adds only bug fixes (and updates
to RPC versions?)
- maybe a stable branch is created at this point?
- 14.1.0 adds updated translations and co-ordinated docs
- this is released from the stable branch?
- 15.0.0 is the next milestone, in the following cycle
- not the bump of the major version to signal an upgrade
incompatibility with 13.x
We are currently watching Ironic to see how their use of semver goes,
and see what lessons need to be learnt before we look to maybe apply
this technique during M.
Feature Classification
~~~~~~~~~~~~~~~~~~~~~~
This is a look at moving forward this effort:
- https://docs.openstack.org/nova/latest/user/support-matrix.html
The things we need to cover:
- note what is tested, and how often that test passes (via 3rd party
CI, or otherwise)
- link to current test results for stable and master (time since
last pass, recent pass rate, etc)
- TODO - sync with jogo on his third party CI audit and getting
trends, ask infra
- include experimental features (untested feature)
- get better at the impact of volume drivers and network drivers on
available features (not just hypervisor drivers)
Main benefits:
- users get a clear picture of what is known to work
- be clear about when experimental features are removed, if no tests
are added
- allows a way to add experimental things into Nova, and track either
their removal or maturation
| {
"content_hash": "ea561d1b3510a73807dd8784358e06f2",
"timestamp": "",
"source": "github",
"line_count": 937,
"max_line_length": 108,
"avg_line_length": 41.02668089647812,
"alnum_prop": 0.752302169502107,
"repo_name": "phenoxim/nova",
"id": "0141b042162211d1f91089b2446de92cfceca909",
"size": "38442",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/source/contributor/process.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "16289098"
},
{
"name": "Shell",
"bytes": "20716"
},
{
"name": "Smarty",
"bytes": "282020"
}
],
"symlink_target": ""
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.CSharp.Syntax;
#if CODE_STYLE
using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions;
#endif
namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody
{
internal abstract class UseExpressionBodyHelper
{
public abstract Option2<CodeStyleOption2<ExpressionBodyPreference>> Option { get; }
public abstract LocalizableString UseExpressionBodyTitle { get; }
public abstract LocalizableString UseBlockBodyTitle { get; }
public abstract string DiagnosticId { get; }
public abstract EnforceOnBuild EnforceOnBuild { get; }
public abstract ImmutableArray<SyntaxKind> SyntaxKinds { get; }
public abstract BlockSyntax GetBody(SyntaxNode declaration);
public abstract ArrowExpressionClauseSyntax GetExpressionBody(SyntaxNode declaration);
public abstract bool CanOfferUseExpressionBody(OptionSet optionSet, SyntaxNode declaration, bool forAnalyzer);
public abstract (bool canOffer, bool fixesError) CanOfferUseBlockBody(OptionSet optionSet, SyntaxNode declaration, bool forAnalyzer);
public abstract SyntaxNode Update(SemanticModel semanticModel, SyntaxNode declaration, bool useExpressionBody);
public abstract Location GetDiagnosticLocation(SyntaxNode declaration);
public static readonly ImmutableArray<UseExpressionBodyHelper> Helpers =
ImmutableArray.Create<UseExpressionBodyHelper>(
UseExpressionBodyForConstructorsHelper.Instance,
UseExpressionBodyForConversionOperatorsHelper.Instance,
UseExpressionBodyForIndexersHelper.Instance,
UseExpressionBodyForMethodsHelper.Instance,
UseExpressionBodyForOperatorsHelper.Instance,
UseExpressionBodyForPropertiesHelper.Instance,
UseExpressionBodyForAccessorsHelper.Instance,
UseExpressionBodyForLocalFunctionHelper.Instance);
}
}
| {
"content_hash": "0756da28e148076a99b56aca0fac174b",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 141,
"avg_line_length": 49.212765957446805,
"alnum_prop": 0.764375270211846,
"repo_name": "AlekseyTs/roslyn",
"id": "9326e2018065b62f832fb69c8d175757cdc7b491",
"size": "2315",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "1C Enterprise",
"bytes": "257760"
},
{
"name": "Batchfile",
"bytes": "8025"
},
{
"name": "C#",
"bytes": "143434676"
},
{
"name": "C++",
"bytes": "5602"
},
{
"name": "CMake",
"bytes": "9153"
},
{
"name": "Dockerfile",
"bytes": "2450"
},
{
"name": "F#",
"bytes": "549"
},
{
"name": "PowerShell",
"bytes": "253312"
},
{
"name": "Shell",
"bytes": "96510"
},
{
"name": "Visual Basic .NET",
"bytes": "72293305"
}
],
"symlink_target": ""
} |
'use strict';
const _ = require('lodash');
module.exports = (roles) => {
if (!_.isArray(roles)) {
throw new Error('roles must be an array');
}
return function*(next) {
if (!this.state || !this.state.user) {
return yield next;
}
if (!_.includes(roles, this.state.user.role)) {
this.throw(403);
}
yield next;
};
}
| {
"content_hash": "6ce130f373597f770430a07cd694fbf6",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 51,
"avg_line_length": 17.19047619047619,
"alnum_prop": 0.554016620498615,
"repo_name": "kofe-i-knigi/kik-server",
"id": "f07fcb9f27f03edce73d73ee65462cb0e4cc735a",
"size": "361",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "middleware/roles.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "54626"
}
],
"symlink_target": ""
} |
import { generateUtilityClass, generateUtilityClasses } from '@material-ui/unstyled';
export function getTreeViewUtilityClass(slot) {
return generateUtilityClass('MuiTreeView', slot);
}
const treeViewClasses = generateUtilityClasses('MuiTreeView', ['root']);
export default treeViewClasses;
| {
"content_hash": "d1a23eec3d85496aa9deab959622dce9",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 85,
"avg_line_length": 32.888888888888886,
"alnum_prop": 0.8006756756756757,
"repo_name": "callemall/material-ui",
"id": "a3c93a3b5d54506771d648818a806582978fd879",
"size": "296",
"binary": false,
"copies": "1",
"ref": "refs/heads/next",
"path": "packages/material-ui-lab/src/TreeView/treeViewClasses.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "302"
},
{
"name": "JavaScript",
"bytes": "1758519"
},
{
"name": "Shell",
"bytes": "144"
},
{
"name": "TypeScript",
"bytes": "27469"
}
],
"symlink_target": ""
} |
package org.apache.camel.component.http;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.camel.Converter;
import org.apache.camel.Exchange;
import org.apache.camel.util.ExchangeHelper;
import org.apache.camel.util.GZIPHelper;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.RequestEntity;
/**
* Some converter methods to make it easier to convert the body to RequestEntity types.
*/
@Converter
public final class RequestEntityConverter {
private RequestEntityConverter() {
}
@Converter
public static RequestEntity toRequestEntity(byte[] data, Exchange exchange) throws Exception {
return asRequestEntity(data, exchange);
}
@Converter
public static RequestEntity toRequestEntity(InputStream inStream, Exchange exchange) throws Exception {
return asRequestEntity(inStream, exchange);
}
@Converter
public static RequestEntity toRequestEntity(String str, Exchange exchange) throws Exception {
if (GZIPHelper.isGzip(exchange.getIn())) {
byte[] data = exchange.getContext().getTypeConverter().convertTo(byte[].class, str);
return asRequestEntity(data, exchange);
} else {
// will use the default StringRequestEntity
return null;
}
}
private static RequestEntity asRequestEntity(InputStream in, Exchange exchange) throws IOException {
if (exchange != null
&& !exchange.getProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.FALSE, Boolean.class)) {
return new InputStreamRequestEntity(GZIPHelper.compressGzip(exchange.getIn()
.getHeader(Exchange.CONTENT_ENCODING, String.class), in), ExchangeHelper
.getContentType(exchange));
} else {
// should set the content type here
if (exchange != null) {
return new InputStreamRequestEntity(in, ExchangeHelper.getContentType(exchange));
} else {
return new InputStreamRequestEntity(in);
}
}
}
private static RequestEntity asRequestEntity(byte[] data, Exchange exchange) throws Exception {
if (exchange != null
&& !exchange.getProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.FALSE, Boolean.class)) {
return new InputStreamRequestEntity(GZIPHelper.compressGzip(exchange.getIn()
.getHeader(Exchange.CONTENT_ENCODING, String.class), data), ExchangeHelper
.getContentType(exchange));
} else {
// should set the content type here
if (exchange != null) {
return new InputStreamRequestEntity(new ByteArrayInputStream(data), ExchangeHelper.getContentType(exchange));
} else {
return new InputStreamRequestEntity(new ByteArrayInputStream(data));
}
}
}
}
| {
"content_hash": "b33bc240430e7c0efeba1d56a00198a6",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 125,
"avg_line_length": 38.72727272727273,
"alnum_prop": 0.6753856472166331,
"repo_name": "aaronwalker/camel",
"id": "9c49a2fcf1fddc570adb0122f43be6b122aaebdb",
"size": "3785",
"binary": false,
"copies": "1",
"ref": "refs/heads/trunk",
"path": "components/camel-http/src/main/java/org/apache/camel/component/http/RequestEntityConverter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ActionScript",
"bytes": "20202"
},
{
"name": "CSS",
"bytes": "221391"
},
{
"name": "Groovy",
"bytes": "2682"
},
{
"name": "Haskell",
"bytes": "5970"
},
{
"name": "Java",
"bytes": "27972791"
},
{
"name": "JavaScript",
"bytes": "3697148"
},
{
"name": "PHP",
"bytes": "88860"
},
{
"name": "Ruby",
"bytes": "9910"
},
{
"name": "Scala",
"bytes": "220463"
},
{
"name": "Shell",
"bytes": "12865"
},
{
"name": "TypeScript",
"bytes": "715"
},
{
"name": "XQuery",
"bytes": "1248"
},
{
"name": "XSLT",
"bytes": "53623"
}
],
"symlink_target": ""
} |
package stainless
package genc
import extraction.throwing.trees._
import collection.mutable.{ Set => MutableSet }
private[genc] object ExtraOps {
// copied from AdtSpecialization
def root(id: Identifier)(using symbols: Symbols): Identifier = {
symbols.getClass(id).parents.map(ct => root(ct.id)).headOption.getOrElse(id)
}
val manualDefAnnotation = "cCode.function"
extension (fa: FunAbstraction) {
def isManuallyDefined: Boolean = hasAnnotation(manualDefAnnotation)
def isExtern: Boolean = fa.flags contains Extern
def isDropped: Boolean = hasAnnotation("cCode.drop") || fa.flags.contains(Ghost)
def isVal: Boolean = fa.isInstanceOf[Outer] && fa.asInstanceOf[Outer].fd.isVal
def noMangling: Boolean = hasAnnotation("cCode.noMangling")
def extAnnotations: Map[String, Seq[Any]] = fa.flags.collect {
case Annotation(s, args) => s -> args
}.toMap
def annotations: Set[String] = extAnnotations.keySet
private def hasAnnotation(annot: String): Boolean = annotations contains annot
}
// Extra tools on FunDef, especially for annotations
extension (fd: FunDef) {
def isMain: Boolean = fd.id.name == "main"
def isExtern: Boolean = fd.flags contains Extern
def isDropped : Boolean = hasAnnotation("cCode.drop") || fd.flags.contains(Ghost)
def isExported : Boolean = hasAnnotation("cCode.export")
def noMangling : Boolean = hasAnnotation("cCode.noMangling")
def isManuallyDefined: Boolean = hasAnnotation(manualDefAnnotation)
def isVal : Boolean =
(fd.flags.exists(_.name == "accessor") || fd.flags.exists { case IsField(_) => true case _ => false }) &&
fd.tparams.isEmpty && fd.params.isEmpty
def extAnnotations: Map[String, Seq[Any]] = fd.flags.collect {
case Annotation(s, args) => s -> args
}.toMap
def annotations: Set[String] = extAnnotations.keySet
def isGeneric = fd.tparams.length > 0
def hasAnnotation(annot: String): Boolean = annotations contains annot
}
case class ManualType(alias: String, include: Option[String])
private val manualTypeAnnotation = "cCode.typedef"
private val droppedAnnotation = "cCode.drop"
// Extra tools on ClassDef, especially for annotations, inheritance & generics
extension (cd: ClassDef) {
def isManuallyTyped: Boolean = hasAnnotation(manualTypeAnnotation)
def isDropped: Boolean = hasAnnotation(droppedAnnotation)
def isExported: Boolean = hasAnnotation("cCode.export")
def noMangling: Boolean = hasAnnotation("cCode.noMangling")
def isPacked: Boolean = hasAnnotation("cCode.pack")
def isGlobal: Boolean = cd.flags.exists(_.name.startsWith("cCode.global"))
def isGlobalDefault: Boolean = cd.flags.exists(_.name == "cCode.global")
def isGlobalUninitialized: Boolean = cd.flags.exists(_.name == "cCode.globalUninitialized")
def isGlobalExternal: Boolean = cd.flags.exists(_.name == "cCode.globalExternal")
def extAnnotations: Map[String, Seq[Any]] = cd.flags.collect {
case Annotation(s, args) => s -> args
}.toMap
def annotations: Set[String] = extAnnotations.keySet
def getManualType: ManualType = {
assert(isManuallyTyped)
val Seq(StringLiteral(alias), StringLiteral(includes0)) = cd.extAnnotations(manualTypeAnnotation): @unchecked
val include = if (includes0.isEmpty) None else Some(includes0)
ManualType(alias, include)
}
def isCandidateForInheritance: Boolean = cd.isAbstract || !cd.parents.isEmpty
def isGeneric: Boolean = cd.tparams.length > 0
def isRecursive(using Symbols): Boolean = {
val defs: Set[ClassDef] = cd.parents.map(_.tcd.cd).toSet + cd
val seens = MutableSet[ClassType]()
def rec(typ: Type): Boolean = typ match {
case t: ClassType if seens(t) => false
case t: ClassType =>
val cd0 = t.tcd.cd
defs(cd0) || {
seens += t
(cd0.fields map { _.getType } exists rec) ||
(cd0.parents exists rec) ||
(cd0.children exists (cd => rec(cd.typed.toType)))
}
case NAryType(ts, _) => ts exists rec
case _ => false
}
// Find out if the parent of cd or cd itself are involved in a type of a field
cd.fields map { _.getType } exists rec
}
// copied from AdtSpecialization
def isCandidate(using symbols: Symbols): Boolean = {
val id = cd.id
cd.parents match {
case Nil =>
def rec(cd: ClassDef): Boolean = {
val cs = cd.children
(cd.parents.size <= 1) &&
(cd.typeMembers.isEmpty) &&
(cs forall rec) &&
(cd.parents forall (_.tps == cd.typeArgs)) &&
((cd.flags contains IsAbstract) || cs.isEmpty) &&
(!(cd.flags contains IsAbstract) || cd.fields.isEmpty) &&
(cd.typeArgs forall (tp => tp.isInvariant && !tp.flags.exists { case Bounds(_, _) => true case _ => false }))
}
rec(cd)
case _ => symbols.getClass(root(id)).isCandidate
}
}
// copied from AdtSpecialization
def isCaseObject(using symbols: Symbols): Boolean = {
val id = cd.id
isCandidate && (symbols.getClass(id).flags contains IsCaseObject)
}
// Check whether the class has some fields or not
def isEmpty: Boolean = cd.fields.isEmpty
def hasAnnotation(annot: String): Boolean = cd.annotations contains annot
}
def isGlobal(tpe: Type)(using Symbols): Boolean = tpe match {
case ct: ClassType => ct.tcd.cd.isGlobal
case _ => false
}
}
| {
"content_hash": "7a52de5c546f16fb2aa20f3409cca56a",
"timestamp": "",
"source": "github",
"line_count": 157,
"max_line_length": 121,
"avg_line_length": 36.23566878980892,
"alnum_prop": 0.6428194761821058,
"repo_name": "epfl-lara/stainless",
"id": "8ac13211ed49d7ab8b767e5b77c43965d2b82ec4",
"size": "5729",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "core/src/main/scala/stainless/genc/phases/ExtraOps.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "206"
},
{
"name": "CSS",
"bytes": "46032"
},
{
"name": "Coq",
"bytes": "37167"
},
{
"name": "Dockerfile",
"bytes": "683"
},
{
"name": "HTML",
"bytes": "4276517"
},
{
"name": "JavaScript",
"bytes": "49474"
},
{
"name": "Nix",
"bytes": "277"
},
{
"name": "Python",
"bytes": "2117"
},
{
"name": "Scala",
"bytes": "3396410"
},
{
"name": "Shell",
"bytes": "22068"
}
],
"symlink_target": ""
} |
package fr.javatronic.blog.massive.annotation2;
import fr.javatronic.blog.processor.Annotation_002;
@Annotation_002
public class Class_334 {
}
| {
"content_hash": "c120023eaacaafb53dd343083081090c",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 51,
"avg_line_length": 20.714285714285715,
"alnum_prop": 0.8068965517241379,
"repo_name": "lesaint/experimenting-annotation-processing",
"id": "37d94878d8e3e1c9bb7bf7c68c61df228db52d60",
"size": "145",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation2/Class_334.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1909421"
},
{
"name": "Shell",
"bytes": "1605"
}
],
"symlink_target": ""
} |
USING_NS_CC;
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// create the application instance
AppDelegate app;
CCEGLView* eglView = CCEGLView::sharedOpenGLView();
eglView->setViewName("SampleFlashImport");
eglView->setFrameSize(480, 320);
return CCApplication::sharedApplication()->run();
}
| {
"content_hash": "035b584f29f6e25e6f3b63c3aa2cd1e4",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 55,
"avg_line_length": 31.41176470588235,
"alnum_prop": 0.6367041198501873,
"repo_name": "MiaoMiaosha/Cocos",
"id": "bf4f1c8cea60a33bb91344d0f203839e6dc20471",
"size": "601",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SampleFlashImport/proj.win32/main.cpp",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1332950"
},
{
"name": "C++",
"bytes": "14873098"
},
{
"name": "Java",
"bytes": "326759"
},
{
"name": "JavaScript",
"bytes": "726954"
},
{
"name": "Lua",
"bytes": "267794"
},
{
"name": "Objective-C",
"bytes": "929701"
},
{
"name": "Objective-C++",
"bytes": "398253"
},
{
"name": "Perl",
"bytes": "131258"
},
{
"name": "Prolog",
"bytes": "1094"
},
{
"name": "Python",
"bytes": "263634"
},
{
"name": "Shell",
"bytes": "115543"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>input (NChurn)</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" />
</head>
<body class="standalone-code">
<pre><span class="ruby-comment cmt"># File lib/albacore/nchurn.rb, line 39</span>
<span class="ruby-keyword kw">def</span> <span class="ruby-identifier">input</span>(<span class="ruby-identifier">p</span>)
<span class="ruby-ivar">@input</span> = <span class="ruby-identifier">quotes</span>(<span class="ruby-identifier">p</span>)
<span class="ruby-keyword kw">end</span></pre>
</body>
</html> | {
"content_hash": "6790fab414167b19b87d17d785c2ec44",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 127,
"avg_line_length": 47.111111111111114,
"alnum_prop": 0.6556603773584906,
"repo_name": "michaelsync/Giles",
"id": "0655590246a92af7e7ba8ca9533d360b118b6cda",
"size": "848",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tools/Rake/lib/ruby/gems/1.8/doc/albacore-0.2.7/rdoc/classes/NChurn.src/M000337.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "3424"
},
{
"name": "C#",
"bytes": "169278"
},
{
"name": "HTML",
"bytes": "6297"
},
{
"name": "PowerShell",
"bytes": "3788"
},
{
"name": "Ruby",
"bytes": "3661"
},
{
"name": "Shell",
"bytes": "56"
},
{
"name": "XSLT",
"bytes": "10342"
}
],
"symlink_target": ""
} |
<?php
namespace Ds\Component\Parameter\Command\Parameter;
use Ds\Component\Parameter\Service\ParameterService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Class GetCommand
*
* @package Ds\Component\Parameter
*/
final class GetCommand extends Command
{
/**
* @var \Ds\Component\Parameter\Service\ParameterService
*/
private $parameterService;
/**
* Constructor
*
* @param \Ds\Component\Parameter\Service\ParameterService $parameterService
* @param string $name
*/
public function __construct(ParameterService $parameterService, $name = null)
{
parent::__construct($name);
$this->parameterService = $parameterService;
}
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('ds:parameter:get')
->addArgument('key', InputArgument::REQUIRED, 'The parameter key.')
->setDescription('Gets a parameter value.')
->setHelp('This command allows you to get a parameter value.');
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$key = $input->getArgument('key');
$value = $this->parameterService->get($key);
$output->write($value);
}
}
| {
"content_hash": "ffe1b457627d0bb685268a7e59e17f9f",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 81,
"avg_line_length": 26.410714285714285,
"alnum_prop": 0.6470588235294118,
"repo_name": "DigitalState/Core",
"id": "36dc8ae10b378197ecf6aebd7c1fc972cfea096d",
"size": "1479",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Parameter/Command/Parameter/GetCommand.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "718820"
}
],
"symlink_target": ""
} |
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var common_1 = require('@angular/common');
var fa_directive_1 = require('./directives/fa.directive');
var fa_component_1 = require('./components/fa.component');
var fa_stack_component_1 = require('./components/fa-stack.component');
var Angular2FontawesomeModule = (function () {
function Angular2FontawesomeModule() {
}
Angular2FontawesomeModule = __decorate([
core_1.NgModule({
imports: [common_1.CommonModule],
declarations: [fa_directive_1.FaDirective, fa_component_1.FaComponent, fa_stack_component_1.FaStackComponent],
exports: [fa_directive_1.FaDirective, fa_component_1.FaComponent, fa_stack_component_1.FaStackComponent]
}),
__metadata('design:paramtypes', [])
], Angular2FontawesomeModule);
return Angular2FontawesomeModule;
}());
exports.Angular2FontawesomeModule = Angular2FontawesomeModule;
//# sourceMappingURL=index.js.map | {
"content_hash": "1736463150e89d145fc908741ea53643",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 150,
"avg_line_length": 57.3,
"alnum_prop": 0.6631762652705061,
"repo_name": "gabrieldamaso7/innocircle",
"id": "f25d6efc5ad47f2c4e25adda7989f66e335e6c80",
"size": "1719",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/angular2-fontawesome/src/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "162"
},
{
"name": "HTML",
"bytes": "4479"
},
{
"name": "JavaScript",
"bytes": "45010"
},
{
"name": "TypeScript",
"bytes": "23194"
}
],
"symlink_target": ""
} |
{{<layout}}
{{$pageTitle}} Choose a vehicle to register {{/pageTitle}}
{{$head}}
{{>includes/head}}
{{>includes/scripts}}
<script src="/public/javascripts/sorttable.js"></script>
<script src="/public/javascripts/Autocomplete/jquery-1.11.1.min.js"></script>
<script src="/public/javascripts/Autocomplete/jquery-ui.min.js"></script>
<script src="/public/javascripts/Autocomplete/jquery.select-to-autocomplete.js"></script>
<script>
(function($){
$(function(){
$('select').selectToAutocomplete( {
'relevancy-sorting': true,
'sort': true
});
//$('input').autocomplete ({sortResults:false})
});
})(jQuery);
</script>
<style type="text/css">
.form-group.continue-validation {
margin-bottom: 0 !important;
padding-bottom: 0 !important;
}
tr { cursor: default; }
.highlight { background: white; border: 5px solid #FFBF47; }
table th { background-color: #FFFFFF; padding-left: 1em; }
table td { padding-left: 1em; }
/* Sortable tables */
table.sortable thead {
background-color:#eee;
color:#666666;
font-weight: bold;
cursor: default;
}
/* Filters */
.form-control-100 {
width: 100%;
}
.filter-tag {
font-size:16px;
background: #DEE0E2;
padding: 8px 4px 6px 9px;
width: 155px;
margin-bottom: 6px;
}
.filter-tag img {
padding-left: 10px;
width: 12px;
height: 12px;
}
.tag-list{
margin-top: 10px;
}
.filter-group {
border-top: 1px solid #BBBDBF;
margin-bottom: 12px;
}
.filter-checkbox {
margin:0px 6px 12px 0px;
}
.filter-checkbox-label {
margin-top: 4px;
font-size: 16px;
}
.form-group-dividers {
border-top: 1px solid #BBBDBF;
margin-bottom: 5px;
}
.column-three-quarters { float: left; width: 73%; }
.column-three-quarters .column-half:first-child { text-align: left; }
.column-three-quarters .column-half:last-child { text-align: right; }
</style>
{{/head}}
{{$content}}
<main id="content" role="main">
{{>includes/phase-banner-beta-logout}}
{{>includes/buttons/back}}
<h1 class="heading-large margin-bottom-1">Choose a vehicle to register</h1>
<div class="grid-row" id="pr3">
<div class="column-quarter"><!-- start filters column -->
<h2 class="border-bottom padding-bottom-0-5 margin-top-1 bold-medium">Filter my results:</h2>
<form class="form">
<div class="form-group no-bottom margin-top-1">
<fieldset>
<div id="vehicle-question" class="padding-bottom-1 border-bottom">
<legend class="visuallyhidden">VIN, chassis or frame number</legend>
<label class="form-label-bold">
VIN, chassis or frame number
</label>
<select name="Vehicle" class="form-control" placeholder="" id="vehicle-selector" autofocus autocorrect="off" autocomplete="off" copy-attributes-to-text-field="false" style="min-width: 11em;">
<optgroup style="font-size:18px;">
<option value="">VIN, chassis or frame number</option>
<option value="EXAMPLEVIN001" vehicle="M1">EXAMPLEVIN001</option>
<option value="EXAMPLEVIN002" vehicle="M1">EXAMPLEVIN002</option>
<option value="EXAMPLEVIN003" vehicle="M1" >EXAMPLEVIN003</option>
<option value="EXAMPLEVIN004" vehicle="M1">EXAMPLEVIN004</option>
<option value="EXAMPLEVIN005" vehicle="M1" >EXAMPLEVIN005</option>
<option value="EXAMPLEVIN006" vehicle="M1">EXAMPLEVIN006</option>
<option value="EXAMPLEVIN007" vehicle="M1" >EXAMPLEVIN007</option>
<option value="EXAMPLEVIN008" vehicle="M1" >EXAMPLEVIN008</option>
<option value="EXAMPLEVIN009" vehicle="M1">EXAMPLEVIN009</option>
<option value="EXAMPLEVIN010" vehicle="M1">EXAMPLEVIN010</option>
<option value="EXAMPLEVIN011" vehicle="M1" >EXAMPLEVIN011</option>
<option value="EXAMPLEVIN012" vehicle="M1">EXAMPLEVIN012</option>
<option value="EXAMPLEVIN013" vehicle="M1" >EXAMPLEVIN013</option>
<option value="EXAMPLEVIN014" vehicle="M1">EXAMPLEVIN014</option>
<option value="EXAMPLEVIN015" vehicle="M1" >EXAMPLEVIN015</option>
<option value="EXAMPLEVIN016" vehicle="M1" >EXAMPLEVIN016</option>
<option value="EXAMPLEVIN017" vehicle="M1" >EXAMPLEVIN017</option>
<option value="EXAMPLEVIN018" vehicle="M1">EXAMPLEVIN018</option>
<option value="EXAMPLEVIN019" vehicle="M1">EXAMPLEVIN019</option>
<option value="EXAMPLEVIN020" vehicle="M1" >EXAMPLEVIN020</option>
<option value="EXAMPLEVIN021" vehicle="M1">EXAMPLEVIN021</option>
<option value="EXAMPLEVIN022" vehicle="M1" >EXAMPLEVIN022</option>
<option value="EXAMPLEVIN023" vehicle="M1">EXAMPLEVIN023</option>
<option value="EXAMPLEVIN024" vehicle="M1" >EXAMPLEVIN024</option>
<option value="EXAMPLEVIN025" vehicle="M1" >EXAMPLEVIN025</option>
<option value="EXAMPLEVIN026" vehicle="M1">EXAMPLEVIN026</option>
<option value="EXAMPLEVIN027" vehicle="M1" >EXAMPLEVIN027</option>
<option value="EXAMPLEVIN028" vehicle="M1">EXAMPLEVIN028</option>
<option value="EXAMPLEVIN029" vehicle="M1" >EXAMPLEVIN029</option>
<option value="EXAMPLEVIN030" vehicle="M1">EXAMPLEVIN030</option>
<option value="EXAMPLEVIN031" vehicle="M1" >EXAMPLEVIN031</option>
<option value="EXAMPLEVIN032" vehicle="M1" >EXAMPLEVIN032</option>
<option value="EXAMPLEVIN033" vehicle="M1">EXAMPLEVIN033</option>
<option value="EXAMPLEVIN034" vehicle="M1">EXAMPLEVIN034</option>
<option value="EXAMPLEVIN035" vehicle="M1" >EXAMPLEVIN035</option>
<option value="EXAMPLEVIN036" vehicle="M1">EXAMPLEVIN036</option>
<option value="EXAMPLEVIN037" vehicle="M1" >EXAMPLEVIN037</option>
<option value="EXAMPLEVIN038" vehicle="M1" selected="selected">EXAMPLEVIN038</option>
<option value="EXAMPLEVIN039" vehicle="M1" >EXAMPLEVIN039</option>
<option value="EXAMPLEVIN040" vehicle="M1" >EXAMPLEVIN040</option>
<option value="EXAMPLEVIN041" vehicle="M1" >EXAMPLEVIN041</option>
<option value="EXAMPLEVIN042" vehicle="M1">EXAMPLEVIN042</option>
<option value="EXAMPLEVIN043" vehicle="M1">EXAMPLEVIN043</option>
<option value="EXAMPLEVIN044" vehicle="M1" >EXAMPLEVIN044</option>
<option value="EXAMPLEVIN045" vehicle="M1">EXAMPLEVIN045</option>
<option value="EXAMPLEVIN046" vehicle="M1" >EXAMPLEVIN046</option>
<option value="EXAMPLEVIN047" vehicle="M1">EXAMPLEVIN047</option>
<option value="EXAMPLEVIN048" vehicle="M1" >EXAMPLEVIN048</option>
<option value="EXAMPLEVIN049" vehicle="M1" >EXAMPLEVIN049</option>
<option value="EXAMPLEVIN050" vehicle="M1" >EXAMPLEVIN050</option>
</optgroup>
</select>
</div>
<div class="form-group margin-bottom-1 margin-top-1" id="make" class="form-group-dividers" style="">
<h3 class="form-label-bold padding-bottom-0-5" for="make">Make</h3>
<input type="checkbox" name="make-1" id="make-checkbox-1" class="filter-checkbox" checked>
<label for="make-checkbox-1" class="filter-checkbox-label">Volkswagen</label><br>
<input type="checkbox" name="make-2" id="make-checkbox-2" class="filter-checkbox">
<label for="make-checkbox-2" class="filter-checkbox-label">Audi</label>
</div>
<div class="form-group filter-group margin-bottom-1" id="models" style="">
<h3 class="form-label-bold margin-top-1-5 padding-bottom-0-5" for="models">Models</h3>
<input type="checkbox" name="models-1" id="models-checkbox-1" class="filter-checkbox" checked>
<label for="models-checkbox-1" class="filter-checkbox-label">Golf GTI</label><br>
<input type="checkbox" name="models-2" id="models-checkbox-2" class="filter-checkbox">
<label for="models-checkbox-2" class="filter-checkbox-label">Caddy Maxi</label><br>
<input type="checkbox" name="models-3" id="models-checkbox-3" class="filter-checkbox">
<label for="models-checkbox-3" class="filter-checkbox-label">Transporter</label><br>
<input type="checkbox" name="models-4" id="models-checkbox-4" class="filter-checkbox">
<label for="models-checkbox-4" class="filter-checkbox-label">A8</label><br>
</div>
<div class="form-group filter-group margin-bottom-1" id="colour" style="">
<h3 class="form-label-bold margin-top-1-5 padding-bottom-0-5" for="colour">Colour</h3>
<input type="checkbox" name="colour-1" id="colour-checkbox-1" class="filter-checkbox" checked>
<label for="colour-checkbox-1" class="filter-checkbox-label">Blue</label><br>
<input type="checkbox" name="colour-2" id="colour-checkbox-2" class="filter-checkbox">
<label for="colour-checkbox-2" class="filter-checkbox-label">Red</label><br>
<input type="checkbox" name="colour-3" id="colour-checkbox-3" class="filter-checkbox">
<label for="colour-checkbox-3" class="filter-checkbox-label">Black</label><br>
<input type="checkbox" name="colour-4" id="colour-checkbox-4" class="filter-checkbox">
<label for="colour-checkbox-4" class="filter-checkbox-label">Silver</label><br>
</div>
</fieldset>
</div>
<a class="button" href="/rave/vehicle-list-filters-on" style="background-color:#1B75BB;" role="button">Apply filters</a>
</form>
</div><!-- end filters column -->
<div class="column-three-quarters border-bottom">
<div class="padding-bottom-0">
<p class="">
<span class="bold-large">1/50</span>
<span class="bold-small">vehicles</span>
</p>
</div>
</div>
<!--
<div class="padding-top-0" style="margin-top: 8px;">
<table class="sortable column-three-quarters" style="background-color:#DDDFE1; margin-bottom:1em; width:71%;">
<thead style="border-top: 1px solid #BBBDBF">
<tr>
<th style="padding-left: 7%;">
<abbr title="Vehicle identification number">VIN</abbr>
</th>
<th>Make</th>
<th>Model</th>
<th>Colour</th>
</tr>
</thead>
<tbody>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-1" name="vehicles">
<label for="radio-id-1" style="padding-left: 12px;">EXAMPLEVIN001</label>
</td>
<td>Volkswagen</td>
<td>Golf GTI</td>
<td>Blue</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-2" name="vehicles">
<label for="radio-id-2" style="padding-left: 12px;">EXAMPLEVIN002</label>
</td>
<td>Volkswagen</td>
<td>Caddy Maxi</td>
<td>Red</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-3" name="vehicles">
<label for="radio-id-3" style="padding-left: 12px;">EXAMPLEVIN003</label>
</td>
<td>Volkswagen</td>
<td>Transporter</td>
<td>Black</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-4" name="vehicles">
<label for="radio-id-4" style="padding-left: 12px;">EXAMPLEVIN004</label>
</td>
<td>Audi</td>
<td>A8</td>
<td>Silver</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-5" name="vehicles">
<label for="radio-id-5" style="padding-left: 12px;">EXAMPLEVIN005</label>
</td>
<td>Volkswagen</td>
<td>Caddy Maxi</td>
<td>Blue</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-6" name="vehicles">
<label for="radio-id-6" style="padding-left: 12px;">EXAMPLEVIN006</label>
</td>
<td>Audi</td>
<td>A8</td>
<td>Blue</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-7" name="vehicles">
<label for="radio-id-7" style="padding-left: 12px;">EXAMPLEVIN007</label>
</td>
<td>Volkswagen</td>
<td>Golf GTI</td>
<td>Red</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-8" name="vehicles"v>
<label for="radio-id-8" style="padding-left: 12px;">EXAMPLEVIN008</label>
</td>
<td>Volkswagen</td>
<td>Caddy Maxi</td>
<td>Blue</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-9" name="vehicles">
<label for="radio-id-9" style="padding-left: 12px;">EXAMPLEVIN009</label>
</td>
<td>Volkswagen</td>
<td>Caddy Maxi</td>
<td>Black</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-10" name="vehicles">
<label for="radio-id-10" style="padding-left: 12px;">EXAMPLEVIN010</label>
</td>
<td>Volkswagen</td>
<td>Golf GTI</td>
<td>Blue</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-11" name="vehicles">
<label for="radio-id-11" style="padding-left: 12px;">EXAMPLEVIN011</label>
</td>
<td>Audi</td>
<td>A8</td>
<td>Silver</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-12" name="vehicles">
<label for="radio-id-12" style="padding-left: 12px;">EXAMPLEVIN012</label>
</td>
<td>Volkswagen</td>
<td>Transporter</td>
<td>Silver</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-13" name="vehicles">
<label for="radio-id-13" style="padding-left: 12px;">EXAMPLEVIN013</label>
</td>
<td>Volkswagen</td>
<td>Golf GTI</td>
<td>Blue</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-14" name="vehicles">
<label for="radio-id-14" style="padding-left: 12px;">EXAMPLEVIN014</label>
</td>
<td>Volkswagen</td>
<td>Caddy Maxi</td>
<td>Red</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-15" name="vehicles">
<label for="radio-id-15" style="padding-left: 12px;">EXAMPLEVIN015</label>
</td>
<td>Volkswagen</td>
<td>Transporter</td>
<td>Blue</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-16" name="vehicles">
<label for="radio-id-16" style="padding-left: 12px;">EXAMPLEVIN016</label>
</td>
<td>Audi</td>
<td>A8</td>
<td>Black</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-17" name="vehicles">
<label for="radio-id-17" style="padding-left: 12px;">EXAMPLEVIN017</label>
</td>
<td>Volkswagen</td>
<td>Caddy Maxi</td>
<td>Red</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-18" name="vehicles">
<label for="radio-id-18" style="padding-left: 12px;">EXAMPLEVIN018</label>
</td>
<td>Volkswagen</td>
<td>Transporter</td>
<td>Silver</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-19" name="vehicles">
<label for="radio-id-19" style="padding-left: 12px;">EXAMPLEVIN019</label>
</td>
<td>Volkswagen</td>
<td>Golf GTI</td>
<td>Blue</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-20" name="vehicles">
<label for="radio-id-20" style="padding-left: 12px;">EXAMPLEVIN020</label>
</td>
<td>Audi</td>
<td>A8</td>
<td>Silver</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-21" name="vehicles">
<label for="radio-id-21" style="padding-left: 12px;">EXAMPLEVIN021</label>
</td>
<td>Audi</td>
<td>A8</td>
<td>Black</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-22" name="vehicles">
<label for="radio-id-22" style="padding-left: 12px;">EXAMPLEVIN022</label>
</td>
<td>Volkswagen</td>
<td>Golf GTI</td>
<td>Blue</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-23" name="vehicles">
<label for="radio-id-23" style="padding-left: 12px;">EXAMPLEVIN023</label>
</td>
<td>Volkswagen</td>
<td>Transporter</td>
<td>Silver</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-24" name="vehicles">
<label for="radio-id-24" style="padding-left: 12px;">EXAMPLEVIN024</label>
</td>
<td>Volkswagen</td>
<td>Golf GTI</td>
<td>Red</td>
</tr>
<tr>
<td style="padding-left: 10px;">
<input type="radio" id="radio-id-25" name="vehicles">
<label for="radio-id-25" style="padding-left: 12px;">EXAMPLEVIN025</label>
</td>
<td>Volkswagen</td>
<td>Caddy Maxi</td>
<td>Blue</td>
</tr>
</tbody>
</table>
</div>
-->
<div>
<table class="sortable column-three-quarters" style="background-color:#DDDFE1; margin-bottom:1em;">
<thead>
<tr>
<th><abbr title="Vehicle identification number">VIN</abbr>, chassis or frame number</th>
<th>Make</th>
<th>Model</th>
<th>Colour</th>
</tr>
</thead>
<tbody>
<tr>
<td>EXAMPLEVIN038</td>
<td>Volkswagen</td>
<td>Golf GTI</td>
<td>Blue</td>
</tr>
</tbody>
</table>
</div>
<div style="padding-left: 27%;">
<p style="text-align: right; margin-right:1em;">Page 1 of 1</p>
{{>includes/buttons/continue-validation}}
</div>
</div>
</main>
<script type="text/javascript">
$(".button").click(function(){
// Enter function name here
next();
});
function next() {
go('/rave/M1');
}
$(function() {
/* Get all rows from your 'table' but not the first one
* that includes headers. */
var rows = $('tr').not(':first');
/* Create 'click' event handler for rows */
rows.on('click', function(e) {
/* Get current row */
var row = $(this);
/* Check if 'Ctrl', 'cmd' or 'Shift' keyboard key was pressed
* 'Ctrl' => is represented by 'e.ctrlKey' or 'e.metaKey'
* 'Shift' => is represented by 'e.shiftKey' */
if ((e.ctrlKey || e.metaKey) || e.shiftKey) {
/* If pressed highlight the other row that was clicked */
row.addClass('highlight');
} else {
/* Otherwise just highlight one row and clean others */
rows.removeClass('highlight');
row.addClass('highlight');
}
});
/* This 'event' is used just to avoid that the table text
* gets selected (just for styling).
* For example, when pressing 'Shift' keyboard key and clicking
* (without this 'event') the text of the 'table' will be selected.
* You can remove it if you want, I just tested this in
* Chrome v30.0.1599.69 */
$(document).bind('selectstart dragstart', function(e) {
e.preventDefault(); return false;
});
});
</script>
{{/content}}
{{/layout}} | {
"content_hash": "0c7508f057ff7af3eb47599871d78bbc",
"timestamp": "",
"source": "github",
"line_count": 559,
"max_line_length": 219,
"avg_line_length": 37.924865831842574,
"alnum_prop": 0.5511320754716981,
"repo_name": "dudelmeister/rave",
"id": "365268f71820e29903eb9788fe95505572b60fe4",
"size": "21200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/views/rave/vehicle-list-filters-on.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "62702"
},
{
"name": "HTML",
"bytes": "2831351"
},
{
"name": "JavaScript",
"bytes": "247511"
},
{
"name": "Shell",
"bytes": "649"
}
],
"symlink_target": ""
} |
'use strict';
(function() {
// Faculties Controller Spec
describe('Faculties Controller Tests', function() {
// Initialize global variables
var FacultiesController,
scope,
$httpBackend,
$stateParams,
$location;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
// Set a new global scope
scope = $rootScope.$new();
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
// Initialize the Faculties controller.
FacultiesController = $controller('FacultiesController', {
$scope: scope
});
}));
it('$scope.find() should create an array with at least one Faculty object fetched from XHR', inject(function(Faculties) {
// Create sample Faculty using the Faculties service
var sampleFaculty = new Faculties({
name: 'New Faculty'
});
// Create a sample Faculties array that includes the new Faculty
var sampleFaculties = [sampleFaculty];
// Set GET response
$httpBackend.expectGET('faculties').respond(sampleFaculties);
// Run controller functionality
scope.find();
$httpBackend.flush();
// Test scope value
expect(scope.faculties).toEqualData(sampleFaculties);
}));
it('$scope.findOne() should create an array with one Faculty object fetched from XHR using a facultyId URL parameter', inject(function(Faculties) {
// Define a sample Faculty object
var sampleFaculty = new Faculties({
name: 'New Faculty'
});
// Set the URL parameter
$stateParams.facultyId = '525a8422f6d0f87f0e407a33';
// Set GET response
$httpBackend.expectGET(/faculties\/([0-9a-fA-F]{24})$/).respond(sampleFaculty);
// Run controller functionality
scope.findOne();
$httpBackend.flush();
// Test scope value
expect(scope.faculty).toEqualData(sampleFaculty);
}));
it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Faculties) {
// Create a sample Faculty object
var sampleFacultyPostData = new Faculties({
name: 'New Faculty'
});
// Create a sample Faculty response
var sampleFacultyResponse = new Faculties({
_id: '525cf20451979dea2c000001',
name: 'New Faculty'
});
// Fixture mock form input values
scope.name = 'New Faculty';
// Set POST response
$httpBackend.expectPOST('faculties', sampleFacultyPostData).respond(sampleFacultyResponse);
// Run controller functionality
scope.create();
$httpBackend.flush();
// Test form inputs are reset
expect(scope.name).toEqual('');
// Test URL redirection after the Faculty was created
expect($location.path()).toBe('/faculties/' + sampleFacultyResponse._id);
}));
it('$scope.update() should update a valid Faculty', inject(function(Faculties) {
// Define a sample Faculty put data
var sampleFacultyPutData = new Faculties({
_id: '525cf20451979dea2c000001',
name: 'New Faculty'
});
// Mock Faculty in scope
scope.faculty = sampleFacultyPutData;
// Set PUT response
$httpBackend.expectPUT(/faculties\/([0-9a-fA-F]{24})$/).respond();
// Run controller functionality
scope.update();
$httpBackend.flush();
// Test URL location to new object
expect($location.path()).toBe('/faculties/' + sampleFacultyPutData._id);
}));
it('$scope.remove() should send a DELETE request with a valid facultyId and remove the Faculty from the scope', inject(function(Faculties) {
// Create new Faculty object
var sampleFaculty = new Faculties({
_id: '525a8422f6d0f87f0e407a33'
});
// Create new Faculties array and include the Faculty
scope.faculties = [sampleFaculty];
// Set expected DELETE response
$httpBackend.expectDELETE(/faculties\/([0-9a-fA-F]{24})$/).respond(204);
// Run controller functionality
scope.remove(sampleFaculty);
$httpBackend.flush();
// Test array after successful delete
expect(scope.faculties.length).toBe(0);
}));
});
}()); | {
"content_hash": "db9631def91ad2987a0d4da208b60196",
"timestamp": "",
"source": "github",
"line_count": 163,
"max_line_length": 161,
"avg_line_length": 31.496932515337424,
"alnum_prop": 0.6959485781067394,
"repo_name": "PongPi/admissions",
"id": "39636c9b462bbf032f4555d1af89539fe62bade8",
"size": "5134",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "public/modules/faculties/tests/faculties.client.controller.test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "124337"
},
{
"name": "HTML",
"bytes": "99365"
},
{
"name": "JavaScript",
"bytes": "353628"
},
{
"name": "Shell",
"bytes": "414"
}
],
"symlink_target": ""
} |
/**
* Returns an error to be thrown when attempting to find an unexisting column.
* @param id Id whose lookup failed.
* @docs-private
*/
export function getTableUnknownColumnError(id: string) {
return Error(`Could not find column with id "${id}".`);
}
/**
* Returns an error to be thrown when two column definitions have the same name.
* @docs-private
*/
export function getTableDuplicateColumnNameError(name: string) {
return Error(`Duplicate column definition name provided: "${name}".`);
}
/**
* Returns an error to be thrown when there are multiple rows that are missing a when function.
* @docs-private
*/
export function getTableMultipleDefaultRowDefsError() {
return Error(`There can only be one default row without a when predicate function.`);
}
/**
* Returns an error to be thrown when there are no matching row defs for a particular set of data.
* @docs-private
*/
export function getTableMissingMatchingRowDefError(data: any) {
return Error(`Could not find a matching row definition for the` +
`provided row data: ${JSON.stringify(data)}`);
}
/**
* Returns an error to be thrown when there is no row definitions present in the content.
* @docs-private
*/
export function getTableMissingRowDefsError() {
return Error('Missing definitions for header, footer, and row; ' +
'cannot determine which columns should be rendered.');
}
/**
* Returns an error to be thrown when the data source does not match the compatible types.
* @docs-private
*/
export function getTableUnknownDataSourceError() {
return Error(`Provided data source did not match an array, Observable, or DataSource`);
}
| {
"content_hash": "3312777690b2244861f2486205dc8444",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 98,
"avg_line_length": 31.596153846153847,
"alnum_prop": 0.7321972002434571,
"repo_name": "amcdnl/material2",
"id": "25eab4434651339ae6c9a09166e6d2cf75718908",
"size": "1844",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/cdk/table/table-errors.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "325329"
},
{
"name": "HTML",
"bytes": "396317"
},
{
"name": "JavaScript",
"bytes": "41908"
},
{
"name": "Python",
"bytes": "68402"
},
{
"name": "Shell",
"bytes": "28632"
},
{
"name": "TypeScript",
"bytes": "4220628"
}
],
"symlink_target": ""
} |
!defined(CHROME_MULTIPLE_DLL_BROWSER))
#include "pdf/pdf.h"
#endif
#if !defined(CHROME_MULTIPLE_DLL_CHILD)
#include "components/startup_metric_utils/browser/startup_metric_utils.h"
#endif
#if !defined(CHROME_MULTIPLE_DLL_BROWSER)
#include "chrome/child/pdf_child_init.h"
base::LazyInstance<ChromeContentRendererClient>
g_chrome_content_renderer_client = LAZY_INSTANCE_INITIALIZER;
base::LazyInstance<ChromeContentUtilityClient>
g_chrome_content_utility_client = LAZY_INSTANCE_INITIALIZER;
base::LazyInstance<ChromeContentPluginClient>
g_chrome_content_plugin_client = LAZY_INSTANCE_INITIALIZER;
#endif
#if !defined(CHROME_MULTIPLE_DLL_CHILD)
base::LazyInstance<ChromeContentBrowserClient> g_chrome_content_browser_client =
LAZY_INSTANCE_INITIALIZER;
#endif
#if defined(OS_POSIX)
base::LazyInstance<ChromeCrashReporterClient>::Leaky g_chrome_crash_client =
LAZY_INSTANCE_INITIALIZER;
#endif
extern int NaClMain(const content::MainFunctionParams&);
extern int ServiceProcessMain(const content::MainFunctionParams&);
namespace {
#if defined(OS_WIN)
// Early versions of Chrome incorrectly registered a chromehtml: URL handler,
// which gives us nothing but trouble. Avoid launching chrome this way since
// some apps fail to properly escape arguments.
bool HasDeprecatedArguments(const base::string16& command_line) {
const wchar_t kChromeHtml[] = L"chromehtml:";
base::string16 command_line_lower = base::ToLowerASCII(command_line);
// We are only searching for ASCII characters so this is OK.
return (command_line_lower.find(kChromeHtml) != base::string16::npos);
}
// If we try to access a path that is not currently available, we want the call
// to fail rather than show an error dialog.
void SuppressWindowsErrorDialogs() {
UINT new_flags = SEM_FAILCRITICALERRORS |
SEM_NOOPENFILEERRORBOX;
// Preserve existing error mode.
UINT existing_flags = SetErrorMode(new_flags);
SetErrorMode(existing_flags | new_flags);
}
bool IsSandboxedProcess() {
typedef bool (*IsSandboxedProcessFunc)();
IsSandboxedProcessFunc is_sandboxed_process_func =
reinterpret_cast<IsSandboxedProcessFunc>(
GetProcAddress(GetModuleHandle(NULL), "IsSandboxedProcess"));
return is_sandboxed_process_func && is_sandboxed_process_func();
}
bool UseHooks() {
#if defined(ARCH_CPU_X86_64)
return false;
#elif defined(NDEBUG)
version_info::Channel channel = chrome::GetChannel();
if (channel == version_info::Channel::CANARY ||
channel == version_info::Channel::DEV) {
return true;
}
return false;
#else // NDEBUG
return true;
#endif
}
#endif // defined(OS_WIN)
#if defined(OS_LINUX)
static void AdjustLinuxOOMScore(const std::string& process_type) {
// Browsers and zygotes should still be killable, but killed last.
const int kZygoteScore = 0;
// The minimum amount to bump a score by. This is large enough that
// even if it's translated into the old values, it will still go up
// by at least one.
const int kScoreBump = 100;
// This is the lowest score that renderers and extensions start with
// in the OomPriorityManager.
const int kRendererScore = chrome::kLowestRendererOomScore;
// For "miscellaneous" things, we want them after renderers,
// but before plugins.
const int kMiscScore = kRendererScore - kScoreBump;
// We want plugins to die after the renderers.
const int kPluginScore = kMiscScore - kScoreBump;
int score = -1;
DCHECK(kMiscScore > 0);
DCHECK(kPluginScore > 0);
if (process_type == switches::kPluginProcess ||
process_type == switches::kPpapiPluginProcess) {
score = kPluginScore;
} else if (process_type == switches::kPpapiBrokerProcess) {
// The broker should be killed before the PPAPI plugin.
score = kPluginScore + kScoreBump;
} else if (process_type == switches::kUtilityProcess ||
process_type == switches::kGpuProcess ||
process_type == switches::kServiceProcess) {
score = kMiscScore;
#ifndef DISABLE_NACL
} else if (process_type == switches::kNaClLoaderProcess ||
process_type == switches::kNaClLoaderNonSfiProcess) {
score = kPluginScore;
#endif
} else if (process_type == switches::kZygoteProcess ||
process_type.empty()) {
// For zygotes and unlabeled process types, we want to still make
// them killable by the OOM killer.
score = kZygoteScore;
} else if (process_type == switches::kRendererProcess) {
LOG(WARNING) << "process type 'renderer' "
<< "should be created through the zygote.";
// When debugging, this process type can end up being run directly, but
// this isn't the typical path for assigning the OOM score for it. Still,
// we want to assign a score that is somewhat representative for debugging.
score = kRendererScore;
} else {
NOTREACHED() << "Unknown process type";
}
if (score > -1)
base::AdjustOOMScore(base::GetCurrentProcId(), score);
}
#endif // defined(OS_LINUX)
// Returns true if this subprocess type needs the ResourceBundle initialized
// and resources loaded.
bool SubprocessNeedsResourceBundle(const std::string& process_type) {
return
#if defined(OS_WIN) || defined(OS_MACOSX)
// Windows needs resources for the default/null plugin.
// Mac needs them for the plugin process name.
process_type == switches::kPluginProcess ||
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX)
// The zygote process opens the resources for the renderers.
process_type == switches::kZygoteProcess ||
#endif
#if defined(OS_MACOSX)
// Mac needs them too for scrollbar related images and for sandbox
// profiles.
#if !defined(DISABLE_NACL)
process_type == switches::kNaClLoaderProcess ||
#endif
process_type == switches::kPpapiPluginProcess ||
process_type == switches::kPpapiBrokerProcess ||
process_type == switches::kGpuProcess ||
#endif
process_type == switches::kRendererProcess ||
process_type == switches::kUtilityProcess;
}
#if defined(OS_POSIX)
// Check for --version and --product-version; return true if we encountered
// one of these switches and should exit now.
bool HandleVersionSwitches(const base::CommandLine& command_line) {
#if !defined(OS_MACOSX)
if (command_line.HasSwitch(switches::kProductVersion)) {
printf("%s\n", version_info::GetVersionNumber().c_str());
return true;
}
#endif
if (command_line.HasSwitch(switches::kVersion)) {
printf("%s %s %s\n",
version_info::GetProductName().c_str(),
version_info::GetVersionNumber().c_str(),
chrome::GetChannelString().c_str());
return true;
}
return false;
}
#if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
// Show the man page if --help or -h is on the command line.
void HandleHelpSwitches(const base::CommandLine& command_line) {
if (command_line.HasSwitch(switches::kHelp) ||
command_line.HasSwitch(switches::kHelpShort)) {
base::FilePath binary(command_line.argv()[0]);
execlp("man", "man", binary.BaseName().value().c_str(), NULL);
PLOG(FATAL) << "execlp failed";
}
}
#endif
#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
void SIGTERMProfilingShutdown(int signal) {
Profiling::Stop();
struct sigaction sigact;
memset(&sigact, 0, sizeof(sigact));
sigact.sa_handler = SIG_DFL;
CHECK(sigaction(SIGTERM, &sigact, NULL) == 0);
raise(signal);
}
void SetUpProfilingShutdownHandler() {
struct sigaction sigact;
sigact.sa_handler = SIGTERMProfilingShutdown;
sigact.sa_flags = SA_RESETHAND;
sigemptyset(&sigact.sa_mask);
CHECK(sigaction(SIGTERM, &sigact, NULL) == 0);
}
#endif // !defined(OS_MACOSX) && !defined(OS_ANDROID)
#endif // OS_POSIX
struct MainFunction {
const char* name;
int (*function)(const content::MainFunctionParams&);
};
// Initializes the user data dir. Must be called before InitializeLocalState().
void InitializeUserDataDir() {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
base::FilePath user_data_dir =
command_line->GetSwitchValuePath(switches::kUserDataDir);
std::string process_type =
command_line->GetSwitchValueASCII(switches::kProcessType);
#if defined(OS_LINUX)
// On Linux, Chrome does not support running multiple copies under different
// DISPLAYs, so the profile directory can be specified in the environment to
// support the virtual desktop use-case.
if (user_data_dir.empty()) {
std::string user_data_dir_string;
scoped_ptr<base::Environment> environment(base::Environment::Create());
if (environment->GetVar("CHROME_USER_DATA_DIR", &user_data_dir_string) &&
base::IsStringUTF8(user_data_dir_string)) {
user_data_dir = base::FilePath::FromUTF8Unsafe(user_data_dir_string);
}
}
#endif
#if defined(OS_MACOSX) || defined(OS_WIN)
policy::path_parser::CheckUserDataDirPolicy(&user_data_dir);
#endif
// On Windows, trailing separators leave Chrome in a bad state.
// See crbug.com/464616.
if (user_data_dir.EndsWithSeparator())
user_data_dir = user_data_dir.StripTrailingSeparators();
const bool specified_directory_was_invalid = !user_data_dir.empty() &&
!PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA,
user_data_dir, false, true);
// Save inaccessible or invalid paths so the user may be prompted later.
if (specified_directory_was_invalid)
chrome::SetInvalidSpecifiedUserDataDir(user_data_dir);
// Warn and fail early if the process fails to get a user data directory.
if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) {
// If an invalid command-line or policy override was specified, the user
// will be given an error with that value. Otherwise, use the directory
// returned by PathService (or the fallback default directory) in the error.
if (!specified_directory_was_invalid) {
// PathService::Get() returns false and yields an empty path if it fails
// to create DIR_USER_DATA. Retrieve the default value manually to display
// a more meaningful error to the user in that case.
if (user_data_dir.empty())
chrome::GetDefaultUserDataDirectory(&user_data_dir);
chrome::SetInvalidSpecifiedUserDataDir(user_data_dir);
}
// The browser process (which is identified by an empty |process_type|) will
// handle the error later; other processes that need the dir crash here.
CHECK(process_type.empty()) << "Unable to get the user data directory "
<< "for process type: " << process_type;
}
// Append the fallback user data directory to the commandline. Otherwise,
// child or service processes will attempt to use the invalid directory.
if (specified_directory_was_invalid)
command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);
}
#if !defined(OS_ANDROID)
void InitLogging(const std::string& process_type) {
logging::OldFileDeletionState file_state =
logging::APPEND_TO_OLD_LOG_FILE;
if (process_type.empty()) {
file_state = logging::DELETE_OLD_LOG_FILE;
}
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
logging::InitChromeLogging(command_line, file_state);
}
#endif
#if !defined(CHROME_MULTIPLE_DLL_CHILD)
void RecordMainStartupMetrics() {
#if defined(OS_MACOSX) || defined(OS_WIN) || defined(OS_LINUX)
// Record the startup process creation time on supported platforms.
startup_metric_utils::RecordStartupProcessCreationTime(
base::CurrentProcessInfo::CreationTime());
#endif
// On Android the main entry point time is the time when the Java code starts.
// This happens before the shared library containing this code is even loaded.
// The Java startup code has recorded that time, but the C++ code can't fetch it
// from the Java side until it has initialized the JNI. See
// ChromeMainDelegateAndroid.
#if !defined(OS_ANDROID)
startup_metric_utils::RecordMainEntryPointTime(base::Time::Now());
#endif
}
#endif // !defined(CHROME_MULTIPLE_DLL_CHILD)
} // namespace
ChromeMainDelegate::ChromeMainDelegate() {
#if !defined(CHROME_MULTIPLE_DLL_CHILD)
// Record startup metrics in the browser process. For component builds, there
// is no way to know the type of process (process command line is not yet
// initialized), so the function below will also be called in renderers.
// This doesn't matter as it simply sets global variables.
RecordMainStartupMetrics();
#endif // !defined(CHROME_MULTIPLE_DLL_CHILD)
}
ChromeMainDelegate::~ChromeMainDelegate() {
}
bool ChromeMainDelegate::BasicStartupComplete(int* exit_code) {
#if defined(OS_CHROMEOS)
chromeos::BootTimesRecorder::Get()->SaveChromeMainStats();
#endif
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
#if defined(OS_WIN)
// Browser should not be sandboxed.
const bool is_browser = !command_line.HasSwitch(switches::kProcessType);
if (is_browser && IsSandboxedProcess()) {
*exit_code = chrome::RESULT_CODE_INVALID_SANDBOX_STATE;
return true;
}
#endif
#if defined(OS_MACOSX)
// Give the browser process a longer treadmill, since crashes
// there have more impact.
const bool is_browser = !command_line.HasSwitch(switches::kProcessType);
ObjcEvilDoers::ZombieEnable(true, is_browser ? 10000 : 1000);
SetUpBundleOverrides();
chrome::common::mac::EnableCFBundleBlocker();
#endif
Profiling::ProcessStarted();
base::trace_event::TraceLog::GetInstance()->SetArgumentFilterPredicate(
base::Bind(&IsTraceEventArgsWhitelisted));
#if defined(OS_WIN)
v8_breakpad_support::SetUp();
#endif
#if defined(OS_POSIX)
if (HandleVersionSwitches(command_line)) {
*exit_code = 0;
return true; // Got a --version switch; exit with a success error code.
}
#if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
// This will directly exit if the user asked for help.
HandleHelpSwitches(command_line);
#endif
#endif // OS_POSIX
#if defined(OS_WIN)
// Must do this before any other usage of command line!
if (HasDeprecatedArguments(command_line.GetCommandLineString())) {
*exit_code = 1;
return true;
}
if (UseHooks())
base::debug::InstallHandleHooks();
else
base::win::DisableHandleVerifier();
#endif
chrome::RegisterPathProvider();
#if defined(OS_CHROMEOS)
chromeos::RegisterPathProvider();
#endif
#if !defined(DISABLE_NACL) && defined(OS_LINUX)
nacl::RegisterPathProvider();
#endif
ContentSettingsPattern::SetNonWildcardDomainNonPortScheme(
extensions::kExtensionScheme);
// No support for ANDROID yet as DiagnosticsController needs wchar support.
// TODO(gspencer): That's not true anymore, or at least there are no w-string
// references anymore. Not sure if that means this can be enabled on Android or
// not though. As there is no easily accessible command line on Android, I'm
// not sure this is a big deal.
#if !defined(OS_ANDROID) && !defined(CHROME_MULTIPLE_DLL_CHILD)
// If we are in diagnostics mode this is the end of the line: after the
// diagnostics are run the process will invariably exit.
if (command_line.HasSwitch(switches::kDiagnostics)) {
diagnostics::DiagnosticsWriter::FormatType format =
diagnostics::DiagnosticsWriter::HUMAN;
if (command_line.HasSwitch(switches::kDiagnosticsFormat)) {
std::string format_str =
command_line.GetSwitchValueASCII(switches::kDiagnosticsFormat);
if (format_str == "machine") {
format = diagnostics::DiagnosticsWriter::MACHINE;
} else if (format_str == "log") {
format = diagnostics::DiagnosticsWriter::LOG;
} else {
DCHECK_EQ("human", format_str);
}
}
diagnostics::DiagnosticsWriter writer(format);
*exit_code = diagnostics::DiagnosticsController::GetInstance()->Run(
command_line, &writer);
diagnostics::DiagnosticsController::GetInstance()->ClearResults();
return true;
}
#endif
#if defined(OS_CHROMEOS)
// Initialize primary user homedir (in multi-profile session) as it may be
// passed as a command line switch.
base::FilePath homedir;
if (command_line.HasSwitch(chromeos::switches::kHomedir)) {
homedir = base::FilePath(
command_line.GetSwitchValueASCII(chromeos::switches::kHomedir));
PathService::OverrideAndCreateIfNeeded(
base::DIR_HOME, homedir, true, false);
}
// If we are recovering from a crash on ChromeOS, then we will do some
// recovery using the diagnostics module, and then continue on. We fake up a
// command line to tell it that we want it to recover, and to preserve the
// original command line.
if (command_line.HasSwitch(chromeos::switches::kLoginUser) ||
command_line.HasSwitch(switches::kDiagnosticsRecovery)) {
// The statistics subsystem needs get initialized soon enough for the
// statistics to be collected. It's safe to call this more than once.
base::StatisticsRecorder::Initialize();
base::CommandLine interim_command_line(command_line.GetProgram());
const char* const kSwitchNames[] = {switches::kUserDataDir, };
interim_command_line.CopySwitchesFrom(
command_line, kSwitchNames, arraysize(kSwitchNames));
interim_command_line.AppendSwitch(switches::kDiagnostics);
interim_command_line.AppendSwitch(switches::kDiagnosticsRecovery);
diagnostics::DiagnosticsWriter::FormatType format =
diagnostics::DiagnosticsWriter::LOG;
if (command_line.HasSwitch(switches::kDiagnosticsFormat)) {
std::string format_str =
command_line.GetSwitchValueASCII(switches::kDiagnosticsFormat);
if (format_str == "machine") {
format = diagnostics::DiagnosticsWriter::MACHINE;
} else if (format_str == "human") {
format = diagnostics::DiagnosticsWriter::HUMAN;
} else {
DCHECK_EQ("log", format_str);
}
}
diagnostics::DiagnosticsWriter writer(format);
int diagnostics_exit_code =
diagnostics::DiagnosticsController::GetInstance()->Run(command_line,
&writer);
if (diagnostics_exit_code) {
// Diagnostics has failed somehow, so we exit.
*exit_code = diagnostics_exit_code;
return true;
}
// Now we run the actual recovery tasks.
int recovery_exit_code =
diagnostics::DiagnosticsController::GetInstance()->RunRecovery(
command_line, &writer);
if (recovery_exit_code) {
// Recovery has failed somehow, so we exit.
*exit_code = recovery_exit_code;
return true;
}
} else { // Not running diagnostics or recovery.
diagnostics::DiagnosticsController::GetInstance()->RecordRegularStartup();
}
#endif
content::SetContentClient(&chrome_content_client_);
return false;
}
#if defined(OS_MACOSX)
void ChromeMainDelegate::InitMacCrashReporter(
const base::CommandLine& command_line,
const std::string& process_type) {
// TODO(mark): Right now, InitializeCrashpad() needs to be called after
// CommandLine::Init() and chrome::RegisterPathProvider(). Ideally, Crashpad
// initialization could occur sooner, preferably even before the framework
// dylib is even loaded, to catch potential early crashes.
const bool browser_process = process_type.empty();
const bool install_from_dmg_relauncher_process =
process_type == switches::kRelauncherProcess &&
command_line.HasSwitch(switches::kRelauncherProcessDMGDevice);
const bool initial_client =
browser_process || install_from_dmg_relauncher_process;
crash_reporter::InitializeCrashpad(initial_client, process_type);
if (!browser_process) {
std::string metrics_client_id =
command_line.GetSwitchValueASCII(switches::kMetricsClientID);
crash_keys::SetMetricsClientIdFromGUID(metrics_client_id);
}
// Mac Chrome is packaged with a main app bundle and a helper app bundle.
// The main app bundle should only be used for the browser process, so it
// should never see a --type switch (switches::kProcessType). Likewise,
// the helper should always have a --type switch.
//
// This check is done this late so there is already a call to
// base::mac::IsBackgroundOnlyProcess(), so there is no change in
// startup/initialization order.
// The helper's Info.plist marks it as a background only app.
if (base::mac::IsBackgroundOnlyProcess()) {
CHECK(command_line.HasSwitch(switches::kProcessType) &&
!process_type.empty())
<< "Helper application requires --type.";
} else {
CHECK(!command_line.HasSwitch(switches::kProcessType) &&
process_type.empty())
<< "Main application forbids --type, saw " << process_type;
}
}
#endif // defined(OS_MACOSX)
void ChromeMainDelegate::PreSandboxStartup() {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
std::string process_type =
command_line.GetSwitchValueASCII(switches::kProcessType);
#if defined(OS_POSIX)
crash_reporter::SetCrashReporterClient(g_chrome_crash_client.Pointer());
#endif
#if defined(OS_MACOSX)
// On the Mac, the child executable lives at a predefined location within
// the app bundle's versioned directory.
PathService::Override(content::CHILD_PROCESS_EXE,
chrome::GetVersionedDirectory().
Append(chrome::kHelperProcessExecutablePath));
InitMacCrashReporter(command_line, process_type);
#endif
#if defined(OS_WIN)
child_process_logging::Init();
#endif
#if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
// Create an instance of the CPU class to parse /proc/cpuinfo and cache
// cpu_brand info.
base::CPU cpu_info;
#endif
// Initialize the user data dir for any process type that needs it.
if (chrome::ProcessNeedsProfileDir(process_type))
InitializeUserDataDir();
// Register component_updater PathProvider after DIR_USER_DATA overidden by
// command line flags. Maybe move the chrome PathProvider down here also?
component_updater::RegisterPathProvider(chrome::DIR_USER_DATA);
// Enable Message Loop related state asap.
if (command_line.HasSwitch(switches::kMessageLoopHistogrammer))
base::MessageLoop::EnableHistogrammer(true);
#if !defined(OS_ANDROID) && !defined(OS_WIN)
// Android does InitLogging when library is loaded. Skip here.
// For windows we call InitLogging when the sandbox is initialized.
InitLogging(process_type);
#endif
#if defined(OS_WIN)
// TODO(zturner): Throbber icons are still stored in chrome.dll, this can be
// killed once those are merged into resources.pak. See
// GlassBrowserFrameView::InitThrobberIcons() and http://crbug.com/368327.
ui::SetResourcesDataDLL(_AtlBaseModule.GetResourceInstance());
#endif
if (SubprocessNeedsResourceBundle(process_type)) {
// Initialize ResourceBundle which handles files loaded from external
// sources. The language should have been passed in to us from the
// browser process as a command line flag.
#if defined(DISABLE_NACL)
DCHECK(command_line.HasSwitch(switches::kLang) ||
process_type == switches::kZygoteProcess ||
process_type == switches::kGpuProcess ||
process_type == switches::kPpapiBrokerProcess ||
process_type == switches::kPpapiPluginProcess);
#else
DCHECK(command_line.HasSwitch(switches::kLang) ||
process_type == switches::kZygoteProcess ||
process_type == switches::kGpuProcess ||
process_type == switches::kNaClLoaderProcess ||
process_type == switches::kPpapiBrokerProcess ||
process_type == switches::kPpapiPluginProcess);
#endif
// TODO(markusheintz): The command line flag --lang is actually processed
// by the CommandLinePrefStore, and made available through the PrefService
// via the preference prefs::kApplicationLocale. The browser process uses
// the --lang flag to pass the value of the PrefService in here. Maybe
// this value could be passed in a different way.
const std::string locale =
command_line.GetSwitchValueASCII(switches::kLang);
#if defined(OS_ANDROID)
// The renderer sandbox prevents us from accessing our .pak files directly.
// Therefore file descriptors to the .pak files that we need are passed in
// at process creation time.
auto global_descriptors = base::GlobalDescriptors::GetInstance();
int pak_fd = global_descriptors->Get(kAndroidLocalePakDescriptor);
base::MemoryMappedFile::Region pak_region =
global_descriptors->GetRegion(kAndroidLocalePakDescriptor);
ResourceBundle::InitSharedInstanceWithPakFileRegion(base::File(pak_fd),
pak_region);
int extra_pak_keys[] = {
kAndroidChrome100PercentPakDescriptor,
kAndroidUIResourcesPakDescriptor,
};
for (size_t i = 0; i < arraysize(extra_pak_keys); ++i) {
pak_fd = global_descriptors->Get(extra_pak_keys[i]);
pak_region = global_descriptors->GetRegion(extra_pak_keys[i]);
ResourceBundle::GetSharedInstance().AddDataPackFromFileRegion(
base::File(pak_fd), pak_region, ui::SCALE_FACTOR_100P);
}
base::i18n::SetICUDefaultLocale(locale);
const std::string loaded_locale = locale;
#else
const std::string loaded_locale =
ui::ResourceBundle::InitSharedInstanceWithLocale(
locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
base::FilePath resources_pack_path;
PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
ResourceBundle::GetSharedInstance().AddDataPackFromPath(
resources_pack_path, ui::SCALE_FACTOR_NONE);
#endif
CHECK(!loaded_locale.empty()) << "Locale could not be found for " <<
locale;
}
#if !defined(CHROME_MULTIPLE_DLL_BROWSER)
if (process_type == switches::kUtilityProcess ||
process_type == switches::kZygoteProcess) {
ChromeContentUtilityClient::PreSandboxStartup();
}
chrome::InitializePDF();
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX)
// Zygote needs to call InitCrashReporter() in RunZygote().
if (process_type != switches::kZygoteProcess) {
#if defined(OS_ANDROID)
if (process_type.empty()) {
breakpad::InitCrashReporter(process_type);
// TODO(crbug.com/551176): Exception reporting should work without
// ANDROID_JAVA_UI
#if BUILDFLAG(ANDROID_JAVA_UI)
chrome::android::InitJavaExceptionReporter();
#endif
} else {
breakpad::InitNonBrowserCrashReporterForAndroid(process_type);
}
#else // !defined(OS_ANDROID)
breakpad::InitCrashReporter(process_type);
#endif // defined(OS_ANDROID)
}
#endif // defined(OS_POSIX) && !defined(OS_MACOSX)
// After all the platform Breakpads have been initialized, store the command
// line for crash reporting.
crash_keys::SetCrashKeysFromCommandLine(command_line);
}
void ChromeMainDelegate::SandboxInitialized(const std::string& process_type) {
// Note: If you are adding a new process type below, be sure to adjust the
// AdjustLinuxOOMScore function too.
#if defined(OS_LINUX)
AdjustLinuxOOMScore(process_type);
#endif
#if defined(OS_WIN)
InitLogging(process_type);
SuppressWindowsErrorDialogs();
#endif
#if defined(CHROME_MULTIPLE_DLL_CHILD) || !defined(CHROME_MULTIPLE_DLL_BROWSER)
#if !defined(DISABLE_NACL)
ChromeContentClient::SetNaClEntryFunctions(
nacl_plugin::PPP_GetInterface,
nacl_plugin::PPP_InitializeModule,
nacl_plugin::PPP_ShutdownModule);
#endif
#if defined(ENABLE_PLUGINS) && defined(ENABLE_PDF)
ChromeContentClient::SetPDFEntryFunctions(
chrome_pdf::PPP_GetInterface,
chrome_pdf::PPP_InitializeModule,
chrome_pdf::PPP_ShutdownModule);
#endif
#endif
}
int ChromeMainDelegate::RunProcess(
const std::string& process_type,
const content::MainFunctionParams& main_function_params) {
// ANDROID doesn't support "service", so no ServiceProcessMain, and arraysize
// doesn't support empty array. So we comment out the block for Android.
#if !defined(OS_ANDROID)
static const MainFunction kMainFunctions[] = {
#if defined(ENABLE_PRINT_PREVIEW) && !defined(CHROME_MULTIPLE_DLL_CHILD)
{ switches::kServiceProcess, ServiceProcessMain },
#endif
#if defined(OS_MACOSX)
{ switches::kRelauncherProcess,
mac_relauncher::internal::RelauncherMain },
#endif
// This entry is not needed on Linux, where the NaCl loader
// process is launched via nacl_helper instead.
#if !defined(DISABLE_NACL) && !defined(CHROME_MULTIPLE_DLL_BROWSER) && \
!defined(OS_LINUX)
{ switches::kNaClLoaderProcess, NaClMain },
#else
{ "<invalid>", NULL }, // To avoid constant array of size 0
// when DISABLE_NACL and CHROME_MULTIPLE_DLL_CHILD
#endif // DISABLE_NACL
};
for (size_t i = 0; i < arraysize(kMainFunctions); ++i) {
if (process_type == kMainFunctions[i].name)
return kMainFunctions[i].function(main_function_params);
}
#endif
return -1;
}
void ChromeMainDelegate::ProcessExiting(const std::string& process_type) {
if (SubprocessNeedsResourceBundle(process_type))
ResourceBundle::CleanupSharedInstance();
#if !defined(OS_ANDROID)
logging::CleanupChromeLogging();
#else
// Android doesn't use InitChromeLogging, so we close the log file manually.
logging::CloseLogFile();
#endif // !defined(OS_ANDROID)
#if defined(OS_WIN)
base::debug::RemoveHandleHooks();
#endif
}
#if defined(OS_MACOSX)
bool ChromeMainDelegate::ProcessRegistersWithSystemProcess(
const std::string& process_type) {
#if defined(DISABLE_NACL)
return false;
#else
return process_type == switches::kNaClLoaderProcess;
#endif
}
bool ChromeMainDelegate::ShouldSendMachPort(const std::string& process_type) {
return process_type != switches::kRelauncherProcess &&
process_type != switches::kServiceProcess;
}
bool ChromeMainDelegate::DelaySandboxInitialization(
const std::string& process_type) {
#if !defined(DISABLE_NACL)
// NaClLoader does this in NaClMainPlatformDelegate::EnableSandbox().
// No sandbox needed for relauncher.
if (process_type == switches::kNaClLoaderProcess)
return true;
#endif
return process_type == switches::kRelauncherProcess;
}
#elif defined(OS_POSIX) && !defined(OS_ANDROID)
void ChromeMainDelegate::ZygoteStarting(
ScopedVector<content::ZygoteForkDelegate>* delegates) {
#if defined(OS_CHROMEOS)
chromeos::ReloadElfTextInHugePages();
#endif
#if !defined(DISABLE_NACL)
nacl::AddNaClZygoteForkDelegates(delegates);
#endif
}
void ChromeMainDelegate::ZygoteForked() {
Profiling::ProcessStarted();
if (Profiling::BeingProfiled()) {
base::debug::RestartProfilingAfterFork();
SetUpProfilingShutdownHandler();
}
// Needs to be called after we have chrome::DIR_USER_DATA. BrowserMain sets
// this up for the browser process in a different manner.
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
std::string process_type =
command_line->GetSwitchValueASCII(switches::kProcessType);
breakpad::InitCrashReporter(process_type);
// Reset the command line for the newly spawned process.
crash_keys::SetCrashKeysFromCommandLine(*command_line);
}
#endif // OS_MACOSX
content::ContentBrowserClient*
ChromeMainDelegate::CreateContentBrowserClient() {
#if defined(CHROME_MULTIPLE_DLL_CHILD)
return NULL;
#else
return g_chrome_content_browser_client.Pointer();
#endif
}
content::ContentPluginClient* ChromeMainDelegate::CreateContentPluginClient() {
#if defined(CHROME_MULTIPLE_DLL_BROWSER)
return NULL;
#else
return g_chrome_content_plugin_client.Pointer();
#endif
}
content::ContentRendererClient*
ChromeMainDelegate::CreateContentRendererClient() {
#if defined(CHROME_MULTIPLE_DLL_BROWSER)
return NULL;
#else
return g_chrome_content_renderer_client.Pointer();
#endif
}
content::ContentUtilityClient*
ChromeMainDelegate::CreateContentUtilityClient() {
#if defined(CHROME_MULTIPLE_DLL_BROWSER)
return NULL;
#else
return g_chrome_content_utility_client.Pointer();
#endif
}
bool ChromeMainDelegate::ShouldEnableProfilerRecording() {
switch (chrome::GetChannel()) {
case version_info::Channel::UNKNOWN:
case version_info::Channel::CANARY:
return true;
case version_info::Channel::DEV:
case version_info::Channel::BETA:
case version_info::Channel::STABLE:
default:
// Don't enable instrumentation.
return false;
}
}
| {
"content_hash": "52e515dbd6effd28b5a906a812a9db58",
"timestamp": "",
"source": "github",
"line_count": 893,
"max_line_length": 80,
"avg_line_length": 36.359462486002236,
"alnum_prop": 0.7134805506791093,
"repo_name": "js0701/chromium-crosswalk",
"id": "e4fa69afd1d1bb9270ed1a9bc6beca0c7797c2a7",
"size": "36899",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "chrome/app/chrome_main_delegate.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
#define FMX_USE_UNIQUE_PTR 1
#include <FMWrapper/FMXBinaryData.h>
#include <FMWrapper/FMXCalcEngine.h>
#include <FMWrapper/FMXClient.h>
#include <FMWrapper/FMXData.h>
#include <FMWrapper/FMXDateTime.h>
#include <FMWrapper/FMXExtern.h>
#include <FMWrapper/FMXFixPt.h>
#include <FMWrapper/FMXText.h>
#include <FMWrapper/FMXTextStyle.h>
#include <FMWrapper/FMXTypes.h>
#include <iostream>
#include <string>
#pragma mark -
#pragma mark Prototypes
#pragma mark -
const fmx::ptrtype Init ( FMX_ExternCallPtr /* pb */ );
void Shutdown ( void );
const fmx::QuadCharUniquePtr PluginID ( void );
const fmx::TextUniquePtr PluginPrefix ( void );
const fmx::TextUniquePtr PluginOptionsString ( void );
void GetString ( FMX_ExternCallPtr pb );
const fmx::errcode RegisterFunction ( const std::string prototype, const fmx::ExtPluginType function, const std::string description = "" );
void UnregisterFunctions ( void );
const fmx::TextUniquePtr FunctionName ( const fmx::TextUniquePtr& signature );
void NumberOfParameters ( const fmx::TextUniquePtr& signature, short& required, short& optional );
// pragma mark generates a warning C4068 in Visual Studio so that warning is disabled in VS
#pragma mark -
#pragma mark Enums, Defines & Globals
#pragma mark -
enum {
kSPOptionsString = 1
};
enum {
kSPManyParameters = -1,
kSPPrefixLength = 4,
kSPPluginIDLength = 5, // kSPPrefixLength = 4 + 1
kSPFirstFunction = 1000
};
enum {
kSPFirstParameter = 0,
kSPSecondParameter = 1,
kSPThirdParameter = 2,
kSPFourthParameter = 3,
kSPFifthParameter = 4
};
enum errors {
kSPNoError = 0,
};
//#define PLUGIN_NAME "SimplePlugin" // default is the project name (Xcode only)
// in Visual Studio set $(TargetName)
//#define PLUGIN_PREFIX "Simp" // default is the first four characters of the name
//#define PLUGIN_OPTIONS_STRING "1YnYYnn" // ask for everything ( "1nnYnnn" )
// Globals
short g_next_function; // used to keep track of the funciton id number
#pragma mark -
#pragma mark Functions
#pragma mark -
/* ****************************************************************************
Add code for plug-in functions here. Each function must be registered using
RegisterFunction in the Init function.
**************************************************************************** */
fmx::errcode Limit ( short /* function_id */, const fmx::ExprEnv& /* environment */, const fmx::DataVect& parameters, fmx::Data& reply );
fmx::errcode Limit ( short /* function_id */, const fmx::ExprEnv& /* environment */, const fmx::DataVect& parameters, fmx::Data& reply )
{
fmx::errcode error = kSPNoError;
// extract the first paramter to the function
fmx::FixPtUniquePtr number;
number->AssignFixPt ( parameters.AtAsNumber ( kSPFirstParameter ) );
fmx::FixPtUniquePtr lower_limit;
// only get the lower and upper limits if they exist (otherwise we crash)
if ( parameters.Size() >= 2 ) {
lower_limit->AssignFixPt ( parameters.AtAsNumber ( kSPSecondParameter ) );
} else {
lower_limit->AssignInt ( 0 );
}
fmx::FixPtUniquePtr upper_limit;
if ( parameters.Size() == 3 ) {
upper_limit->AssignFixPt ( parameters.AtAsNumber ( kSPThirdParameter ) );
} else {
fmx::int32 precision = number->GetPrecision();
upper_limit->AssignInt ( precision * 10 );
}
// apply the limits
if ( *number < *lower_limit ) {
number->AssignFixPt ( *lower_limit );
} else if ( *number > *upper_limit ) {
number->AssignFixPt ( *upper_limit );
}
// send the result of the calculation back to FileMaker
reply.SetAsNumber ( *number );
return error;
} // Limit
/* ***************************************************************************
Public plug-in functions
**************************************************************************** */
#pragma mark -
#pragma mark Plugin
#pragma mark -
/*
initalise the plug-in
perform any setup and register functions
*/
const fmx::ptrtype Init ( FMX_ExternCallPtr /* pb */ )
{
fmx::errcode error = kSPNoError;
fmx::ptrtype enable = kCurrentExtnVersion; // kDoNotEnable to prevent the plugin loading
// perform any initialisation and set-up globals
/*
register plug-in functions
functions must always be registered in the same order (to avoid breaking existing calculation in FM).
*/
error = RegisterFunction ( "Limit ( number {; lowerLimit ; upperLimit } )", Limit, "This function is Limit ed.!" );
if ( kSPNoError != error ) {
enable = (fmx::ptrtype)kDoNotEnable;
}
return enable;
} // Init
/*
clean up anything set up or allocated in Init
plug-in functions are un-registered automatically before this function is called
*/
void Shutdown ( void )
{
}
/*
the main entry point for the plug-in
calls from fmp go either here or directly to registered plugin function
see also the options for FMX_ExternCallSwitch in FMXExtern.h
only edit to add additonal call handlers
*/
void FMX_ENTRYPT FMExternCallProc ( FMX_ExternCallPtr pb )
{
switch ( pb->whichCall )
{
case kFMXT_GetString:
GetString ( pb );
break;
case kFMXT_Init:
g_next_function = kSPFirstFunction;
pb->result = Init ( pb );
break;
case kFMXT_Shutdown:
UnregisterFunctions ( );
Shutdown ( );
break;
}
} // FMExternCallProc
/* ***************************************************************************
You should not need to edit anything in this section.
*************************************************************************** */
#pragma mark -
#pragma mark Private Functions
#pragma mark -
// get the plug-in name or options string and hand back to FileMaker
void GetString ( FMX_ExternCallPtr pb )
{
fmx::TextUniquePtr string;
switch ( pb->parm1 )
{
case kSPOptionsString:
case kFMXT_OptionsStr:
string->SetText ( *PluginOptionsString() );
break;
case kFMXT_NameStr:
case kFMXT_AppConfigStr:
string->Assign ( PLUGIN_NAME );
break;
// default:
}
string->GetUnicode ( (fmx::unichar16*)(pb->result), 0, fmx::Text::kSize_End );
} // GetString
/*
register plug-in functions
RegisterFunction takes three parameters:
1. the external function signature as it should appear in the calcuation dialogs but
without the prefix i.e. Explode ( timer ) rather than Bomb_Explode ( timer )
2. the plug-in function to call when the function is used in FileMaker
3. (optional) a description of the function ... default: ""
*/
const fmx::errcode RegisterFunction ( const std::string prototype, const fmx::ExtPluginType function, const std::string description )
{
fmx::TextUniquePtr underscore;
underscore->Assign ( "_" );
fmx::TextUniquePtr function_protoype;
function_protoype->Assign ( prototype.c_str() );
function_protoype->InsertText ( *PluginPrefix(), 0 );
function_protoype->InsertText ( *underscore, kSPPrefixLength );
fmx::TextUniquePtr function_description;
function_description->Assign ( description.c_str() );
fmx::TextUniquePtr name;
name->SetText ( *FunctionName ( function_protoype ) );
short required_parameters = 0;
short optional_rarameters = 0;
NumberOfParameters ( function_protoype, required_parameters, optional_rarameters );
const fmx::uint32 function_flags = fmx::ExprEnv::kDisplayInAllDialogs;
const fmx::errcode error = fmx::ExprEnv::RegisterExternalFunctionEx ( *PluginID(),
g_next_function,
*name,
*function_protoype,
*function_description,
required_parameters,
required_parameters + optional_rarameters,
function_flags,
function
);
if ( error != kSPNoError ) {
std::cerr << "Error registering: " << prototype << "! Error #: " << error << std::endl;
}
++g_next_function;
return error;
} // RegisterFunction
// unregister all registered functions
void UnregisterFunctions ( void )
{
for ( short i = kSPFirstFunction ; i < g_next_function ; i++ ) {
fmx::ExprEnv::UnRegisterExternalFunction ( *PluginID(), i );
}
}
// automaticlly generate the PluginID from the prefix
const fmx::QuadCharUniquePtr PluginID ( void )
{
fmx::TextUniquePtr prefix;
prefix->SetText ( *PluginPrefix() );
char buffer[kSPPluginIDLength];
prefix->GetBytes ( buffer, kSPPluginIDLength );
fmx::QuadCharUniquePtr id ( buffer[0], buffer[1], buffer[2], buffer[3] );
return id;
}
// use the defined prefix if it exists otherwise use the first four characters of the name
const fmx::TextUniquePtr PluginPrefix ( void )
{
fmx::TextUniquePtr prefix;
#ifdef PLUGIN_PREFIX
prefix->Assign ( PLUGIN_PREFIX );
#else
prefix->Assign ( PLUGIN_NAME );
prefix->DeleteText ( kSPPrefixLength );
#endif
return prefix;
}
// use the options string defined above otherwise turn everything on
const fmx::TextUniquePtr PluginOptionsString ( void )
{
fmx::TextUniquePtr optionsString;
#ifdef PLUGIN_OPTIONS_STRING
optionsString->Assign ( PLUGIN_OPTIONS_STRING );
#else
optionsString->Assign ( "1YnYYnn" );
#endif
optionsString->InsertText ( *PluginPrefix(), 0 );
return optionsString;
}
// extract the function name from a function signature/prototype
const fmx::TextUniquePtr FunctionName ( const fmx::TextUniquePtr& signature )
{
fmx::TextUniquePtr separator;
separator->Assign ( "(" );
fmx::uint32 parameters_start = signature->Find ( *separator, 0 );
if ( parameters_start == fmx::Text::kSize_Invalid ) {
parameters_start = fmx::Text::kSize_End;
} else {
// there may or may not be spaces between the function name and the bracket
fmx::TextUniquePtr space;
space->Assign ( " " );
fmx::uint32 last = parameters_start - 1;
while ( signature->Find ( *space, last ) == last ) {
--last;
}
parameters_start = last + 1;
}
fmx::TextUniquePtr name;
name->SetText ( *signature, 0, parameters_start );
return name;
} // FunctionName
// calculate the number of required and optional parameters from a function signature/prototye
void NumberOfParameters ( const fmx::TextUniquePtr& signature, short& required, short& optional )
{
required = 0;
optional = 0;
fmx::TextUniquePtr separator;
separator->Assign ( "(" );
const fmx::uint32 parameters_start = signature->Find ( *separator, 0 );
if ( parameters_start == fmx::Text::kSize_Invalid ) {
return;
}
// we have parameters
fmx::TextUniquePtr semi_colon;
semi_colon->Assign ( ";" );
fmx::TextUniquePtr curly_bracket;
curly_bracket->Assign ( "{" );
bool has_optional_parameters = false;
fmx::uint32 next = parameters_start;
while ( next != fmx::Text::kSize_Invalid ) {
++next;
const fmx::uint32 next_semi_colon = signature->Find ( *semi_colon, next );
const fmx::uint32 next_curly_bracket = signature->Find ( *curly_bracket, next );
if ( next_curly_bracket < next_semi_colon && has_optional_parameters == false ) {
next = signature->Find ( *semi_colon, next_curly_bracket + 1 );
++required;
has_optional_parameters = true;
fmx::TextUniquePtr elipsis;
elipsis->Assign ( "…" );
if ( signature->Find ( *elipsis, next_curly_bracket + 1 ) != fmx::Text::kSize_Invalid ) {
optional = -1;
next = fmx::Text::kSize_Invalid;
} else {
fmx::TextUniquePtr faux_elipsis;
faux_elipsis->Assign ( "..." );
if ( signature->Find ( *faux_elipsis, next_curly_bracket + 1 ) != fmx::Text::kSize_Invalid ) {
optional = kSPManyParameters;
next = fmx::Text::kSize_Invalid;
}
}
} else {
next = next_semi_colon;
if ( has_optional_parameters == true ) {
++optional;
} else {
++required;
}
}
}
} // NumberOfParameters
| {
"content_hash": "1cd3f23601402269a81a0c8ff95c5c9f",
"timestamp": "",
"source": "github",
"line_count": 481,
"max_line_length": 139,
"avg_line_length": 24.295218295218294,
"alnum_prop": 0.6571966455587883,
"repo_name": "minstral/SimplePlugin",
"id": "c4cd6c9c24e498474a1625e5a8a1f20f94063bbf",
"size": "11886",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SimplePlugin.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "11886"
}
],
"symlink_target": ""
} |
import pickle
from django.conf import settings
from django_redis.serializers.pickle import PickleSerializer
from testil import eq
def test_highest_protocol():
assert pickle.HIGHEST_PROTOCOL <= 5, """
The highest pickle procol supported by Python at time of writing
this test is 5. Support for newer protocols must be added or the
default version used by libraries such as django_redis must be
limited to 5 or less so pickles written by a newer Python can be
read by an older Python after a downgrade.
"""
def test_pickle_5():
eq(pickle.loads(b'\x80\x05\x89.'), False)
def test_dump_and_load_all_protocols():
def test(protocol):
eq(pickle.loads(pickle.dumps(False, protocol=protocol)), False)
for protocol in range(1, pickle.HIGHEST_PROTOCOL + 1):
yield test, protocol
def test_django_redis_protocol():
# Override default pickle protocol to allow smoother Python upgrades.
# Heroics like this will not be necessary once we have upgraded to a
# version of django_redis that uses pickle.DEFAULT_PROTOCOL. See:
# https://github.com/jazzband/django-redis/issues/547
# https://github.com/jazzband/django-redis/pull/555
#
# This test may be removed after upgrading django_redis.
# In the mean time, test for effective protocol override in settings.py
pkl = PickleSerializer(settings.CACHES['default'].get("OPTIONS", {}))
eq(pkl.dumps(False)[1], pickle.DEFAULT_PROTOCOL)
| {
"content_hash": "8120429fb06d8f7e0df611ca0a7eae5e",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 75,
"avg_line_length": 37.225,
"alnum_prop": 0.7118871725990598,
"repo_name": "dimagi/commcare-hq",
"id": "ff72f8866bbe887c5eae3e97ab5df7c953dd58ef",
"size": "1489",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "corehq/tests/test_pickle.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "82928"
},
{
"name": "Dockerfile",
"bytes": "2341"
},
{
"name": "HTML",
"bytes": "2589268"
},
{
"name": "JavaScript",
"bytes": "5889543"
},
{
"name": "Jinja",
"bytes": "3693"
},
{
"name": "Less",
"bytes": "176180"
},
{
"name": "Makefile",
"bytes": "1622"
},
{
"name": "PHP",
"bytes": "2232"
},
{
"name": "PLpgSQL",
"bytes": "66704"
},
{
"name": "Python",
"bytes": "21779773"
},
{
"name": "Roff",
"bytes": "150"
},
{
"name": "Shell",
"bytes": "67473"
}
],
"symlink_target": ""
} |
package org.apache.ignite.internal;
import java.io.Externalizable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidObjectException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Properties;
import java.util.Timer;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import javax.management.JMException;
import javax.management.ObjectName;
import org.apache.ignite.IgniteAtomicLong;
import org.apache.ignite.IgniteAtomicReference;
import org.apache.ignite.IgniteAtomicSequence;
import org.apache.ignite.IgniteAtomicStamped;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteClientDisconnectedException;
import org.apache.ignite.IgniteCompute;
import org.apache.ignite.IgniteCountDownLatch;
import org.apache.ignite.IgniteDataStreamer;
import org.apache.ignite.IgniteEvents;
import org.apache.ignite.IgniteException;
import org.apache.ignite.IgniteFileSystem;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.IgniteMessaging;
import org.apache.ignite.IgnitePortables;
import org.apache.ignite.IgniteQueue;
import org.apache.ignite.IgniteScheduler;
import org.apache.ignite.IgniteServices;
import org.apache.ignite.IgniteSet;
import org.apache.ignite.IgniteSystemProperties;
import org.apache.ignite.IgniteTransactions;
import org.apache.ignite.Ignition;
import org.apache.ignite.cache.affinity.Affinity;
import org.apache.ignite.cluster.ClusterGroup;
import org.apache.ignite.cluster.ClusterMetrics;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.CollectionConfiguration;
import org.apache.ignite.configuration.ConnectorConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.configuration.NearCacheConfiguration;
import org.apache.ignite.internal.cluster.ClusterGroupAdapter;
import org.apache.ignite.internal.cluster.IgniteClusterEx;
import org.apache.ignite.internal.managers.GridManager;
import org.apache.ignite.internal.managers.checkpoint.GridCheckpointManager;
import org.apache.ignite.internal.managers.collision.GridCollisionManager;
import org.apache.ignite.internal.managers.communication.GridIoManager;
import org.apache.ignite.internal.managers.deployment.GridDeploymentManager;
import org.apache.ignite.internal.managers.discovery.GridDiscoveryManager;
import org.apache.ignite.internal.managers.eventstorage.GridEventStorageManager;
import org.apache.ignite.internal.managers.failover.GridFailoverManager;
import org.apache.ignite.internal.managers.indexing.GridIndexingManager;
import org.apache.ignite.internal.managers.loadbalancer.GridLoadBalancerManager;
import org.apache.ignite.internal.managers.swapspace.GridSwapSpaceManager;
import org.apache.ignite.internal.processors.GridProcessor;
import org.apache.ignite.internal.processors.affinity.GridAffinityProcessor;
import org.apache.ignite.internal.processors.cache.GridCacheAdapter;
import org.apache.ignite.internal.processors.cache.GridCacheContext;
import org.apache.ignite.internal.processors.cache.GridCacheProcessor;
import org.apache.ignite.internal.processors.cache.GridCacheUtilityKey;
import org.apache.ignite.internal.processors.cache.IgniteCacheProxy;
import org.apache.ignite.internal.processors.cache.IgniteInternalCache;
import org.apache.ignite.internal.processors.cache.portable.CacheObjectPortableProcessor;
import org.apache.ignite.internal.processors.cache.portable.CacheObjectPortableProcessorImpl;
import org.apache.ignite.internal.processors.cacheobject.IgniteCacheObjectProcessor;
import org.apache.ignite.internal.processors.clock.GridClockSyncProcessor;
import org.apache.ignite.internal.processors.closure.GridClosureProcessor;
import org.apache.ignite.internal.processors.cluster.ClusterProcessor;
import org.apache.ignite.internal.processors.continuous.GridContinuousProcessor;
import org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor;
import org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor;
import org.apache.ignite.internal.processors.hadoop.Hadoop;
import org.apache.ignite.internal.processors.job.GridJobProcessor;
import org.apache.ignite.internal.processors.jobmetrics.GridJobMetricsProcessor;
import org.apache.ignite.internal.processors.nodevalidation.DiscoveryNodeValidationProcessor;
import org.apache.ignite.internal.processors.nodevalidation.OsDiscoveryNodeValidationProcessor;
import org.apache.ignite.internal.processors.offheap.GridOffHeapProcessor;
import org.apache.ignite.internal.processors.platform.PlatformNoopProcessor;
import org.apache.ignite.internal.processors.platform.PlatformProcessor;
import org.apache.ignite.internal.processors.plugin.IgnitePluginProcessor;
import org.apache.ignite.internal.processors.port.GridPortProcessor;
import org.apache.ignite.internal.processors.port.GridPortRecord;
import org.apache.ignite.internal.processors.query.GridQueryProcessor;
import org.apache.ignite.internal.processors.resource.GridResourceProcessor;
import org.apache.ignite.internal.processors.resource.GridSpringResourceContext;
import org.apache.ignite.internal.processors.rest.GridRestProcessor;
import org.apache.ignite.internal.processors.security.GridSecurityProcessor;
import org.apache.ignite.internal.processors.segmentation.GridSegmentationProcessor;
import org.apache.ignite.internal.processors.service.GridServiceProcessor;
import org.apache.ignite.internal.processors.session.GridTaskSessionProcessor;
import org.apache.ignite.internal.processors.task.GridTaskProcessor;
import org.apache.ignite.internal.processors.timeout.GridTimeoutProcessor;
import org.apache.ignite.internal.util.GridEnumCache;
import org.apache.ignite.internal.util.GridTimerTask;
import org.apache.ignite.internal.util.future.GridFinishedFuture;
import org.apache.ignite.internal.util.future.GridFutureAdapter;
import org.apache.ignite.internal.util.future.IgniteFutureImpl;
import org.apache.ignite.internal.util.lang.GridAbsClosure;
import org.apache.ignite.internal.util.tostring.GridToStringExclude;
import org.apache.ignite.internal.util.typedef.C1;
import org.apache.ignite.internal.util.typedef.CI1;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.X;
import org.apache.ignite.internal.util.typedef.internal.A;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.LT;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.SB;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteFuture;
import org.apache.ignite.lang.IgnitePredicate;
import org.apache.ignite.lang.IgniteProductVersion;
import org.apache.ignite.lifecycle.LifecycleAware;
import org.apache.ignite.lifecycle.LifecycleBean;
import org.apache.ignite.lifecycle.LifecycleEventType;
import org.apache.ignite.marshaller.MarshallerExclusions;
import org.apache.ignite.marshaller.optimized.OptimizedMarshaller;
import org.apache.ignite.marshaller.portable.PortableMarshaller;
import org.apache.ignite.mxbean.ClusterLocalNodeMetricsMXBean;
import org.apache.ignite.mxbean.IgniteMXBean;
import org.apache.ignite.mxbean.ThreadPoolMXBean;
import org.apache.ignite.plugin.IgnitePlugin;
import org.apache.ignite.plugin.PluginNotFoundException;
import org.apache.ignite.plugin.PluginProvider;
import org.apache.ignite.spi.IgniteSpi;
import org.apache.ignite.spi.IgniteSpiVersionCheckException;
import org.jetbrains.annotations.Nullable;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_CONFIG_URL;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_DAEMON;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_NO_ASCII;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_STARVATION_CHECK_INTERVAL;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_SUCCESS_FILE;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_UPDATE_NOTIFIER;
import static org.apache.ignite.IgniteSystemProperties.getBoolean;
import static org.apache.ignite.IgniteSystemProperties.snapshot;
import static org.apache.ignite.internal.GridKernalState.DISCONNECTED;
import static org.apache.ignite.internal.GridKernalState.STARTED;
import static org.apache.ignite.internal.GridKernalState.STARTING;
import static org.apache.ignite.internal.GridKernalState.STOPPED;
import static org.apache.ignite.internal.GridKernalState.STOPPING;
import static org.apache.ignite.internal.IgniteComponentType.IGFS;
import static org.apache.ignite.internal.IgniteComponentType.IGFS_HELPER;
import static org.apache.ignite.internal.IgniteComponentType.SCHEDULE;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_BUILD_DATE;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_BUILD_VER;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_CLIENT_MODE;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_CONSISTENCY_CHECK_SKIPPED;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DAEMON;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_DEPLOYMENT_MODE;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_GRID_NAME;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_IPS;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JIT_NAME;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JMX_PORT;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JVM_ARGS;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_JVM_PID;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_LANG_RUNTIME;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MACS;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MARSHALLER;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_NODE_CONSISTENT_ID;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PEER_CLASSLOADING;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PHY_RAM;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PORTABLE_PROTO_VER;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_PREFIX;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_RESTART_ENABLED;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_REST_PORT_RANGE;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_SPI_CLASS;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_USER_NAME;
import static org.apache.ignite.internal.IgniteVersionUtils.ACK_VER_STR;
import static org.apache.ignite.internal.IgniteVersionUtils.BUILD_TSTAMP_STR;
import static org.apache.ignite.internal.IgniteVersionUtils.COPYRIGHT;
import static org.apache.ignite.internal.IgniteVersionUtils.REV_HASH_STR;
import static org.apache.ignite.internal.IgniteVersionUtils.VER;
import static org.apache.ignite.internal.IgniteVersionUtils.VER_STR;
import static org.apache.ignite.lifecycle.LifecycleEventType.AFTER_NODE_START;
import static org.apache.ignite.lifecycle.LifecycleEventType.BEFORE_NODE_START;
/**
* Ignite kernal.
* <p/>
* See <a href="http://en.wikipedia.org/wiki/Kernal">http://en.wikipedia.org/wiki/Kernal</a> for information on the
* misspelling.
*/
public class IgniteKernal implements IgniteEx, IgniteMXBean, Externalizable {
/** */
private static final long serialVersionUID = 0L;
/** Ignite site that is shown in log messages. */
static final String SITE = "ignite.apache.org";
/** System line separator. */
private static final String NL = U.nl();
/** Periodic version check delay. */
private static final long PERIODIC_VER_CHECK_DELAY = 1000 * 60 * 60; // Every hour.
/** Periodic version check delay. */
private static final long PERIODIC_VER_CHECK_CONN_TIMEOUT = 10 * 1000; // 10 seconds.
/** Periodic starvation check interval. */
private static final long PERIODIC_STARVATION_CHECK_FREQ = 1000 * 30;
/** */
@GridToStringExclude
private GridKernalContextImpl ctx;
/** Configuration. */
private IgniteConfiguration cfg;
/** */
@SuppressWarnings({"FieldAccessedSynchronizedAndUnsynchronized"})
@GridToStringExclude
private GridLoggerProxy log;
/** */
private String gridName;
/** */
@GridToStringExclude
private ObjectName kernalMBean;
/** */
@GridToStringExclude
private ObjectName locNodeMBean;
/** */
@GridToStringExclude
private ObjectName pubExecSvcMBean;
/** */
@GridToStringExclude
private ObjectName sysExecSvcMBean;
/** */
@GridToStringExclude
private ObjectName mgmtExecSvcMBean;
/** */
@GridToStringExclude
private ObjectName p2PExecSvcMBean;
/** */
@GridToStringExclude
private ObjectName restExecSvcMBean;
/** Kernal start timestamp. */
private long startTime = U.currentTimeMillis();
/** Spring context, potentially {@code null}. */
private GridSpringResourceContext rsrcCtx;
/** */
@GridToStringExclude
private Timer updateNtfTimer;
/** */
@GridToStringExclude
private GridTimeoutProcessor.CancelableTask starveTask;
/** */
@GridToStringExclude
private GridTimeoutProcessor.CancelableTask metricsLogTask;
/** Indicate error on grid stop. */
@GridToStringExclude
private boolean errOnStop;
/** Scheduler. */
@GridToStringExclude
private IgniteScheduler scheduler;
/** Kernal gateway. */
@GridToStringExclude
private final AtomicReference<GridKernalGateway> gw = new AtomicReference<>();
/** Stop guard. */
@GridToStringExclude
private final AtomicBoolean stopGuard = new AtomicBoolean();
/** Version checker. */
@GridToStringExclude
private GridUpdateNotifier verChecker;
/**
* No-arg constructor is required by externalization.
*/
public IgniteKernal() {
this(null);
}
/**
* @param rsrcCtx Optional Spring application context.
*/
public IgniteKernal(@Nullable GridSpringResourceContext rsrcCtx) {
this.rsrcCtx = rsrcCtx;
}
/** {@inheritDoc} */
@Override public IgniteClusterEx cluster() {
return ctx.cluster().get();
}
/** {@inheritDoc} */
@Override public ClusterNode localNode() {
return ctx.cluster().get().localNode();
}
/** {@inheritDoc} */
@Override public IgniteCompute compute() {
return ((ClusterGroupAdapter)ctx.cluster().get().forServers()).compute();
}
/** {@inheritDoc} */
@Override public IgniteMessaging message() {
return ctx.cluster().get().message();
}
/** {@inheritDoc} */
@Override public IgniteEvents events() {
return ctx.cluster().get().events();
}
/** {@inheritDoc} */
@Override public IgniteServices services() {
return ((ClusterGroupAdapter)ctx.cluster().get().forServers()).services();
}
/** {@inheritDoc} */
@Override public ExecutorService executorService() {
return ctx.cluster().get().executorService();
}
/** {@inheritDoc} */
@Override public final IgniteCompute compute(ClusterGroup grp) {
return ((ClusterGroupAdapter)grp).compute();
}
/** {@inheritDoc} */
@Override public final IgniteMessaging message(ClusterGroup prj) {
return ((ClusterGroupAdapter)prj).message();
}
/** {@inheritDoc} */
@Override public final IgniteEvents events(ClusterGroup grp) {
return ((ClusterGroupAdapter) grp).events();
}
/** {@inheritDoc} */
@Override public IgniteServices services(ClusterGroup grp) {
return ((ClusterGroupAdapter)grp).services();
}
/** {@inheritDoc} */
@Override public ExecutorService executorService(ClusterGroup grp) {
return ((ClusterGroupAdapter)grp).executorService();
}
/** {@inheritDoc} */
@Override public String name() {
return gridName;
}
/** {@inheritDoc} */
@Override public String getCopyright() {
return COPYRIGHT;
}
/** {@inheritDoc} */
@Override public long getStartTimestamp() {
return startTime;
}
/** {@inheritDoc} */
@Override public String getStartTimestampFormatted() {
return DateFormat.getDateTimeInstance().format(new Date(startTime));
}
/** {@inheritDoc} */
@Override public long getUpTime() {
return U.currentTimeMillis() - startTime;
}
/** {@inheritDoc} */
@Override public String getUpTimeFormatted() {
return X.timeSpan2HMSM(U.currentTimeMillis() - startTime);
}
/** {@inheritDoc} */
@Override public String getFullVersion() {
return VER_STR + '-' + BUILD_TSTAMP_STR;
}
/** {@inheritDoc} */
@Override public String getCheckpointSpiFormatted() {
assert cfg != null;
return Arrays.toString(cfg.getCheckpointSpi());
}
/** {@inheritDoc} */
@Override public String getSwapSpaceSpiFormatted() {
assert cfg != null;
return cfg.getSwapSpaceSpi().toString();
}
/** {@inheritDoc} */
@Override public String getCommunicationSpiFormatted() {
assert cfg != null;
return cfg.getCommunicationSpi().toString();
}
/** {@inheritDoc} */
@Override public String getDeploymentSpiFormatted() {
assert cfg != null;
return cfg.getDeploymentSpi().toString();
}
/** {@inheritDoc} */
@Override public String getDiscoverySpiFormatted() {
assert cfg != null;
return cfg.getDiscoverySpi().toString();
}
/** {@inheritDoc} */
@Override public String getEventStorageSpiFormatted() {
assert cfg != null;
return cfg.getEventStorageSpi().toString();
}
/** {@inheritDoc} */
@Override public String getCollisionSpiFormatted() {
assert cfg != null;
return cfg.getCollisionSpi().toString();
}
/** {@inheritDoc} */
@Override public String getFailoverSpiFormatted() {
assert cfg != null;
return Arrays.toString(cfg.getFailoverSpi());
}
/** {@inheritDoc} */
@Override public String getLoadBalancingSpiFormatted() {
assert cfg != null;
return Arrays.toString(cfg.getLoadBalancingSpi());
}
/** {@inheritDoc} */
@Override public String getOsInformation() {
return U.osString();
}
/** {@inheritDoc} */
@Override public String getJdkInformation() {
return U.jdkString();
}
/** {@inheritDoc} */
@Override public String getOsUser() {
return System.getProperty("user.name");
}
/** {@inheritDoc} */
@Override public void printLastErrors() {
ctx.exceptionRegistry().printErrors(log);
}
/** {@inheritDoc} */
@Override public String getVmName() {
return ManagementFactory.getRuntimeMXBean().getName();
}
/** {@inheritDoc} */
@Override public String getInstanceName() {
return gridName;
}
/** {@inheritDoc} */
@Override public String getExecutorServiceFormatted() {
assert cfg != null;
return String.valueOf(cfg.getPublicThreadPoolSize());
}
/** {@inheritDoc} */
@Override public String getIgniteHome() {
assert cfg != null;
return cfg.getIgniteHome();
}
/** {@inheritDoc} */
@Override public String getGridLoggerFormatted() {
assert cfg != null;
return cfg.getGridLogger().toString();
}
/** {@inheritDoc} */
@Override public String getMBeanServerFormatted() {
assert cfg != null;
return cfg.getMBeanServer().toString();
}
/** {@inheritDoc} */
@Override public UUID getLocalNodeId() {
assert cfg != null;
return cfg.getNodeId();
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public Collection<String> getUserAttributesFormatted() {
assert cfg != null;
return F.transform(cfg.getUserAttributes().entrySet(), new C1<Map.Entry<String, ?>, String>() {
@Override public String apply(Map.Entry<String, ?> e) {
return e.getKey() + ", " + e.getValue().toString();
}
});
}
/** {@inheritDoc} */
@Override public boolean isPeerClassLoadingEnabled() {
assert cfg != null;
return cfg.isPeerClassLoadingEnabled();
}
/** {@inheritDoc} */
@Override public Collection<String> getLifecycleBeansFormatted() {
LifecycleBean[] beans = cfg.getLifecycleBeans();
return F.isEmpty(beans) ? Collections.<String>emptyList() : F.transform(beans, F.<LifecycleBean>string());
}
/**
* @param name New attribute name.
* @param val New attribute value.
* @throws IgniteCheckedException If duplicated SPI name found.
*/
private void add(String name, @Nullable Serializable val) throws IgniteCheckedException {
assert name != null;
if (ctx.addNodeAttribute(name, val) != null) {
if (name.endsWith(ATTR_SPI_CLASS))
// User defined duplicated names for the different SPIs.
throw new IgniteCheckedException("Failed to set SPI attribute. Duplicated SPI name found: " +
name.substring(0, name.length() - ATTR_SPI_CLASS.length()));
// Otherwise it's a mistake of setting up duplicated attribute.
assert false : "Duplicate attribute: " + name;
}
}
/**
* Notifies life-cycle beans of grid event.
*
* @param evt Grid event.
* @throws IgniteCheckedException If user threw exception during start.
*/
@SuppressWarnings({"CatchGenericClass"})
private void notifyLifecycleBeans(LifecycleEventType evt) throws IgniteCheckedException {
if (!cfg.isDaemon() && cfg.getLifecycleBeans() != null) {
for (LifecycleBean bean : cfg.getLifecycleBeans())
if (bean != null) {
try {
bean.onLifecycleEvent(evt);
}
catch (Exception e) {
throw new IgniteCheckedException(e);
}
}
}
}
/**
* Notifies life-cycle beans of grid event.
*
* @param evt Grid event.
*/
@SuppressWarnings({"CatchGenericClass"})
private void notifyLifecycleBeansEx(LifecycleEventType evt) {
try {
notifyLifecycleBeans(evt);
}
// Catch generic throwable to secure against user assertions.
catch (Throwable e) {
U.error(log, "Failed to notify lifecycle bean (safely ignored) [evt=" + evt +
", gridName=" + gridName + ']', e);
if (e instanceof Error)
throw (Error)e;
}
}
/**
* @param cfg Configuration to use.
* @param utilityCachePool Utility cache pool.
* @param execSvc Executor service.
* @param sysExecSvc System executor service.
* @param p2pExecSvc P2P executor service.
* @param mgmtExecSvc Management executor service.
* @param igfsExecSvc IGFS executor service.
* @param restExecSvc Reset executor service.
* @param errHnd Error handler to use for notification about startup problems.
* @throws IgniteCheckedException Thrown in case of any errors.
*/
@SuppressWarnings({"CatchGenericClass", "unchecked"})
public void start(final IgniteConfiguration cfg,
ExecutorService utilityCachePool,
ExecutorService marshCachePool,
final ExecutorService execSvc,
final ExecutorService sysExecSvc,
ExecutorService p2pExecSvc,
ExecutorService mgmtExecSvc,
ExecutorService igfsExecSvc,
ExecutorService restExecSvc,
GridAbsClosure errHnd)
throws IgniteCheckedException
{
gw.compareAndSet(null, new GridKernalGatewayImpl(cfg.getGridName()));
GridKernalGateway gw = this.gw.get();
gw.writeLock();
try {
switch (gw.getState()) {
case STARTED: {
U.warn(log, "Grid has already been started (ignored).");
return;
}
case STARTING: {
U.warn(log, "Grid is already in process of being started (ignored).");
return;
}
case STOPPING: {
throw new IgniteCheckedException("Grid is in process of being stopped");
}
case STOPPED: {
break;
}
}
gw.setState(STARTING);
}
finally {
gw.writeUnlock();
}
assert cfg != null;
// Make sure we got proper configuration.
validateCommon(cfg);
gridName = cfg.getGridName();
this.cfg = cfg;
log = (GridLoggerProxy)cfg.getGridLogger().getLogger(getClass().getName() +
(gridName != null ? '%' + gridName : ""));
RuntimeMXBean rtBean = ManagementFactory.getRuntimeMXBean();
// Ack various information.
ackAsciiLogo();
ackConfigUrl();
ackDaemon();
ackOsInfo();
ackLanguageRuntime();
ackRemoteManagement();
ackVmArguments(rtBean);
ackClassPaths(rtBean);
ackSystemProperties();
ackEnvironmentVariables();
ackCacheConfiguration();
ackP2pConfiguration();
// Run background network diagnostics.
GridDiagnostic.runBackgroundCheck(gridName, execSvc, log);
boolean notifyEnabled = IgniteSystemProperties.getBoolean(IGNITE_UPDATE_NOTIFIER, true);
// Ack 3-rd party licenses location.
if (log.isInfoEnabled() && cfg.getIgniteHome() != null)
log.info("3-rd party licenses can be found at: " + cfg.getIgniteHome() + File.separatorChar + "libs" +
File.separatorChar + "licenses");
// Check that user attributes are not conflicting
// with internally reserved names.
for (String name : cfg.getUserAttributes().keySet())
if (name.startsWith(ATTR_PREFIX))
throw new IgniteCheckedException("User attribute has illegal name: '" + name + "'. Note that all names " +
"starting with '" + ATTR_PREFIX + "' are reserved for internal use.");
// Ack local node user attributes.
logNodeUserAttributes();
// Ack configuration.
ackSpis();
List<PluginProvider> plugins = U.allPluginProviders();
// Spin out SPIs & managers.
try {
ctx = new GridKernalContextImpl(log,
this,
cfg,
gw,
utilityCachePool,
marshCachePool,
execSvc,
sysExecSvc,
p2pExecSvc,
mgmtExecSvc,
igfsExecSvc,
restExecSvc,
plugins);
cfg.getMarshaller().setContext(ctx.marshallerContext());
startProcessor(new ClusterProcessor(ctx));
fillNodeAttributes();
U.onGridStart();
// Start and configure resource processor first as it contains resources used
// by all other managers and processors.
GridResourceProcessor rsrcProc = new GridResourceProcessor(ctx);
rsrcProc.setSpringContext(rsrcCtx);
scheduler = new IgniteSchedulerImpl(ctx);
startProcessor(rsrcProc);
// Inject resources into lifecycle beans.
if (!cfg.isDaemon() && cfg.getLifecycleBeans() != null) {
for (LifecycleBean bean : cfg.getLifecycleBeans()) {
if (bean != null)
rsrcProc.inject(bean);
}
}
// Lifecycle notification.
notifyLifecycleBeans(BEFORE_NODE_START);
// Starts lifecycle aware components.
U.startLifecycleAware(lifecycleAwares(cfg));
addHelper(IGFS_HELPER.create(F.isEmpty(cfg.getFileSystemConfiguration())));
startProcessor(new IgnitePluginProcessor(ctx, cfg, plugins));
verChecker = null;
if (notifyEnabled) {
try {
verChecker = new GridUpdateNotifier(gridName, VER_STR, gw, ctx.plugins().allProviders(), false);
updateNtfTimer = new Timer("ignite-update-notifier-timer", true);
// Setup periodic version check.
updateNtfTimer.scheduleAtFixedRate(new UpdateNotifierTimerTask(this, execSvc, verChecker),
0, PERIODIC_VER_CHECK_DELAY);
}
catch (IgniteCheckedException e) {
if (log.isDebugEnabled())
log.debug("Failed to create GridUpdateNotifier: " + e);
}
}
// Off-heap processor has no dependencies.
startProcessor(new GridOffHeapProcessor(ctx));
// Closure processor should be started before all others
// (except for resource processor), as many components can depend on it.
startProcessor(new GridClosureProcessor(ctx));
// Start some other processors (order & place is important).
startProcessor(new GridPortProcessor(ctx));
startProcessor(new GridJobMetricsProcessor(ctx));
// Timeout processor needs to be started before managers,
// as managers may depend on it.
startProcessor(new GridTimeoutProcessor(ctx));
// Start security processors.
startProcessor(createComponent(GridSecurityProcessor.class, ctx));
// Start SPI managers.
// NOTE: that order matters as there are dependencies between managers.
startManager(new GridIoManager(ctx));
startManager(new GridCheckpointManager(ctx));
startManager(new GridEventStorageManager(ctx));
startManager(new GridDeploymentManager(ctx));
startManager(new GridLoadBalancerManager(ctx));
startManager(new GridFailoverManager(ctx));
startManager(new GridCollisionManager(ctx));
startManager(new GridSwapSpaceManager(ctx));
startManager(new GridIndexingManager(ctx));
ackSecurity();
// Assign discovery manager to context before other processors start so they
// are able to register custom event listener.
GridManager discoMgr = new GridDiscoveryManager(ctx);
ctx.add(discoMgr, false);
// Start processors before discovery manager, so they will
// be able to start receiving messages once discovery completes.
startProcessor(createComponent(DiscoveryNodeValidationProcessor.class, ctx));
startProcessor(new GridClockSyncProcessor(ctx));
startProcessor(new GridAffinityProcessor(ctx));
startProcessor(createComponent(GridSegmentationProcessor.class, ctx));
startProcessor(createComponent(IgniteCacheObjectProcessor.class, ctx));
startProcessor(new GridCacheProcessor(ctx));
startProcessor(new GridQueryProcessor(ctx));
startProcessor(new GridTaskSessionProcessor(ctx));
startProcessor(new GridJobProcessor(ctx));
startProcessor(new GridTaskProcessor(ctx));
startProcessor((GridProcessor)SCHEDULE.createOptional(ctx));
startProcessor(new GridRestProcessor(ctx));
startProcessor(new DataStreamProcessor(ctx));
startProcessor((GridProcessor)IGFS.create(ctx, F.isEmpty(cfg.getFileSystemConfiguration())));
startProcessor(new GridContinuousProcessor(ctx));
startProcessor((GridProcessor)(cfg.isPeerClassLoadingEnabled() ?
IgniteComponentType.HADOOP.create(ctx, true): // No-op when peer class loading is enabled.
IgniteComponentType.HADOOP.createIfInClassPath(ctx, cfg.getHadoopConfiguration() != null)));
startProcessor(new GridServiceProcessor(ctx));
startProcessor(new DataStructuresProcessor(ctx));
startProcessor(createComponent(PlatformProcessor.class, ctx));
// Start plugins.
for (PluginProvider provider : ctx.plugins().allProviders()) {
ctx.add(new GridPluginComponent(provider));
provider.start(ctx.plugins().pluginContextForProvider(provider));
}
gw.writeLock();
try {
gw.setState(STARTED);
// Start discovery manager last to make sure that grid is fully initialized.
startManager(discoMgr);
}
finally {
gw.writeUnlock();
}
// Check whether physical RAM is not exceeded.
checkPhysicalRam();
// Suggest configuration optimizations.
suggestOptimizations(cfg);
// Notify discovery manager the first to make sure that topology is discovered.
ctx.discovery().onKernalStart();
// Notify IO manager the second so further components can send and receive messages.
ctx.io().onKernalStart();
// Callbacks.
for (GridComponent comp : ctx) {
// Skip discovery manager.
if (comp instanceof GridDiscoveryManager)
continue;
// Skip IO manager.
if (comp instanceof GridIoManager)
continue;
if (!skipDaemon(comp))
comp.onKernalStart();
}
// Register MBeans.
registerKernalMBean();
registerLocalNodeMBean();
registerExecutorMBeans(execSvc, sysExecSvc, p2pExecSvc, mgmtExecSvc, restExecSvc);
// Lifecycle bean notifications.
notifyLifecycleBeans(AFTER_NODE_START);
}
catch (Throwable e) {
IgniteSpiVersionCheckException verCheckErr = X.cause(e, IgniteSpiVersionCheckException.class);
if (verCheckErr != null)
U.error(log, verCheckErr.getMessage());
else if (X.hasCause(e, InterruptedException.class, IgniteInterruptedCheckedException.class))
U.warn(log, "Grid startup routine has been interrupted (will rollback).");
else
U.error(log, "Got exception while starting (will rollback startup routine).", e);
errHnd.apply();
stop(true);
if (e instanceof Error)
throw e;
else if (e instanceof IgniteCheckedException)
throw (IgniteCheckedException)e;
else
throw new IgniteCheckedException(e);
}
// Mark start timestamp.
startTime = U.currentTimeMillis();
String intervalStr = IgniteSystemProperties.getString(IGNITE_STARVATION_CHECK_INTERVAL);
// Start starvation checker if enabled.
boolean starveCheck = !isDaemon() && !"0".equals(intervalStr);
if (starveCheck) {
final long interval = F.isEmpty(intervalStr) ? PERIODIC_STARVATION_CHECK_FREQ : Long.parseLong(intervalStr);
starveTask = ctx.timeout().schedule(new Runnable() {
/** Last completed task count. */
private long lastCompletedCnt;
@Override public void run() {
if (!(execSvc instanceof ThreadPoolExecutor))
return;
ThreadPoolExecutor exec = (ThreadPoolExecutor)execSvc;
long completedCnt = exec.getCompletedTaskCount();
// If all threads are active and no task has completed since last time and there is
// at least one waiting request, then it is possible starvation.
if (exec.getPoolSize() == exec.getActiveCount() && completedCnt == lastCompletedCnt &&
!exec.getQueue().isEmpty())
LT.warn(log, null, "Possible thread pool starvation detected (no task completed in last " +
interval + "ms, is executorService pool size large enough?)");
lastCompletedCnt = completedCnt;
}
}, interval, interval);
}
long metricsLogFreq = cfg.getMetricsLogFrequency();
if (metricsLogFreq > 0) {
metricsLogTask = ctx.timeout().schedule(new Runnable() {
private final DecimalFormat dblFmt = new DecimalFormat("#.##");
@Override public void run() {
if (log.isInfoEnabled()) {
try {
ClusterMetrics m = cluster().localNode().metrics();
double cpuLoadPct = m.getCurrentCpuLoad() * 100;
double avgCpuLoadPct = m.getAverageCpuLoad() * 100;
double gcPct = m.getCurrentGcCpuLoad() * 100;
long heapUsed = m.getHeapMemoryUsed();
long heapMax = m.getHeapMemoryMaximum();
long heapUsedInMBytes = heapUsed / 1024 / 1024;
long heapCommInMBytes = m.getHeapMemoryCommitted() / 1024 / 1024;
double freeHeapPct = heapMax > 0 ? ((double)((heapMax - heapUsed) * 100)) / heapMax : -1;
int hosts = 0;
int nodes = 0;
int cpus = 0;
try {
ClusterMetrics metrics = cluster().metrics();
Collection<ClusterNode> nodes0 = cluster().nodes();
hosts = U.neighborhood(nodes0).size();
nodes = metrics.getTotalNodes();
cpus = metrics.getTotalCpus();
}
catch (IgniteException ignore) {
// No-op.
}
int pubPoolActiveThreads = 0;
int pubPoolIdleThreads = 0;
int pubPoolQSize = 0;
if (execSvc instanceof ThreadPoolExecutor) {
ThreadPoolExecutor exec = (ThreadPoolExecutor)execSvc;
int poolSize = exec.getPoolSize();
pubPoolActiveThreads = Math.min(poolSize, exec.getActiveCount());
pubPoolIdleThreads = poolSize - pubPoolActiveThreads;
pubPoolQSize = exec.getQueue().size();
}
int sysPoolActiveThreads = 0;
int sysPoolIdleThreads = 0;
int sysPoolQSize = 0;
if (sysExecSvc instanceof ThreadPoolExecutor) {
ThreadPoolExecutor exec = (ThreadPoolExecutor)sysExecSvc;
int poolSize = exec.getPoolSize();
sysPoolActiveThreads = Math.min(poolSize, exec.getActiveCount());
sysPoolIdleThreads = poolSize - sysPoolActiveThreads;
sysPoolQSize = exec.getQueue().size();
}
String id = U.id8(localNode().id());
String msg = NL +
"Metrics for local node (to disable set 'metricsLogFrequency' to 0)" + NL +
" ^-- Node [id=" + id + ", name=" + name() + "]" + NL +
" ^-- H/N/C [hosts=" + hosts + ", nodes=" + nodes + ", CPUs=" + cpus + "]" + NL +
" ^-- CPU [cur=" + dblFmt.format(cpuLoadPct) + "%, avg=" +
dblFmt.format(avgCpuLoadPct) + "%, GC=" + dblFmt.format(gcPct) + "%]" + NL +
" ^-- Heap [used=" + dblFmt.format(heapUsedInMBytes) + "MB, free=" +
dblFmt.format(freeHeapPct) + "%, comm=" + dblFmt.format(heapCommInMBytes) + "MB]" + NL +
" ^-- Public thread pool [active=" + pubPoolActiveThreads + ", idle=" +
pubPoolIdleThreads + ", qSize=" + pubPoolQSize + "]" + NL +
" ^-- System thread pool [active=" + sysPoolActiveThreads + ", idle=" +
sysPoolIdleThreads + ", qSize=" + sysPoolQSize + "]" + NL +
" ^-- Outbound messages queue [size=" + m.getOutboundMessagesQueueSize() + "]";
log.info(msg);
}
catch (IgniteClientDisconnectedException ignore) {
// No-op.
}
}
}
}, metricsLogFreq, metricsLogFreq);
}
ctx.performance().logSuggestions(log, gridName);
U.quietAndInfo(log, "To start Console Management & Monitoring run ignitevisorcmd.{sh|bat}");
ackStart(rtBean);
if (!isDaemon())
ctx.discovery().ackTopology();
}
/**
* Validates common configuration parameters.
*
* @param cfg Configuration.
*/
private void validateCommon(IgniteConfiguration cfg) {
A.notNull(cfg.getNodeId(), "cfg.getNodeId()");
A.notNull(cfg.getMBeanServer(), "cfg.getMBeanServer()");
A.notNull(cfg.getGridLogger(), "cfg.getGridLogger()");
A.notNull(cfg.getMarshaller(), "cfg.getMarshaller()");
A.notNull(cfg.getUserAttributes(), "cfg.getUserAttributes()");
// All SPIs should be non-null.
A.notNull(cfg.getSwapSpaceSpi(), "cfg.getSwapSpaceSpi()");
A.notNull(cfg.getCheckpointSpi(), "cfg.getCheckpointSpi()");
A.notNull(cfg.getCommunicationSpi(), "cfg.getCommunicationSpi()");
A.notNull(cfg.getDeploymentSpi(), "cfg.getDeploymentSpi()");
A.notNull(cfg.getDiscoverySpi(), "cfg.getDiscoverySpi()");
A.notNull(cfg.getEventStorageSpi(), "cfg.getEventStorageSpi()");
A.notNull(cfg.getCollisionSpi(), "cfg.getCollisionSpi()");
A.notNull(cfg.getFailoverSpi(), "cfg.getFailoverSpi()");
A.notNull(cfg.getLoadBalancingSpi(), "cfg.getLoadBalancingSpi()");
A.notNull(cfg.getIndexingSpi(), "cfg.getIndexingSpi()");
A.ensure(cfg.getNetworkTimeout() > 0, "cfg.getNetworkTimeout() > 0");
A.ensure(cfg.getNetworkSendRetryDelay() > 0, "cfg.getNetworkSendRetryDelay() > 0");
A.ensure(cfg.getNetworkSendRetryCount() > 0, "cfg.getNetworkSendRetryCount() > 0");
}
/**
* Checks whether physical RAM is not exceeded.
*/
@SuppressWarnings("ConstantConditions")
private void checkPhysicalRam() {
long ram = ctx.discovery().localNode().attribute(ATTR_PHY_RAM);
if (ram != -1) {
String macs = ctx.discovery().localNode().attribute(ATTR_MACS);
long totalHeap = 0;
for (ClusterNode node : ctx.discovery().allNodes()) {
if (macs.equals(node.attribute(ATTR_MACS))) {
long heap = node.metrics().getHeapMemoryMaximum();
if (heap != -1)
totalHeap += heap;
}
}
if (totalHeap > ram) {
U.quietAndWarn(log, "Attempting to start more nodes than physical RAM " +
"available on current host (this can cause significant slowdown)");
}
}
}
/**
* @param cfg Configuration to check for possible performance issues.
*/
private void suggestOptimizations(IgniteConfiguration cfg) {
GridPerformanceSuggestions perf = ctx.performance();
if (ctx.collision().enabled())
perf.add("Disable collision resolution (remove 'collisionSpi' from configuration)");
if (ctx.checkpoint().enabled())
perf.add("Disable checkpoints (remove 'checkpointSpi' from configuration)");
if (cfg.isPeerClassLoadingEnabled())
perf.add("Disable peer class loading (set 'peerClassLoadingEnabled' to false)");
if (cfg.isMarshalLocalJobs())
perf.add("Disable local jobs marshalling (set 'marshalLocalJobs' to false)");
if (cfg.getIncludeEventTypes() != null && cfg.getIncludeEventTypes().length != 0)
perf.add("Disable grid events (remove 'includeEventTypes' from configuration)");
if (OptimizedMarshaller.available() && !(cfg.getMarshaller() instanceof OptimizedMarshaller))
perf.add("Enable optimized marshaller (set 'marshaller' to " +
OptimizedMarshaller.class.getSimpleName() + ')');
}
/**
* Creates attributes map and fills it in.
*
* @throws IgniteCheckedException thrown if was unable to set up attribute.
*/
@SuppressWarnings({"SuspiciousMethodCalls", "unchecked", "TypeMayBeWeakened"})
private void fillNodeAttributes() throws IgniteCheckedException {
final String[] incProps = cfg.getIncludeProperties();
try {
// Stick all environment settings into node attributes.
for (Map.Entry<String, String> sysEntry : System.getenv().entrySet()) {
String name = sysEntry.getKey();
if (incProps == null || U.containsStringArray(incProps, name, true) ||
U.isVisorNodeStartProperty(name) || U.isVisorRequiredProperty(name))
ctx.addNodeAttribute(name, sysEntry.getValue());
}
if (log.isDebugEnabled())
log.debug("Added environment properties to node attributes.");
}
catch (SecurityException e) {
throw new IgniteCheckedException("Failed to add environment properties to node attributes due to " +
"security violation: " + e.getMessage());
}
try {
// Stick all system properties into node's attributes overwriting any
// identical names from environment properties.
for (Map.Entry<Object, Object> e : snapshot().entrySet()) {
String key = (String)e.getKey();
if (incProps == null || U.containsStringArray(incProps, key, true) ||
U.isVisorRequiredProperty(key)) {
Object val = ctx.nodeAttribute(key);
if (val != null && !val.equals(e.getValue()))
U.warn(log, "System property will override environment variable with the same name: " + key);
ctx.addNodeAttribute(key, e.getValue());
}
}
if (log.isDebugEnabled())
log.debug("Added system properties to node attributes.");
}
catch (SecurityException e) {
throw new IgniteCheckedException("Failed to add system properties to node attributes due to security " +
"violation: " + e.getMessage());
}
// Add local network IPs and MACs.
String ips = F.concat(U.allLocalIps(), ", "); // Exclude loopbacks.
String macs = F.concat(U.allLocalMACs(), ", "); // Only enabled network interfaces.
// Ack network context.
if (log.isInfoEnabled()) {
log.info("Non-loopback local IPs: " + (F.isEmpty(ips) ? "N/A" : ips));
log.info("Enabled local MACs: " + (F.isEmpty(macs) ? "N/A" : macs));
}
// Warn about loopback.
if (ips.isEmpty() && macs.isEmpty())
U.warn(log, "Ignite is starting on loopback address... Only nodes on the same physical " +
"computer can participate in topology.",
"Ignite is starting on loopback address...");
// Stick in network context into attributes.
add(ATTR_IPS, (ips.isEmpty() ? "" : ips));
add(ATTR_MACS, (macs.isEmpty() ? "" : macs));
// Stick in some system level attributes
add(ATTR_JIT_NAME, U.getCompilerMx() == null ? "" : U.getCompilerMx().getName());
add(ATTR_BUILD_VER, VER_STR);
add(ATTR_BUILD_DATE, BUILD_TSTAMP_STR);
add(ATTR_MARSHALLER, cfg.getMarshaller().getClass().getName());
add(ATTR_USER_NAME, System.getProperty("user.name"));
add(ATTR_GRID_NAME, gridName);
add(ATTR_PORTABLE_PROTO_VER, cfg.getMarshaller() instanceof PortableMarshaller ?
((PortableMarshaller)cfg.getMarshaller()).getProtocolVersion().toString() :
PortableMarshaller.DFLT_PORTABLE_PROTO_VER.toString());
add(ATTR_PEER_CLASSLOADING, cfg.isPeerClassLoadingEnabled());
add(ATTR_DEPLOYMENT_MODE, cfg.getDeploymentMode());
add(ATTR_LANG_RUNTIME, getLanguage());
add(ATTR_JVM_PID, U.jvmPid());
add(ATTR_CLIENT_MODE, cfg.isClientMode());
add(ATTR_CONSISTENCY_CHECK_SKIPPED, getBoolean(IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK));
if (cfg.getConsistentId() != null)
add(ATTR_NODE_CONSISTENT_ID, cfg.getConsistentId());
// Build a string from JVM arguments, because parameters with spaces are split.
SB jvmArgs = new SB(512);
for (String arg : U.jvmArgs()) {
if (arg.startsWith("-"))
jvmArgs.a("@@@");
else
jvmArgs.a(' ');
jvmArgs.a(arg);
}
// Add it to attributes.
add(ATTR_JVM_ARGS, jvmArgs.toString());
// Check daemon system property and override configuration if it's set.
if (isDaemon())
add(ATTR_DAEMON, "true");
// In case of the parsing error, JMX remote disabled or port not being set
// node attribute won't be set.
if (isJmxRemoteEnabled()) {
String portStr = System.getProperty("com.sun.management.jmxremote.port");
if (portStr != null)
try {
add(ATTR_JMX_PORT, Integer.parseInt(portStr));
}
catch (NumberFormatException ignore) {
// No-op.
}
}
// Whether restart is enabled and stick the attribute.
add(ATTR_RESTART_ENABLED, Boolean.toString(isRestartEnabled()));
// Save port range, port numbers will be stored by rest processor at runtime.
if (cfg.getConnectorConfiguration() != null)
add(ATTR_REST_PORT_RANGE, cfg.getConnectorConfiguration().getPortRange());
// Stick in SPI versions and classes attributes.
addSpiAttributes(cfg.getCollisionSpi());
addSpiAttributes(cfg.getSwapSpaceSpi());
addSpiAttributes(cfg.getDiscoverySpi());
addSpiAttributes(cfg.getFailoverSpi());
addSpiAttributes(cfg.getCommunicationSpi());
addSpiAttributes(cfg.getEventStorageSpi());
addSpiAttributes(cfg.getCheckpointSpi());
addSpiAttributes(cfg.getLoadBalancingSpi());
addSpiAttributes(cfg.getDeploymentSpi());
// Set user attributes for this node.
if (cfg.getUserAttributes() != null) {
for (Map.Entry<String, ?> e : cfg.getUserAttributes().entrySet()) {
if (ctx.hasNodeAttribute(e.getKey()))
U.warn(log, "User or internal attribute has the same name as environment or system " +
"property and will take precedence: " + e.getKey());
ctx.addNodeAttribute(e.getKey(), e.getValue());
}
}
}
/**
* Add SPI version and class attributes into node attributes.
*
* @param spiList Collection of SPIs to get attributes from.
* @throws IgniteCheckedException Thrown if was unable to set up attribute.
*/
private void addSpiAttributes(IgniteSpi... spiList) throws IgniteCheckedException {
for (IgniteSpi spi : spiList) {
Class<? extends IgniteSpi> spiCls = spi.getClass();
add(U.spiAttribute(spi, ATTR_SPI_CLASS), spiCls.getName());
}
}
/** @throws IgniteCheckedException If registration failed. */
private void registerKernalMBean() throws IgniteCheckedException {
try {
kernalMBean = U.registerMBean(
cfg.getMBeanServer(),
cfg.getGridName(),
"Kernal",
getClass().getSimpleName(),
this,
IgniteMXBean.class);
if (log.isDebugEnabled())
log.debug("Registered kernal MBean: " + kernalMBean);
}
catch (JMException e) {
kernalMBean = null;
throw new IgniteCheckedException("Failed to register kernal MBean.", e);
}
}
/** @throws IgniteCheckedException If registration failed. */
private void registerLocalNodeMBean() throws IgniteCheckedException {
ClusterLocalNodeMetricsMXBean mbean = new ClusterLocalNodeMetricsMXBeanImpl(ctx.discovery().localNode());
try {
locNodeMBean = U.registerMBean(
cfg.getMBeanServer(),
cfg.getGridName(),
"Kernal",
mbean.getClass().getSimpleName(),
mbean,
ClusterLocalNodeMetricsMXBean.class);
if (log.isDebugEnabled())
log.debug("Registered local node MBean: " + locNodeMBean);
}
catch (JMException e) {
locNodeMBean = null;
throw new IgniteCheckedException("Failed to register local node MBean.", e);
}
}
/** @throws IgniteCheckedException If registration failed. */
private void registerExecutorMBeans(ExecutorService execSvc, ExecutorService sysExecSvc, ExecutorService p2pExecSvc,
ExecutorService mgmtExecSvc, ExecutorService restExecSvc) throws IgniteCheckedException {
pubExecSvcMBean = registerExecutorMBean(execSvc, "GridExecutionExecutor");
sysExecSvcMBean = registerExecutorMBean(sysExecSvc, "GridSystemExecutor");
mgmtExecSvcMBean = registerExecutorMBean(mgmtExecSvc, "GridManagementExecutor");
p2PExecSvcMBean = registerExecutorMBean(p2pExecSvc, "GridClassLoadingExecutor");
ConnectorConfiguration clientCfg = cfg.getConnectorConfiguration();
if (clientCfg != null)
restExecSvcMBean = registerExecutorMBean(restExecSvc, "GridRestExecutor");
}
/**
* @param exec Executor service to register.
* @param name Property name for executor.
* @return Name for created MBean.
* @throws IgniteCheckedException If registration failed.
*/
private ObjectName registerExecutorMBean(ExecutorService exec, String name) throws IgniteCheckedException {
assert exec != null;
try {
ObjectName res = U.registerMBean(
cfg.getMBeanServer(),
cfg.getGridName(),
"Thread Pools",
name,
new ThreadPoolMXBeanAdapter(exec),
ThreadPoolMXBean.class);
if (log.isDebugEnabled())
log.debug("Registered executor service MBean: " + res);
return res;
}
catch (JMException e) {
throw new IgniteCheckedException("Failed to register executor service MBean [name=" + name + ", exec=" + exec + ']',
e);
}
}
/**
* Unregisters given mbean.
*
* @param mbean MBean to unregister.
* @return {@code True} if successfully unregistered, {@code false} otherwise.
*/
private boolean unregisterMBean(@Nullable ObjectName mbean) {
if (mbean != null)
try {
cfg.getMBeanServer().unregisterMBean(mbean);
if (log.isDebugEnabled())
log.debug("Unregistered MBean: " + mbean);
return true;
}
catch (JMException e) {
U.error(log, "Failed to unregister MBean.", e);
return false;
}
return true;
}
/**
* @param mgr Manager to start.
* @throws IgniteCheckedException Throw in case of any errors.
*/
private void startManager(GridManager mgr) throws IgniteCheckedException {
// Add manager to registry before it starts to avoid cases when manager is started
// but registry does not have it yet.
ctx.add(mgr);
try {
if (!skipDaemon(mgr))
mgr.start();
}
catch (IgniteCheckedException e) {
throw new IgniteCheckedException("Failed to start manager: " + mgr, e);
}
}
/**
* @param proc Processor to start.
* @throws IgniteCheckedException Thrown in case of any error.
*/
private void startProcessor(GridProcessor proc) throws IgniteCheckedException {
ctx.add(proc);
try {
if (!skipDaemon(proc))
proc.start();
}
catch (IgniteCheckedException e) {
throw new IgniteCheckedException("Failed to start processor: " + proc, e);
}
}
/**
* Add helper.
*
* @param helper Helper.
*/
private void addHelper(Object helper) {
ctx.addHelper(helper);
}
/**
* Gets "on" or "off" string for given boolean value.
*
* @param b Boolean value to convert.
* @return Result string.
*/
private String onOff(boolean b) {
return b ? "on" : "off";
}
/**
*
* @return Whether or not REST is enabled.
*/
private boolean isRestEnabled() {
assert cfg != null;
return cfg.getConnectorConfiguration() != null;
}
/**
* Acks remote management.
*/
private void ackRemoteManagement() {
assert log != null;
if (!log.isInfoEnabled())
return;
SB sb = new SB();
sb.a("Remote Management [");
boolean on = isJmxRemoteEnabled();
sb.a("restart: ").a(onOff(isRestartEnabled())).a(", ");
sb.a("REST: ").a(onOff(isRestEnabled())).a(", ");
sb.a("JMX (");
sb.a("remote: ").a(onOff(on));
if (on) {
sb.a(", ");
sb.a("port: ").a(System.getProperty("com.sun.management.jmxremote.port", "<n/a>")).a(", ");
sb.a("auth: ").a(onOff(Boolean.getBoolean("com.sun.management.jmxremote.authenticate"))).a(", ");
// By default SSL is enabled, that's why additional check for null is needed.
// See http://docs.oracle.com/javase/6/docs/technotes/guides/management/agent.html
sb.a("ssl: ").a(onOff(Boolean.getBoolean("com.sun.management.jmxremote.ssl") ||
System.getProperty("com.sun.management.jmxremote.ssl") == null));
}
sb.a(")");
sb.a(']');
log.info(sb.toString());
}
/**
* Acks configuration URL.
*/
private void ackConfigUrl() {
assert log != null;
if (log.isInfoEnabled())
log.info("Config URL: " + System.getProperty(IGNITE_CONFIG_URL, "n/a"));
}
/**
* Acks ASCII-logo. Thanks to http://patorjk.com/software/taag
*/
private void ackAsciiLogo() {
assert log != null;
if (System.getProperty(IGNITE_NO_ASCII) == null) {
String ver = "ver. " + ACK_VER_STR;
// Big thanks to: http://patorjk.com/software/taag
// Font name "Small Slant"
if (log.isInfoEnabled()) {
log.info(NL + NL +
">>> __________ ________________ " + NL +
">>> / _/ ___/ |/ / _/_ __/ __/ " + NL +
">>> _/ // (7 7 // / / / / _/ " + NL +
">>> /___/\\___/_/|_/___/ /_/ /___/ " + NL +
">>> " + NL +
">>> " + ver + NL +
">>> " + COPYRIGHT + NL +
">>> " + NL +
">>> Ignite documentation: " + "http://" + SITE + NL
);
}
if (log.isQuiet()) {
U.quiet(false,
" __________ ________________ ",
" / _/ ___/ |/ / _/_ __/ __/ ",
" _/ // (7 7 // / / / / _/ ",
"/___/\\___/_/|_/___/ /_/ /___/ ",
"",
ver,
COPYRIGHT,
"",
"Ignite documentation: " + "http://" + SITE,
"",
"Quiet mode.");
String fileName = log.fileName();
if (fileName != null)
U.quiet(false, " ^-- Logging to file '" + fileName + '\'');
U.quiet(false,
" ^-- To see **FULL** console log here add -DIGNITE_QUIET=false or \"-v\" to ignite.{sh|bat}",
"");
}
}
}
/**
* Prints start info.
*
* @param rtBean Java runtime bean.
*/
private void ackStart(RuntimeMXBean rtBean) {
ClusterNode locNode = localNode();
if (log.isQuiet()) {
U.quiet(false, "");
U.quiet(false, "Ignite node started OK (id=" + U.id8(locNode.id()) +
(F.isEmpty(gridName) ? "" : ", grid=" + gridName) + ')');
}
if (log.isInfoEnabled()) {
log.info("");
String ack = "Ignite ver. " + VER_STR + '#' + BUILD_TSTAMP_STR + "-sha1:" + REV_HASH_STR;
String dash = U.dash(ack.length());
SB sb = new SB();
for (GridPortRecord rec : ctx.ports().records())
sb.a(rec.protocol()).a(":").a(rec.port()).a(" ");
String str =
NL + NL +
">>> " + dash + NL +
">>> " + ack + NL +
">>> " + dash + NL +
">>> OS name: " + U.osString() + NL +
">>> CPU(s): " + locNode.metrics().getTotalCpus() + NL +
">>> Heap: " + U.heapSize(locNode, 2) + "GB" + NL +
">>> VM name: " + rtBean.getName() + NL +
">>> Grid name: " + gridName + NL +
">>> Local node [" +
"ID=" + locNode.id().toString().toUpperCase() +
", order=" + locNode.order() + ", clientMode=" + ctx.clientNode() +
"]" + NL +
">>> Local node addresses: " + U.addressesAsString(locNode) + NL +
">>> Local ports: " + sb + NL;
log.info(str);
}
}
/**
* Logs out OS information.
*/
private void ackOsInfo() {
assert log != null;
if (log.isInfoEnabled()) {
log.info("OS: " + U.osString());
log.info("OS user: " + System.getProperty("user.name"));
}
}
/**
* Logs out language runtime.
*/
private void ackLanguageRuntime() {
assert log != null;
if (log.isInfoEnabled()) {
log.info("Language runtime: " + getLanguage());
log.info("VM information: " + U.jdkString());
log.info("VM total memory: " + U.heapSize(2) + "GB");
}
}
/**
* @return Language runtime.
*/
@SuppressWarnings("ThrowableInstanceNeverThrown")
private String getLanguage() {
boolean scala = false;
boolean groovy = false;
boolean clojure = false;
for (StackTraceElement elem : Thread.currentThread().getStackTrace()) {
String s = elem.getClassName().toLowerCase();
if (s.contains("scala")) {
scala = true;
break;
}
else if (s.contains("groovy")) {
groovy = true;
break;
}
else if (s.contains("clojure")) {
clojure = true;
break;
}
}
if (scala) {
try (InputStream in = getClass().getResourceAsStream("/library.properties")) {
Properties props = new Properties();
if (in != null)
props.load(in);
return "Scala ver. " + props.getProperty("version.number", "<unknown>");
}
catch (Exception ignore) {
return "Scala ver. <unknown>";
}
}
// How to get Groovy and Clojure version at runtime?!?
return groovy ? "Groovy" : clojure ? "Clojure" : U.jdkName() + " ver. " + U.jdkVersion();
}
/**
* Stops grid instance.
*
* @param cancel Whether or not to cancel running jobs.
*/
public void stop(boolean cancel) {
// Make sure that thread stopping grid is not interrupted.
boolean interrupted = Thread.interrupted();
try {
stop0(cancel);
}
finally {
if (interrupted)
Thread.currentThread().interrupt();
}
}
/**
* @return {@code True} if node started shutdown sequence.
*/
public boolean isStopping() {
return stopGuard.get();
}
/**
* @param cancel Whether or not to cancel running jobs.
*/
private void stop0(boolean cancel) {
gw.compareAndSet(null, new GridKernalGatewayImpl(gridName));
GridKernalGateway gw = this.gw.get();
if (stopGuard.compareAndSet(false, true)) {
// Only one thread is allowed to perform stop sequence.
boolean firstStop = false;
GridKernalState state = gw.getState();
if (state == STARTED || state == DISCONNECTED)
firstStop = true;
else if (state == STARTING)
U.warn(log, "Attempt to stop starting grid. This operation " +
"cannot be guaranteed to be successful.");
if (firstStop) {
// Notify lifecycle beans.
if (log.isDebugEnabled())
log.debug("Notifying lifecycle beans.");
notifyLifecycleBeansEx(LifecycleEventType.BEFORE_NODE_STOP);
}
GridCacheProcessor cacheProcessor = ctx.cache();
List<GridComponent> comps = ctx.components();
ctx.marshallerContext().onKernalStop();
// Callback component in reverse order while kernal is still functional
// if called in the same thread, at least.
for (ListIterator<GridComponent> it = comps.listIterator(comps.size()); it.hasPrevious();) {
GridComponent comp = it.previous();
try {
if (!skipDaemon(comp))
comp.onKernalStop(cancel);
}
catch (Throwable e) {
errOnStop = true;
U.error(log, "Failed to pre-stop processor: " + comp, e);
if (e instanceof Error)
throw e;
}
}
// Cancel update notification timer.
if (updateNtfTimer != null)
updateNtfTimer.cancel();
if (verChecker != null)
verChecker.stop();
if (starveTask != null)
starveTask.close();
if (metricsLogTask != null)
metricsLogTask.close();
boolean interrupted = false;
while (true) {
try {
if (gw.tryWriteLock(10))
break;
}
catch (InterruptedException ignored) {
// Preserve interrupt status & ignore.
// Note that interrupted flag is cleared.
interrupted = true;
}
finally {
// Cleanup even on successful acquire.
if (cacheProcessor != null)
cacheProcessor.cancelUserOperations();
}
}
if (interrupted)
Thread.currentThread().interrupt();
try {
GridCacheProcessor cache = ctx.cache();
if (cache != null)
cache.blockGateways();
assert gw.getState() == STARTED || gw.getState() == STARTING || gw.getState() == DISCONNECTED;
// No more kernal calls from this point on.
gw.setState(STOPPING);
ctx.cluster().get().clearNodeMap();
if (log.isDebugEnabled())
log.debug("Grid " + (gridName == null ? "" : '\'' + gridName + "' ") + "is stopping.");
}
finally {
gw.writeUnlock();
}
// Unregister MBeans.
if (!(
unregisterMBean(pubExecSvcMBean) &
unregisterMBean(sysExecSvcMBean) &
unregisterMBean(mgmtExecSvcMBean) &
unregisterMBean(p2PExecSvcMBean) &
unregisterMBean(kernalMBean) &
unregisterMBean(locNodeMBean) &
unregisterMBean(restExecSvcMBean)
))
errOnStop = false;
// Stop components in reverse order.
for (ListIterator<GridComponent> it = comps.listIterator(comps.size()); it.hasPrevious();) {
GridComponent comp = it.previous();
try {
if (!skipDaemon(comp)) {
comp.stop(cancel);
if (log.isDebugEnabled())
log.debug("Component stopped: " + comp);
}
}
catch (Throwable e) {
errOnStop = true;
U.error(log, "Failed to stop component (ignoring): " + comp, e);
if (e instanceof Error)
throw (Error)e;
}
}
// Stops lifecycle aware components.
U.stopLifecycleAware(log, lifecycleAwares(cfg));
// Lifecycle notification.
notifyLifecycleBeansEx(LifecycleEventType.AFTER_NODE_STOP);
// Clean internal class/classloader caches to avoid stopped contexts held in memory.
U.clearClassCache();
MarshallerExclusions.clearCache();
GridEnumCache.clear();
gw.writeLock();
try {
gw.setState(STOPPED);
}
finally {
gw.writeUnlock();
}
// Ack stop.
if (log.isQuiet()) {
if (!errOnStop)
U.quiet(false, "Ignite node stopped OK [uptime=" +
X.timeSpan2HMSM(U.currentTimeMillis() - startTime) + ']');
else
U.quiet(true, "Ignite node stopped wih ERRORS [uptime=" +
X.timeSpan2HMSM(U.currentTimeMillis() - startTime) + ']');
}
if (log.isInfoEnabled())
if (!errOnStop) {
String ack = "Ignite ver. " + VER_STR + '#' + BUILD_TSTAMP_STR + "-sha1:" + REV_HASH_STR +
" stopped OK";
String dash = U.dash(ack.length());
log.info(NL + NL +
">>> " + dash + NL +
">>> " + ack + NL +
">>> " + dash + NL +
">>> Grid name: " + gridName + NL +
">>> Grid uptime: " + X.timeSpan2HMSM(U.currentTimeMillis() - startTime) +
NL +
NL);
}
else {
String ack = "Ignite ver. " + VER_STR + '#' + BUILD_TSTAMP_STR + "-sha1:" + REV_HASH_STR +
" stopped with ERRORS";
String dash = U.dash(ack.length());
log.info(NL + NL +
">>> " + ack + NL +
">>> " + dash + NL +
">>> Grid name: " + gridName + NL +
">>> Grid uptime: " + X.timeSpan2HMSM(U.currentTimeMillis() - startTime) +
NL +
">>> See log above for detailed error message." + NL +
">>> Note that some errors during stop can prevent grid from" + NL +
">>> maintaining correct topology since this node may have" + NL +
">>> not exited grid properly." + NL +
NL);
}
try {
U.onGridStop();
}
catch (InterruptedException ignored) {
// Preserve interrupt status.
Thread.currentThread().interrupt();
}
}
else {
// Proper notification.
if (log.isDebugEnabled()) {
if (gw.getState() == STOPPED)
log.debug("Grid is already stopped. Nothing to do.");
else
log.debug("Grid is being stopped by another thread. Aborting this stop sequence " +
"allowing other thread to finish.");
}
}
}
/**
* USED ONLY FOR TESTING.
*
* @param <K> Key type.
* @param <V> Value type.
* @return Internal cache instance.
*/
/*@java.test.only*/
public <K, V> GridCacheAdapter<K, V> internalCache() {
return internalCache(null);
}
/**
* USED ONLY FOR TESTING.
*
* @param name Cache name.
* @param <K> Key type.
* @param <V> Value type.
* @return Internal cache instance.
*/
/*@java.test.only*/
public <K, V> GridCacheAdapter<K, V> internalCache(@Nullable String name) {
return ctx.cache().internalCache(name);
}
/**
* It's intended for use by internal marshalling implementation only.
*
* @return Kernal context.
*/
@Override public GridKernalContext context() {
return ctx;
}
/**
* Prints all system properties in debug mode.
*/
private void ackSystemProperties() {
assert log != null;
if (log.isDebugEnabled())
for (Map.Entry<Object, Object> entry : snapshot().entrySet())
log.debug("System property [" + entry.getKey() + '=' + entry.getValue() + ']');
}
/**
* Prints all user attributes in info mode.
*/
private void logNodeUserAttributes() {
assert log != null;
if (log.isInfoEnabled())
for (Map.Entry<?, ?> attr : cfg.getUserAttributes().entrySet())
log.info("Local node user attribute [" + attr.getKey() + '=' + attr.getValue() + ']');
}
/**
* Prints all environment variables in debug mode.
*/
private void ackEnvironmentVariables() {
assert log != null;
if (log.isDebugEnabled())
for (Map.Entry<?, ?> envVar : System.getenv().entrySet())
log.debug("Environment variable [" + envVar.getKey() + '=' + envVar.getValue() + ']');
}
/**
* Acks daemon mode status.
*/
private void ackDaemon() {
assert log != null;
if (log.isInfoEnabled())
log.info("Daemon mode: " + (isDaemon() ? "on" : "off"));
}
/**
*
* @return {@code True} is this node is daemon.
*/
private boolean isDaemon() {
assert cfg != null;
return cfg.isDaemon() || "true".equalsIgnoreCase(System.getProperty(IGNITE_DAEMON));
}
/**
* Whether or not remote JMX management is enabled for this node. Remote JMX management is
* enabled when the following system property is set:
* <ul>
* <li>{@code com.sun.management.jmxremote}</li>
* </ul>
*
* @return {@code True} if remote JMX management is enabled - {@code false} otherwise.
*/
@Override public boolean isJmxRemoteEnabled() {
return System.getProperty("com.sun.management.jmxremote") != null;
}
/**
* Whether or not node restart is enabled. Node restart us supported when this node was started
* with {@code bin/ignite.{sh|bat}} script using {@code -r} argument. Node can be
* programmatically restarted using {@link Ignition#restart(boolean)}} method.
*
* @return {@code True} if restart mode is enabled, {@code false} otherwise.
* @see Ignition#restart(boolean)
*/
@Override public boolean isRestartEnabled() {
return System.getProperty(IGNITE_SUCCESS_FILE) != null;
}
/**
* Prints all configuration properties in info mode and SPIs in debug mode.
*/
private void ackSpis() {
assert log != null;
if (log.isDebugEnabled()) {
log.debug("+-------------+");
log.debug("START SPI LIST:");
log.debug("+-------------+");
log.debug("Grid checkpoint SPI : " + Arrays.toString(cfg.getCheckpointSpi()));
log.debug("Grid collision SPI : " + cfg.getCollisionSpi());
log.debug("Grid communication SPI : " + cfg.getCommunicationSpi());
log.debug("Grid deployment SPI : " + cfg.getDeploymentSpi());
log.debug("Grid discovery SPI : " + cfg.getDiscoverySpi());
log.debug("Grid event storage SPI : " + cfg.getEventStorageSpi());
log.debug("Grid failover SPI : " + Arrays.toString(cfg.getFailoverSpi()));
log.debug("Grid load balancing SPI : " + Arrays.toString(cfg.getLoadBalancingSpi()));
log.debug("Grid swap space SPI : " + cfg.getSwapSpaceSpi());
}
}
/**
*
*/
private void ackCacheConfiguration() {
CacheConfiguration[] cacheCfgs = cfg.getCacheConfiguration();
if (cacheCfgs == null || cacheCfgs.length == 0)
U.warn(log, "Cache is not configured - in-memory data grid is off.");
else {
SB sb = new SB();
for (CacheConfiguration c : cacheCfgs) {
String name = U.maskName(c.getName());
sb.a("'").a(name).a("', ");
}
String names = sb.toString();
U.log(log, "Configured caches [" + names.substring(0, names.length() - 2) + ']');
}
}
/**
*
*/
private void ackP2pConfiguration() {
assert cfg != null;
if (cfg.isPeerClassLoadingEnabled())
U.warn(
log,
"Peer class loading is enabled (disable it in production for performance and " +
"deployment consistency reasons)",
"Peer class loading is enabled (disable it for better performance)"
);
}
/**
* Prints security status.
*/
private void ackSecurity() {
assert log != null;
U.quietAndInfo(log, "Security status [authentication=" + onOff(ctx.security().enabled())
+ ", communication encryption=" + onOff(ctx.config().getSslContextFactory() != null) + ']');
}
/**
* Prints out VM arguments and IGNITE_HOME in info mode.
*
* @param rtBean Java runtime bean.
*/
private void ackVmArguments(RuntimeMXBean rtBean) {
assert log != null;
// Ack IGNITE_HOME and VM arguments.
if (log.isInfoEnabled()) {
log.info("IGNITE_HOME=" + cfg.getIgniteHome());
log.info("VM arguments: " + rtBean.getInputArguments());
}
}
/**
* Prints out class paths in debug mode.
*
* @param rtBean Java runtime bean.
*/
private void ackClassPaths(RuntimeMXBean rtBean) {
assert log != null;
// Ack all class paths.
if (log.isDebugEnabled()) {
log.debug("Boot class path: " + rtBean.getBootClassPath());
log.debug("Class path: " + rtBean.getClassPath());
log.debug("Library path: " + rtBean.getLibraryPath());
}
}
/**
* @param cfg Grid configuration.
* @return Components provided in configuration which can implement {@link LifecycleAware} interface.
*/
private Iterable<Object> lifecycleAwares(IgniteConfiguration cfg) {
Collection<Object> objs = new ArrayList<>();
if (!F.isEmpty(cfg.getLifecycleBeans()))
F.copy(objs, cfg.getLifecycleBeans());
if (!F.isEmpty(cfg.getSegmentationResolvers()))
F.copy(objs, cfg.getSegmentationResolvers());
if (cfg.getConnectorConfiguration() != null)
F.copy(objs, cfg.getConnectorConfiguration().getMessageInterceptor(),
cfg.getConnectorConfiguration().getSslContextFactory());
F.copy(objs, cfg.getMarshaller(), cfg.getGridLogger(), cfg.getMBeanServer());
return objs;
}
/** {@inheritDoc} */
@Override public IgniteConfiguration configuration() {
return cfg;
}
/** {@inheritDoc} */
@Override public IgniteLogger log() {
return log;
}
/** {@inheritDoc} */
@Override public boolean removeCheckpoint(String key) {
A.notNull(key, "key");
guard();
try {
return ctx.checkpoint().removeCheckpoint(key);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public boolean pingNode(String nodeId) {
A.notNull(nodeId, "nodeId");
return cluster().pingNode(UUID.fromString(nodeId));
}
/** {@inheritDoc} */
@Override public void undeployTaskFromGrid(String taskName) throws JMException {
A.notNull(taskName, "taskName");
try {
compute().undeployTask(taskName);
}
catch (IgniteException e) {
throw U.jmException(e);
}
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public String executeTask(String taskName, String arg) throws JMException {
try {
return compute().execute(taskName, arg);
}
catch (IgniteException e) {
throw U.jmException(e);
}
}
/** {@inheritDoc} */
@Override public boolean pingNodeByAddress(String host) {
guard();
try {
for (ClusterNode n : cluster().nodes())
if (n.addresses().contains(host))
return ctx.discovery().pingNode(n.id());
return false;
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public boolean eventUserRecordable(int type) {
guard();
try {
return ctx.event().isUserRecordable(type);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public boolean allEventsUserRecordable(int[] types) {
A.notNull(types, "types");
guard();
try {
return ctx.event().isAllUserRecordable(types);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public IgniteTransactions transactions() {
guard();
try {
return ctx.cache().transactions();
}
finally {
unguard();
}
}
/**
* @param name Cache name.
* @return Cache.
*/
public <K, V> IgniteInternalCache<K, V> getCache(@Nullable String name) {
guard();
try {
return ctx.cache().publicCache(name);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public <K, V> IgniteCache<K, V> cache(@Nullable String name) {
guard();
try {
return ctx.cache().publicJCache(name, false);
}
catch (IgniteCheckedException e) {
throw CU.convertToCacheException(e);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public <K, V> IgniteCache<K, V> createCache(CacheConfiguration<K, V> cacheCfg) {
A.notNull(cacheCfg, "cacheCfg");
guard();
try {
ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), null, true, true).get();
return ctx.cache().publicJCache(cacheCfg.getName());
}
catch (IgniteCheckedException e) {
throw CU.convertToCacheException(e);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public <K, V> IgniteCache<K, V> createCache(String cacheName) {
guard();
try {
ctx.cache().createFromTemplate(cacheName).get();
return ctx.cache().publicJCache(cacheName);
}
catch (IgniteCheckedException e) {
throw CU.convertToCacheException(e);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public <K, V> IgniteCache<K, V> getOrCreateCache(CacheConfiguration<K, V> cacheCfg) {
A.notNull(cacheCfg, "cacheCfg");
guard();
try {
if (ctx.cache().cache(cacheCfg.getName()) == null)
ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), null, false, true).get();
return ctx.cache().publicJCache(cacheCfg.getName());
}
catch (IgniteCheckedException e) {
throw CU.convertToCacheException(e);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public <K, V> IgniteCache<K, V> createCache(
CacheConfiguration<K, V> cacheCfg,
NearCacheConfiguration<K, V> nearCfg
) {
A.notNull(cacheCfg, "cacheCfg");
A.notNull(nearCfg, "nearCfg");
guard();
try {
ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), nearCfg, true, true).get();
return ctx.cache().publicJCache(cacheCfg.getName());
}
catch (IgniteCheckedException e) {
throw CU.convertToCacheException(e);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public <K, V> IgniteCache<K, V> getOrCreateCache(CacheConfiguration<K, V> cacheCfg,
NearCacheConfiguration<K, V> nearCfg) {
A.notNull(cacheCfg, "cacheCfg");
A.notNull(nearCfg, "nearCfg");
guard();
try {
IgniteInternalCache<Object, Object> cache = ctx.cache().cache(cacheCfg.getName());
if (cache == null)
ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), nearCfg, false, true).get();
else {
if (cache.configuration().getNearConfiguration() == null)
ctx.cache().dynamicStartCache(cacheCfg, cacheCfg.getName(), nearCfg, false, true).get();
}
return ctx.cache().publicJCache(cacheCfg.getName());
}
catch (IgniteCheckedException e) {
throw CU.convertToCacheException(e);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public <K, V> IgniteCache<K, V> createNearCache(String cacheName, NearCacheConfiguration<K, V> nearCfg) {
A.notNull(nearCfg, "nearCfg");
guard();
try {
ctx.cache().dynamicStartCache(null, cacheName, nearCfg, true, true).get();
IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName);
checkNearCacheStarted(cache);
return cache;
}
catch (IgniteCheckedException e) {
throw CU.convertToCacheException(e);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public <K, V> IgniteCache<K, V> getOrCreateNearCache(@Nullable String cacheName,
NearCacheConfiguration<K, V> nearCfg) {
A.notNull(nearCfg, "nearCfg");
guard();
try {
IgniteInternalCache<Object, Object> internalCache = ctx.cache().cache(cacheName);
if (internalCache == null)
ctx.cache().dynamicStartCache(null, cacheName, nearCfg, false, true).get();
else {
if (internalCache.configuration().getNearConfiguration() == null)
ctx.cache().dynamicStartCache(null, cacheName, nearCfg, false, true).get();
}
IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName);
checkNearCacheStarted(cache);
return cache;
}
catch (IgniteCheckedException e) {
throw CU.convertToCacheException(e);
}
finally {
unguard();
}
}
/**
* @param cache Cache.
*/
private void checkNearCacheStarted(IgniteCacheProxy<?, ?> cache) throws IgniteCheckedException {
if (!cache.context().isNear())
throw new IgniteCheckedException("Failed to start near cache " +
"(a cache with the same name without near cache is already started)");
}
/** {@inheritDoc} */
@Override public void destroyCache(String cacheName) {
IgniteInternalFuture stopFut = destroyCacheAsync(cacheName);
try {
stopFut.get();
}
catch (IgniteCheckedException e) {
throw CU.convertToCacheException(e);
}
}
/**
* @param cacheName Cache name.
* @return Ignite future.
*/
public IgniteInternalFuture<?> destroyCacheAsync(String cacheName) {
guard();
try {
return ctx.cache().dynamicDestroyCache(cacheName);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public <K, V> IgniteCache<K, V> getOrCreateCache(String cacheName) {
guard();
try {
if (ctx.cache().cache(cacheName) == null)
ctx.cache().getOrCreateFromTemplate(cacheName).get();
return ctx.cache().publicJCache(cacheName);
}
catch (IgniteCheckedException e) {
throw CU.convertToCacheException(e);
}
finally {
unguard();
}
}
/**
* @param cacheName Cache name.
* @return Future that will be completed when cache is deployed.
*/
public IgniteInternalFuture<?> getOrCreateCacheAsync(String cacheName) {
guard();
try {
if (ctx.cache().cache(cacheName) == null)
return ctx.cache().getOrCreateFromTemplate(cacheName);
return new GridFinishedFuture<>();
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public <K, V> void addCacheConfiguration(CacheConfiguration<K, V> cacheCfg) {
A.notNull(cacheCfg, "cacheCfg");
guard();
try {
ctx.cache().addCacheConfiguration(cacheCfg);
}
catch (IgniteCheckedException e) {
throw CU.convertToCacheException(e);
}
finally {
unguard();
}
}
/**
* @return Public caches.
*/
public Collection<IgniteCacheProxy<?, ?>> caches() {
guard();
try {
return ctx.cache().publicCaches();
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public <K extends GridCacheUtilityKey, V> IgniteInternalCache<K, V> utilityCache() {
guard();
try {
return ctx.cache().utilityCache();
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public <K, V> IgniteInternalCache<K, V> cachex(@Nullable String name) {
guard();
try {
return ctx.cache().cache(name);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public <K, V> IgniteInternalCache<K, V> cachex() {
guard();
try {
return ctx.cache().cache();
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public Collection<IgniteInternalCache<?, ?>> cachesx(IgnitePredicate<? super IgniteInternalCache<?, ?>>[] p) {
guard();
try {
return F.retain(ctx.cache().caches(), true, p);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public <K, V> IgniteDataStreamer<K, V> dataStreamer(@Nullable String cacheName) {
guard();
try {
return ctx.<K, V>dataStream().dataStreamer(cacheName);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public IgniteFileSystem fileSystem(String name) {
guard();
try{
IgniteFileSystem fs = ctx.igfs().igfs(name);
if (fs == null)
throw new IllegalArgumentException("IGFS is not configured: " + name);
return fs;
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Nullable @Override public IgniteFileSystem igfsx(@Nullable String name) {
guard();
try {
return ctx.igfs().igfs(name);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public Collection<IgniteFileSystem> fileSystems() {
guard();
try {
return ctx.igfs().igfss();
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public Hadoop hadoop() {
guard();
try {
return ctx.hadoop().hadoop();
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public <T extends IgnitePlugin> T plugin(String name) throws PluginNotFoundException {
guard();
try {
return (T)ctx.pluginProvider(name).plugin();
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Override public IgnitePortables portables() {
return ((CacheObjectPortableProcessor)ctx.cacheObjects()).portables();
}
/** {@inheritDoc} */
@Override public IgniteProductVersion version() {
return VER;
}
/** {@inheritDoc} */
@Override public String latestVersion() {
ctx.gateway().readLock();
try {
return verChecker != null ? verChecker.latestVersion() : null;
}
finally {
ctx.gateway().readUnlock();
}
}
/** {@inheritDoc} */
@Override public IgniteScheduler scheduler() {
return scheduler;
}
/** {@inheritDoc} */
@Override public void close() throws IgniteException {
Ignition.stop(gridName, true);
}
/** {@inheritDoc} */
@Override public <K> Affinity<K> affinity(String cacheName) {
GridCacheAdapter<K, ?> cache = ctx.cache().internalCache(cacheName);
if (cache != null)
return cache.affinity();
return ctx.affinity().affinityProxy(cacheName);
}
/** {@inheritDoc} */
@Nullable @Override public IgniteAtomicSequence atomicSequence(String name, long initVal, boolean create) {
guard();
try {
return ctx.dataStructures().sequence(name, initVal, create);
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Nullable @Override public IgniteAtomicLong atomicLong(String name, long initVal, boolean create) {
guard();
try {
return ctx.dataStructures().atomicLong(name, initVal, create);
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Nullable @Override public <T> IgniteAtomicReference<T> atomicReference(String name,
@Nullable T initVal,
boolean create)
{
guard();
try {
return ctx.dataStructures().atomicReference(name, initVal, create);
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Nullable @Override public <T, S> IgniteAtomicStamped<T, S> atomicStamped(String name,
@Nullable T initVal,
@Nullable S initStamp,
boolean create) {
guard();
try {
return ctx.dataStructures().atomicStamped(name, initVal, initStamp, create);
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Nullable @Override public IgniteCountDownLatch countDownLatch(String name,
int cnt,
boolean autoDel,
boolean create) {
guard();
try {
return ctx.dataStructures().countDownLatch(name, cnt, autoDel, create);
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Nullable @Override public <T> IgniteQueue<T> queue(String name,
int cap,
CollectionConfiguration cfg)
{
guard();
try {
return ctx.dataStructures().queue(name, cap, cfg);
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
finally {
unguard();
}
}
/** {@inheritDoc} */
@Nullable @Override public <T> IgniteSet<T> set(String name,
CollectionConfiguration cfg)
{
guard();
try {
return ctx.dataStructures().set(name, cfg);
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
finally {
unguard();
}
}
/**
* <tt>ctx.gateway().readLock()</tt>
*/
private void guard() {
assert ctx != null;
ctx.gateway().readLock();
}
/**
* <tt>ctx.gateway().readUnlock()</tt>
*/
private void unguard() {
assert ctx != null;
ctx.gateway().readUnlock();
}
/**
*
*/
public void onDisconnected() {
Throwable err = null;
GridFutureAdapter<?> reconnectFut = ctx.gateway().onDisconnected();
if (reconnectFut == null) {
assert ctx.gateway().getState() != STARTED : ctx.gateway().getState();
return;
}
IgniteFuture<?> userFut = new IgniteFutureImpl<>(reconnectFut);
ctx.cluster().get().clientReconnectFuture(userFut);
ctx.disconnected(true);
List<GridComponent> comps = ctx.components();
for (ListIterator<GridComponent> it = comps.listIterator(comps.size()); it.hasPrevious();) {
GridComponent comp = it.previous();
try {
if (!skipDaemon(comp))
comp.onDisconnected(userFut);
}
catch (IgniteCheckedException e) {
err = e;
}
catch (Throwable e) {
err = e;
if (e instanceof Error)
throw e;
}
}
for (GridCacheContext cctx : ctx.cache().context().cacheContexts()) {
cctx.gate().writeLock();
cctx.gate().writeUnlock();
}
ctx.gateway().writeLock();
ctx.gateway().writeUnlock();
if (err != null) {
reconnectFut.onDone(err);
U.error(log, "Failed to reconnect, will stop node", err);
close();
}
}
/**
* @param clusterRestarted {@code True} if all cluster nodes restarted while client was disconnected.
*/
public void onReconnected(final boolean clusterRestarted) {
Throwable err = null;
try {
ctx.disconnected(false);
for (GridComponent comp : ctx.components())
comp.onReconnected(clusterRestarted);
ctx.cache().context().exchange().reconnectExchangeFuture().listen(new CI1<IgniteInternalFuture<?>>() {
@Override public void apply(IgniteInternalFuture<?> fut) {
try {
fut.get();
ctx.gateway().onReconnected();
}
catch (IgniteCheckedException e) {
U.error(log, "Failed to reconnect, will stop node", e);
close();
}
}
});
}
catch (IgniteCheckedException e) {
err = e;
}
catch (Throwable e) {
err = e;
if (e instanceof Error)
throw e;
}
if (err != null) {
U.error(log, "Failed to reconnect, will stop node", err);
close();
}
}
/**
* Creates optional component.
*
* @param cls Component interface.
* @param ctx Kernal context.
* @return Created component.
* @throws IgniteCheckedException If failed to create component.
*/
private static <T extends GridComponent> T createComponent(Class<T> cls, GridKernalContext ctx)
throws IgniteCheckedException {
assert cls.isInterface() : cls;
T comp = ctx.plugins().createComponent(cls);
if (comp != null)
return comp;
if (cls.equals(IgniteCacheObjectProcessor.class))
return (T)new CacheObjectPortableProcessorImpl(ctx);
if (cls.equals(DiscoveryNodeValidationProcessor.class))
return (T)new OsDiscoveryNodeValidationProcessor(ctx);
Class<T> implCls = null;
try {
String clsName;
// Handle special case for PlatformProcessor
if (cls.equals(PlatformProcessor.class)) {
clsName = PlatformNoopProcessor.class.getName();
// clsName = ctx.config().getPlatformConfiguration() == null ?
// PlatformNoopProcessor.class.getName() : cls.getName() + "Impl";
}
else
clsName = componentClassName(cls);
implCls = (Class<T>)Class.forName(clsName);
}
catch (ClassNotFoundException ignore) {
// No-op.
}
if (implCls == null)
throw new IgniteCheckedException("Failed to find component implementation: " + cls.getName());
if (!cls.isAssignableFrom(implCls))
throw new IgniteCheckedException("Component implementation does not implement component interface " +
"[component=" + cls.getName() + ", implementation=" + implCls.getName() + ']');
Constructor<T> constructor;
try {
constructor = implCls.getConstructor(GridKernalContext.class);
}
catch (NoSuchMethodException e) {
throw new IgniteCheckedException("Component does not have expected constructor: " + implCls.getName(), e);
}
try {
return constructor.newInstance(ctx);
}
catch (ReflectiveOperationException e) {
throw new IgniteCheckedException("Failed to create component [component=" + cls.getName() +
", implementation=" + implCls.getName() + ']', e);
}
}
/**
* @param cls Component interface.
* @return Name of component implementation class for open source edition.
*/
private static String componentClassName(Class<?> cls) {
return cls.getPackage().getName() + ".os." + cls.getSimpleName().replace("Grid", "GridOs");
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
gridName = U.readString(in);
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
U.writeString(out, gridName);
}
/**
* @return IgniteKernal instance.
*
* @throws ObjectStreamException If failed.
*/
protected Object readResolve() throws ObjectStreamException {
try {
return IgnitionEx.gridx(gridName);
}
catch (IllegalStateException e) {
throw U.withCause(new InvalidObjectException(e.getMessage()), e);
}
}
/**
* @param comp Grid component.
* @return {@code true} if node running in daemon mode and component marked by {@code SkipDaemon} annotation.
*/
private boolean skipDaemon(GridComponent comp) {
return ctx.isDaemon() && U.hasAnnotation(comp.getClass(), SkipDaemon.class);
}
/**
*
*/
public void dumpDebugInfo() {
U.warn(log, "Dumping debug info for node [id=" + ctx.localNodeId() +
", name=" + ctx.gridName() +
", order=" + ctx.discovery().localNode().order() +
", client=" + ctx.clientNode() + ']');
ctx.cache().context().exchange().dumpDebugInfo();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(IgniteKernal.class, this);
}
/**
* Update notifier timer task.
*/
private static class UpdateNotifierTimerTask extends GridTimerTask {
/** Reference to kernal. */
private final WeakReference<IgniteKernal> kernalRef;
/** Logger. */
private final IgniteLogger log;
/** Executor service. */
private final ExecutorService execSvc;
/** Version checker. */
private final GridUpdateNotifier verChecker;
/** Whether this is the first run. */
private boolean first = true;
/**
* Constructor.
*
* @param kernal Kernal.
* @param execSvc Executor service.
* @param verChecker Version checker.
*/
private UpdateNotifierTimerTask(IgniteKernal kernal, ExecutorService execSvc, GridUpdateNotifier verChecker) {
kernalRef = new WeakReference<>(kernal);
log = kernal.log.getLogger(UpdateNotifierTimerTask.class);
this.execSvc = execSvc;
this.verChecker = verChecker;
}
/** {@inheritDoc} */
@Override public void safeRun() throws InterruptedException {
if (!first) {
IgniteKernal kernal = kernalRef.get();
if (kernal != null)
verChecker.topologySize(kernal.cluster().nodes().size());
}
verChecker.checkForNewVersion(log);
// Just wait for 10 secs.
Thread.sleep(PERIODIC_VER_CHECK_CONN_TIMEOUT);
// Just wait another 60 secs in order to get
// version info even on slow connection.
for (int i = 0; i < 60 && verChecker.latestVersion() == null; i++)
Thread.sleep(1000);
// Report status if one is available.
// No-op if status is NOT available.
verChecker.reportStatus(log);
if (first) {
first = false;
verChecker.reportOnlyNew(true);
}
}
}
}
| {
"content_hash": "509cf7c93c772b5806c2746e0c5a3aff",
"timestamp": "",
"source": "github",
"line_count": 3234,
"max_line_length": 128,
"avg_line_length": 33.72974644403216,
"alnum_prop": 0.5765112484186209,
"repo_name": "adeelmahmood/ignite",
"id": "9b615b116b419f1e21938099e1630394949e5cac",
"size": "109884",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "31291"
},
{
"name": "C",
"bytes": "3323"
},
{
"name": "C#",
"bytes": "2612254"
},
{
"name": "C++",
"bytes": "864786"
},
{
"name": "CSS",
"bytes": "17517"
},
{
"name": "Groovy",
"bytes": "15092"
},
{
"name": "HTML",
"bytes": "4649"
},
{
"name": "Java",
"bytes": "20632806"
},
{
"name": "JavaScript",
"bytes": "1085"
},
{
"name": "PHP",
"bytes": "11079"
},
{
"name": "Scala",
"bytes": "653258"
},
{
"name": "Shell",
"bytes": "398304"
}
],
"symlink_target": ""
} |
package com.tod.eclipse.servoy.console.hyperlinks;
import java.util.HashMap;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.console.IHyperlink;
import org.eclipse.ui.ide.IGotoMarker;
import com.servoy.eclipse.model.ServoyModelFinder;
import com.servoy.eclipse.model.repository.SolutionSerializer;
import com.servoy.eclipse.ui.util.EditorUtil;
import com.servoy.j2db.FlattenedSolution;
import com.servoy.j2db.persistence.AbstractRepository;
import com.servoy.j2db.persistence.BaseComponent;
import com.servoy.j2db.persistence.Form;
import com.servoy.j2db.persistence.IPersist;
import com.servoy.j2db.persistence.IPersistVisitor;
import com.servoy.j2db.util.Pair;
import com.servoy.j2db.util.UUID;
public class Hyperlink implements IHyperlink {
private String form;
private String element;
/**
* Constructor for ElementHyperlink.
*/
public Hyperlink(String form, String element) {
this.form = form;
this.element = element;
}
@Override
public void linkEntered() {
}
@Override
public void linkExited() {
}
@Override
public void linkActivated() {
FlattenedSolution fs = ServoyModelFinder.getServoyModel().getActiveProject().getEditingFlattenedSolution();
Form f = fs.getForm(form);
UUID persistUUID = null;
if (f == null) {
return;
}
IEditorPart ep = EditorUtil.openFormDesignEditor(f);
if (this.element == null) {
return;
}
if (this.element.startsWith("<")) {
persistUUID = UUID.fromString(this.element.substring(1, this.element.length() - 1));
} else {
final String elementName = this.element.substring(1);
IPersist persist = (IPersist) fs.getFlattenedForm(f).acceptVisitor(new IPersistVisitor() {
public Object visit(IPersist o) {
if (o instanceof BaseComponent) {
BaseComponent bc = (BaseComponent) o;
if (elementName.equals(bc.getName())) {
return bc;
}
}
return IPersistVisitor.CONTINUE_TRAVERSAL;
}
});
if (persist != null) {
persistUUID = persist.getUUID();
}
}
if (persistUUID == null) {
return;
}
IPersist persist = AbstractRepository.searchPersist(f, persistUUID);
IGotoMarker gm = (IGotoMarker) ep.getAdapter(IGotoMarker.class);
IMarker marker = null;
try {
Pair<String, String> pathPair = SolutionSerializer.getFilePath(persist, true);
Path path = new Path(pathPair.getLeft() + pathPair.getRight());
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
if (file.exists()) {
marker = file.createMarker("com.tod.console.hyperlink2selection.helpermarker");
HashMap<String, String> attributes = new HashMap<String, String>();
attributes.put("elementUuid", persist.getUUID().toString());
marker.setAttributes(attributes);
gm.gotoMarker(marker);
}
} catch (CoreException e) {
System.out.println("Failure selecting element");
e.printStackTrace();
} finally {
if (marker != null)
try {
marker.delete();
} catch (CoreException e) {
e.printStackTrace();
}
}
}
} | {
"content_hash": "a3545bf01048e7de55399bc119f9bf83",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 109,
"avg_line_length": 28.95689655172414,
"alnum_prop": 0.6951473652872879,
"repo_name": "TheOrangeDots/ServoyConsoleHyperlinks",
"id": "326fb1be71fe83b1589c1c780e28722edcffb276",
"size": "4468",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "patternMatchers/src/com/tod/eclipse/servoy/console/hyperlinks/Hyperlink.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "7043"
}
],
"symlink_target": ""
} |
package academy.learnprogramming.challenge2;
public class Main {
public static void main(String[] args) {
Integer one = 1;
Integer two = 2;
Integer three = 3;
Integer four = 4;
IntegerLinkedList list = new IntegerLinkedList();
list.insertSorted(three);
list.printList();
list.insertSorted(two);
list.printList();
list.insertSorted(one);
list.printList();
list.insertSorted(four);
list.printList();
}
}
| {
"content_hash": "592d30542d59b9de562449bece72728e",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 57,
"avg_line_length": 23.545454545454547,
"alnum_prop": 0.5868725868725869,
"repo_name": "abhishekajain/questions",
"id": "4661d53938dc00647684c6c7a6299a5b1bb26f2e",
"size": "518",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/academy/learnprogramming/challenge2/Main.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "3163"
},
{
"name": "Java",
"bytes": "166231"
}
],
"symlink_target": ""
} |
class HTTParty::CookieHash < Hash #:nodoc:
CLIENT_COOKIES = %w{path expires domain path secure httponly}
def add_cookies(value)
case value
when Hash
merge!(value)
when String
value.split('; ').each do |cookie|
array = cookie.split('=',2)
self[array[0].to_sym] = array[1]
end
else
raise "add_cookies only takes a Hash or a String"
end
end
def to_cookie_string
delete_if { |k, v| CLIENT_COOKIES.include?(k.to_s.downcase) }.collect { |k, v| "#{k}=#{v}" }.join("; ")
end
end
| {
"content_hash": "b0977d31db97a94a79b2ea99e82f28cf",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 107,
"avg_line_length": 24.90909090909091,
"alnum_prop": 0.5967153284671532,
"repo_name": "rubygem/website",
"id": "674696edf9d19ab62ba76b5002c85483351d9b17",
"size": "548",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "gems/ruby/2.2.0/gems/httparty-0.13.3/lib/httparty/cookie_hash.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "455330"
},
{
"name": "C",
"bytes": "1730986"
},
{
"name": "C++",
"bytes": "111879"
},
{
"name": "CSS",
"bytes": "782833"
},
{
"name": "CoffeeScript",
"bytes": "91"
},
{
"name": "Cucumber",
"bytes": "22093"
},
{
"name": "Groff",
"bytes": "4034"
},
{
"name": "HTML",
"bytes": "24610"
},
{
"name": "Java",
"bytes": "1129744"
},
{
"name": "JavaScript",
"bytes": "823233"
},
{
"name": "Liquid",
"bytes": "70"
},
{
"name": "Logos",
"bytes": "1171"
},
{
"name": "Makefile",
"bytes": "67894"
},
{
"name": "Ragel in Ruby Host",
"bytes": "140816"
},
{
"name": "Ruby",
"bytes": "9931961"
},
{
"name": "Shell",
"bytes": "377702"
},
{
"name": "TeX",
"bytes": "230259"
}
],
"symlink_target": ""
} |
<?php
namespace App\Models\Entities;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Storage;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use HasRoles;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'username', 'email', 'password', 'dob', 'gender', 'profile_photo_path', 'profile_photo_extension', 'bio', 'is_banned',
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* Gets the users profile photo
*
* @return string
*/
public function ProfilePhotoBase64()
{
$file = Storage::get($this->profile_photo_path);
return 'data:image/' . $this->profile_photo_extension . ';base64,' . base64_encode($file);
}
/**
* Gets a list of all users following the user.
*/
public function followers()
{
return $this->belongsToMany(__CLASS__, 'followers', 'user_id', 'follow_id')->withPivot('accepted')->withTimestamps();
}
/**
* Gets a list of all users that the user is following.
*/
public function following()
{
return $this->belongsToMany(__CLASS__, 'followers', 'follow_id', 'user_id')->withPivot('accepted')->withTimestamps();
}
/**
* Get all of the posts for the user.
*/
public function posts()
{
return $this->hasMany(Post::class);
}
}
| {
"content_hash": "dc0a9c1b5ba7ed88758b49b3eaa9b47c",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 134,
"avg_line_length": 24.369230769230768,
"alnum_prop": 0.5896464646464646,
"repo_name": "DGoodrich/laravel-socialize",
"id": "53ea2e3bc75bb1d252dc433f975d8b4751b49839",
"size": "1584",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/Models/Entities/User.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "37482"
},
{
"name": "HTML",
"bytes": "64936"
},
{
"name": "JavaScript",
"bytes": "49655"
},
{
"name": "PHP",
"bytes": "262416"
}
],
"symlink_target": ""
} |
'use strict';
// Resolve URLs using the application environment
const vcap = require('cf-abacus-vcapenv');
const urienv = require('..');
describe('cf-abacus-urienv', () => {
it('resolves URIs to the first application URI', () => {
// Return VCAP env like when running in a Bluemix app instance
vcap.env = stub().returns({ application_uris: ['test.ng.bluemix.net', 'test.mybluemix.net'] });
const uris = urienv.resolve({ abc: undefined, def: 9081, ghi: 'http://localhost:9082'});
expect(uris.abc).to.equal('https://abc.ng.bluemix.net');
expect(uris.def).to.equal('https://def.ng.bluemix.net');
expect(uris.ghi).to.equal('https://ghi.ng.bluemix.net');
});
it('resolves URIs to localhost', () => {
// Return empty VCAP env like when running on localhost
vcap.env = stub().returns({});
const uris = urienv.resolve({ abc: undefined, def: 9081, ghi: 'http://localhost:9082'});
expect(uris.abc).to.equal('http://localhost:9080');
expect(uris.def).to.equal('http://localhost:9081');
expect(uris.ghi).to.equal('http://localhost:9082');
});
it('resolves default port from environment', () => {
// Return empty VCAP env like when running on localhost
vcap.env = stub().returns({});
process.env.PORT = '9083';
const uris = urienv.resolve({ jkl: undefined });
expect(uris.jkl).to.equal('http://localhost:9083');
delete process.env.PORT;
});
it('resolves URIs from browser location', () => {
process.browser = true;
global.window = { location: { protocol: 'https:', hostname: 'xyz.net', port: 9084 }};
const uris = urienv.resolve({ mno: undefined });
expect(uris.mno).to.equal('https://xyz.net:9084');
process.browser = false;
delete global.window;
});
});
| {
"content_hash": "7059bce41fb77ea967b14bb20042dfd7",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 103,
"avg_line_length": 37.58,
"alnum_prop": 0.6024481106971793,
"repo_name": "stefanschneider/cf-abacus",
"id": "9f4acff6d640ece571abf6cfdf9e8df82eef9f7e",
"size": "1879",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/utils/urienv/src/test/test.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "403821"
},
{
"name": "Shell",
"bytes": "1396"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>
<script type="text/javascript" src="variables_6d.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body class="SRPage">
<div id="SRIndex">
<div class="SRStatus" id="Loading">Wczytywanie...</div>
<div id="SRResults"></div>
<script type="text/javascript"><!--
createResults();
--></script>
<div class="SRStatus" id="Searching">Szukanie...</div>
<div class="SRStatus" id="NoMatches">Brak dopasowań</div>
<script type="text/javascript"><!--
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults");
searchResults.Search();
--></script>
</div>
</body>
</html>
| {
"content_hash": "203d83780a59ed68a4c9a947574d201c",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 121,
"avg_line_length": 39.08,
"alnum_prop": 0.7093142272262026,
"repo_name": "lnawrot/traffic-simulator",
"id": "9594027e1bf844ee58eab5b73d95da6e1cd95f19",
"size": "978",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/html/search/variables_6d.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "1649"
},
{
"name": "C++",
"bytes": "117128"
},
{
"name": "CSS",
"bytes": "7616"
},
{
"name": "HTML",
"bytes": "35945"
},
{
"name": "Python",
"bytes": "251420"
},
{
"name": "QMake",
"bytes": "1753"
},
{
"name": "XSLT",
"bytes": "8010"
}
],
"symlink_target": ""
} |
#include <aws/opsworks/model/CreateLayerResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::OpsWorks::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
CreateLayerResult::CreateLayerResult()
{
}
CreateLayerResult::CreateLayerResult(const AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
CreateLayerResult& CreateLayerResult::operator =(const AmazonWebServiceResult<JsonValue>& result)
{
const JsonValue& jsonValue = result.GetPayload();
if(jsonValue.ValueExists("LayerId"))
{
m_layerId = jsonValue.GetString("LayerId");
}
return *this;
}
| {
"content_hash": "da0df54567cc2ded2d493a3352eef532",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 97,
"avg_line_length": 21.54054054054054,
"alnum_prop": 0.7628607277289837,
"repo_name": "chiaming0914/awe-cpp-sdk",
"id": "1dcb4ad9c913f6c3487c0ab08597c5c560afc5d5",
"size": "1370",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-opsworks/source/model/CreateLayerResult.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2313"
},
{
"name": "C++",
"bytes": "98158533"
},
{
"name": "CMake",
"bytes": "437471"
},
{
"name": "HTML",
"bytes": "4471"
},
{
"name": "Java",
"bytes": "239297"
},
{
"name": "Python",
"bytes": "72827"
},
{
"name": "Shell",
"bytes": "2803"
}
],
"symlink_target": ""
} |
import os
from setuptools import setup, find_packages
long_description = open(
os.path.join(
os.path.dirname(__file__),
'README.rst'
)
).read()
setup(
name='prompt_toolkit',
author='Jonathan Slenders',
version='0.52',
license='LICENSE.txt',
url='https://github.com/jonathanslenders/python-prompt-toolkit',
description='Library for building powerful interactive command lines in Python',
long_description=long_description,
packages=find_packages('.'),
install_requires = [
'pygments',
'six>=1.9.0',
'wcwidth',
],
)
| {
"content_hash": "9e6a875a4153c5f6e3bf60d0485f1302",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 84,
"avg_line_length": 22.444444444444443,
"alnum_prop": 0.6287128712871287,
"repo_name": "ddalex/python-prompt-toolkit",
"id": "c3640d7386867d870ff2bd64ab59cad535d2f91c",
"size": "628",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "577643"
}
],
"symlink_target": ""
} |
import os,uuid,sys
import requests,subprocess,shutil
from pprint import pprint
from KBaseReport.KBaseReportClient import KBaseReport
from biokbase.workspace.client import Workspace as workspaceService
from ReadsUtils.ReadsUtilsClient import ReadsUtils
#END_HEADER
class kb_fastqc:
'''
Module Name:
kb_fastqc
Module Description:
A KBase module: kb_fastqc
'''
######## WARNING FOR GEVENT USERS ####### noqa
# Since asynchronous IO can lead to methods - even the same method -
# interrupting each other, you must be *very* careful when using global
# state. A method could easily clobber the state set by another while
# the latter method is running.
######################################### noqa
VERSION = "1.0.1"
GIT_URL = "https://github.com/rsutormin/kb_fastqc"
GIT_COMMIT_HASH = "82f3adf025cccb35b247652439709a64a78ca74b"
#BEGIN_CLASS_HEADER
def _get_input_file_ref_from_params(self, params):
if 'input_file_ref' in params:
return params['input_file_ref']
else:
if 'input_ws' not in params and 'input_file' not in params:
raise ValueError('Either the "input_file_ref" field or the "input_ws" with' +
'"input_file" fields must be set.')
return str(params['input_ws']) + '/' + str(params['input_file'])
#END_CLASS_HEADER
# config contains contents of config file in a hash or None if it couldn't
# be found
def __init__(self, config):
#BEGIN_CONSTRUCTOR
self.workspaceURL = config['workspace-url']
self.scratch = os.path.abspath(config['scratch'])
self.callback_url = os.environ['SDK_CALLBACK_URL']
#END_CONSTRUCTOR
pass
def runFastQC(self, ctx, input_params):
"""
:param input_params: instance of type "FastQCParams" -> structure:
parameter "input_ws" of String, parameter "input_file" of String,
parameter "input_file_ref" of String
:returns: instance of type "FastQCOutput" -> structure: parameter
"report_name" of String, parameter "report_ref" of String
"""
# ctx is the context object
# return variables are: reported_output
#BEGIN runFastQC
token = ctx['token']
wsClient = workspaceService(self.workspaceURL, token=token)
headers = {'Authorization': 'OAuth '+token}
uuid_string = str(uuid.uuid4())
read_file_path=self.scratch+"/"+uuid_string
os.mkdir(read_file_path)
input_file_ref = self._get_input_file_ref_from_params(input_params)
library=None
try:
library = wsClient.get_objects2({'objects': [{'ref': input_file_ref}]})['data'][0]
except Exception as e:
raise ValueError('Unable to get read library object from workspace: (' + input_file_ref + ')' + str(e))
download_read_params = {'read_libraries': [], 'interleaved':"false"}
if("SingleEnd" in library['info'][2] or "PairedEnd" in library['info'][2]):
download_read_params['read_libraries'].append(library['info'][7]+"/"+library['info'][1])
elif("SampleSet" in library['info'][2]):
for sample_id in library['data']['sample_ids']:
if("/" in sample_id):
download_read_params['read_libraries'].append(sample_id)
else:
if(sample_id.isdigit()):
download_read_params['read_libraries'].append(library['info'][6]+"/"+sample_id)
else:
download_read_params['read_libraries'].append(library['info'][7]+"/"+sample_id)
ru = ReadsUtils(os.environ['SDK_CALLBACK_URL'])
ret = ru.download_reads(download_read_params)
read_file_list=list()
for file in ret['files']:
files = ret['files'][file]['files']
fwd_name=files['fwd'].split('/')[-1]
fwd_name=fwd_name.replace('.gz','')
shutil.move(files['fwd'],os.path.join(read_file_path, fwd_name))
read_file_list.append(os.path.join(read_file_path, fwd_name))
if(files['rev'] is not None):
rev_name=files['rev'].split('/')[-1]
rev_name=rev_name.replace('.gz','')
shutil.move(files['rev'],os.path.join(read_file_path, rev_name))
read_file_list.append(os.path.join(read_file_path, rev_name))
subprocess.check_output(["fastqc"]+read_file_list)
report = "Command run: "+" ".join(["fastqc"]+read_file_list)
output_html_files = list()
output_zip_files = list()
first_file=""
html_string = ""
html_count = 0
with open('/kb/data/index_start.txt', 'r') as start_file:
html_string=start_file.read()
#Make HTML folder
os.mkdir(os.path.join(read_file_path, 'html'))
for file in os.listdir(read_file_path):
label=".".join(file.split(".")[1:])
if(file.endswith(".zip")):
output_zip_files.append({'path' : os.path.join(read_file_path,file),
'name' : file,
'label' : label,
'description' : 'Zip file generated by fastqc that contains ' + \
'original images seen in the report'})
if(file.endswith(".html")):
#Move html into html folder
shutil.move(os.path.join(read_file_path,file),os.path.join(read_file_path,'html',file))
# file = os.path.join('html',file)
if(first_file==""):
first_file=file
html_string+=" <button data-button=\"page "+str(html_count) + \
"\" data-page=\""+file+"\">Page "+str(html_count+1)+"</button>\n"
html_count+=1
html_string+=" </div> </div> <div id=\"body\">\n <iframe id=\"content\" " + \
"style=\"width: 100%; border: none; \" src=\""+first_file+"\"></iframe>\n </div>"
output_html_files.append({'path' : os.path.join(read_file_path,'html'),
'name' : 'html files',
'label' : 'html files',
'description' : 'HTML files generated by fastqc that ' + \
'contains report on quality of reads'})
with open('/kb/data/index_end.txt', 'r') as end_file:
html_string+=end_file.read()
with open(os.path.join(read_file_path,'html',"index.html"),'w') as index_file:
index_file.write(html_string)
# output_html_files.append({'path' : read_file_path+"/index.html",
# 'name' : "index.html",
# 'label' : "index.html",
# 'description' : 'HTML file generated by fastqc that contains report on quality of reads'})
report_params = { 'objects_created' : [],
# 'message' : report,
'direct_html' : html_string,
# 'direct_html_link_index' : 1,
'file_links' : output_zip_files,
'html_links' : output_html_files,
'workspace_name' : input_params['input_ws'],
'report_object_name' : 'kb_fastqc_report_' + uuid_string }
kbase_report_client = KBaseReport(self.callback_url, token=token)
output = kbase_report_client.create_extended_report(report_params)
reported_output = { 'report_name': output['name'], 'report_ref': output['ref'] }
#Remove temp reads directory
shutil.rmtree(read_file_path, ignore_errors=True)
#END runFastQC
# At some point might do deeper type checking...
if not isinstance(reported_output, dict):
raise ValueError('Method runFastQC return value ' +
'reported_output is not type dict as required.')
# return the results
return [reported_output]
def status(self, ctx):
#BEGIN_STATUS
returnVal = {'state': "OK", 'message': "", 'version': self.VERSION,
'git_url': self.GIT_URL, 'git_commit_hash': self.GIT_COMMIT_HASH}
#END_STATUS
return [returnVal]
| {
"content_hash": "75df2c0f6d888073ac700fbd06bf1bca",
"timestamp": "",
"source": "github",
"line_count": 192,
"max_line_length": 125,
"avg_line_length": 44.723958333333336,
"alnum_prop": 0.5384884127168976,
"repo_name": "samseaver/kb_fastqc",
"id": "52298809c282be58f5e5c9a38102648d53cd9532",
"size": "8625",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/kb_fastqc/kb_fastqcImpl.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2063"
},
{
"name": "Java",
"bytes": "11641"
},
{
"name": "JavaScript",
"bytes": "4619"
},
{
"name": "Makefile",
"bytes": "2870"
},
{
"name": "Perl",
"bytes": "10925"
},
{
"name": "Python",
"bytes": "117869"
},
{
"name": "Ruby",
"bytes": "405"
},
{
"name": "Shell",
"bytes": "1665"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="LOCAL" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="$APPLICATION_HOME_DIR$/gradle/gradle-2.2.1" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/common" />
<option value="$PROJECT_DIR$/mobile" />
<option value="$PROJECT_DIR$/wearable" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>
| {
"content_hash": "144c7b34d563cd0650b56d3ab6599922",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 87,
"avg_line_length": 35.666666666666664,
"alnum_prop": 0.5887850467289719,
"repo_name": "SimoneCasagranda/android-wear-tutorial",
"id": "83bfdd37b01d1aa6be6142c153ceea8619696394",
"size": "749",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/gradle.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "150249"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<!--
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See LICENSE.txt in the project root for license information.
-->
<doc>
<assembly>
<name>Microsoft.Graphics.Canvas</name>
</assembly>
<members>
<member name="T:Microsoft.Graphics.Canvas.Effects.StraightenEffect" Win10="true" NoComposition="true">
<summary>
Rotates and optionally scales an image.
</summary>
<remarks>
<p>This effect is useful for correcting photos that were taken at an angle so their horizon is not quite horizontal.</p>
<p>This Windows Runtime type corresponds to the
<a href="http://msdn.microsoft.com/en-us/library/windows/desktop/dn900462.aspx">D2D Straighten effect</a>.</p>
</remarks>
</member>
<member name="M:Microsoft.Graphics.Canvas.Effects.StraightenEffect.#ctor">
<summary>Initializes a new instance of the StraightenEffect class.</summary>
</member>
<member name="M:Microsoft.Graphics.Canvas.Effects.StraightenEffect.GetBounds(Microsoft.Graphics.Canvas.CanvasDrawingSession)">
<summary>Retrieves the bounds of this CanvasImage, in device-independent units.</summary>
<inheritdoc/>
</member>
<member name="M:Microsoft.Graphics.Canvas.Effects.StraightenEffect.GetBounds(Microsoft.Graphics.Canvas.CanvasDrawingSession,Microsoft.Graphics.Canvas.Numerics.Matrix3x2)">
<summary>Retrieves the bounds of this CanvasImage, in device-independent units.</summary>
<inheritdoc/>
</member>
<member name="M:Microsoft.Graphics.Canvas.Effects.StraightenEffect.Dispose">
<summary>Releases all resources used by the StraightenEffect.</summary>
</member>
<member name="P:Microsoft.Graphics.Canvas.Effects.StraightenEffect.Name">
<summary>Attaches a user-defined name string to the effect.</summary>
<inheritdoc/>
</member>
<member name="P:Microsoft.Graphics.Canvas.Effects.StraightenEffect.Source">
<summary>Gets or sets the input source for Straighten effect.</summary>
<remarks>
This property is initialized to null.
</remarks>
</member>
<member name="P:Microsoft.Graphics.Canvas.Effects.StraightenEffect.Angle">
<summary>Specifies how much the image should be rotated.
Units are specified in radians. Default value 0, range -pi/4 to pi/4.</summary>
</member>
<member name="P:Microsoft.Graphics.Canvas.Effects.StraightenEffect.MaintainSize">
<summary>Specifies whether the image will be scaled such that the result fits
within the original rectangle without any invalid regions, no matter how
it is rotated. Default value false.</summary>
</member>
<member name="P:Microsoft.Graphics.Canvas.Effects.StraightenEffect.InterpolationMode">
<summary>Gets or sets the interpolation mode.</summary>
<remarks>
<p>Default interpolation mode is <see cref="F:Microsoft.Graphics.Canvas.CanvasImageInterpolation.Linear"/>.</p>
<p>Please note that <see cref="F:Microsoft.Graphics.Canvas.CanvasImageInterpolation.HighQualityCubic"/> mode is not supported.</p>
</remarks>
</member>
</members>
</doc>
| {
"content_hash": "a24f6798c5191e0c71b368818733e17e",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 175,
"avg_line_length": 48.3134328358209,
"alnum_prop": 0.7126969416126042,
"repo_name": "ChrisBriggsy/Win2D",
"id": "5194baa7ff3358f15e526fce76cb57a8124172e7",
"size": "3237",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "winrt/docsrc/effects/StraightenEffect.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "3918"
},
{
"name": "C",
"bytes": "647"
},
{
"name": "C#",
"bytes": "605869"
},
{
"name": "C++",
"bytes": "3329594"
},
{
"name": "Objective-C",
"bytes": "175"
}
],
"symlink_target": ""
} |
<readable><title>246041128_bedb09ed74</title><content>
A girl with blonde hair and a black shirt .
A woman sits at an outdoor cafe table with really big blond hair .
A woman who is wearing red lipstick and has curly hair sits at a table .
A woman with bright red lipstick and big blonde hair sitting at an outside cafe
A woman with thick curly blond hair sits outdoors at a table .
</content></readable> | {
"content_hash": "26377b46cc25a5fab0f52506665a5cd5",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 79,
"avg_line_length": 57.57142857142857,
"alnum_prop": 0.7791563275434243,
"repo_name": "kevint2u/audio-collector",
"id": "580e1569acac8ef27035cdb044c506c0d831911b",
"size": "403",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "captions/xml/246041128_bedb09ed74.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1015"
},
{
"name": "HTML",
"bytes": "18349"
},
{
"name": "JavaScript",
"bytes": "109819"
},
{
"name": "Python",
"bytes": "3260"
},
{
"name": "Shell",
"bytes": "4319"
}
],
"symlink_target": ""
} |
package org.eclipse.ceylon.cmr.spi;
import java.io.InputStream;
/**
* An InputStream holder which may know its size
*/
public class SizedInputStream {
private final InputStream inputStream;
private final long size;
public SizedInputStream(InputStream inputStream, long size){
this.inputStream = inputStream;
this.size = size;
}
public InputStream getInputStream() {
return inputStream;
}
/**
* Can be -1 if we don't know its size
*/
public long getSize() {
return size;
}
}
| {
"content_hash": "3240946d6c574a342acad0d9a5cfdfad",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 64,
"avg_line_length": 19,
"alnum_prop": 0.6333333333333333,
"repo_name": "ceylon/ceylon",
"id": "0baf112e8aef86f796798f1a79a323f22e4f9143",
"size": "1042",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cmr/spi/src/main/java/org/eclipse/ceylon/cmr/spi/SizedInputStream.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3806"
},
{
"name": "CSS",
"bytes": "19001"
},
{
"name": "Ceylon",
"bytes": "6230332"
},
{
"name": "GAP",
"bytes": "178688"
},
{
"name": "Groovy",
"bytes": "28376"
},
{
"name": "HTML",
"bytes": "4562"
},
{
"name": "Java",
"bytes": "24954709"
},
{
"name": "JavaScript",
"bytes": "499145"
},
{
"name": "Makefile",
"bytes": "19934"
},
{
"name": "Perl",
"bytes": "2756"
},
{
"name": "Roff",
"bytes": "47559"
},
{
"name": "Shell",
"bytes": "212436"
},
{
"name": "XSLT",
"bytes": "1992114"
}
],
"symlink_target": ""
} |
all:
g++ -o test VocabGen.cpp Word2Vec.cpp HashMap.cpp embedding.cpp FileReader.cpp RandomGen.cpp ExpTable.cpp -lpthread -lm -O3 -Wall -funroll-loops -Wno-unused-result | {
"content_hash": "b630a1666e8e9106399cd2f112675ded",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 164,
"avg_line_length": 84.5,
"alnum_prop": 0.7810650887573964,
"repo_name": "largelymfs/MTMSWord2Vec",
"id": "9cc3890c13312fb37905cc5a4a784c501a491d63",
"size": "169",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Makefile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "32593"
},
{
"name": "Makefile",
"bytes": "169"
},
{
"name": "Python",
"bytes": "2963"
}
],
"symlink_target": ""
} |
module.controller('ResourceServerCtrl', function($scope, realm, ResourceServer) {
$scope.realm = realm;
ResourceServer.query({realm : realm.realm}, function (data) {
$scope.servers = data;
});
});
module.controller('ResourceServerDetailCtrl', function($scope, $http, $route, $location, $upload, $modal, realm, ResourceServer, client, AuthzDialog, Notifications) {
$scope.realm = realm;
$scope.client = client;
ResourceServer.get({
realm : $route.current.params.realm,
client : client.id
}, function(data) {
$scope.server = angular.copy(data);
$scope.changed = false;
$scope.$watch('server', function() {
if (!angular.equals($scope.server, data)) {
$scope.changed = true;
}
}, true);
$scope.save = function() {
ResourceServer.update({realm : realm.realm, client : $scope.server.clientId}, $scope.server, function() {
$route.reload();
Notifications.success("The resource server has been created.");
});
}
$scope.reset = function() {
$route.reload();
}
$scope.export = function() {
$scope.exportSettings = true;
ResourceServer.settings({
realm : $route.current.params.realm,
client : client.id
}, function(data) {
var tmp = angular.fromJson(data);
$scope.settings = angular.toJson(tmp, true);
})
}
$scope.downloadSettings = function() {
saveAs(new Blob([$scope.settings], { type: 'application/json' }), $scope.server.name + "-authz-config.json");
}
$scope.cancelExport = function() {
delete $scope.settings
}
$scope.onFileSelect = function($fileContent) {
$scope.server = angular.copy(JSON.parse($fileContent));
$scope.importing = true;
};
$scope.viewImportDetails = function() {
$modal.open({
templateUrl: resourceUrl + '/partials/modal/view-object.html',
controller: 'ObjectModalCtrl',
resolve: {
object: function () {
return $scope.server;
}
}
})
};
$scope.import = function () {
ResourceServer.import({realm : realm.realm, client : client.id}, $scope.server, function() {
$route.reload();
Notifications.success("The resource server has been updated.");
});
}
});
});
module.controller('ResourceServerResourceCtrl', function($scope, $http, $route, $location, realm, ResourceServer, ResourceServerResource, client) {
$scope.realm = realm;
$scope.client = client;
ResourceServer.get({
realm : $route.current.params.realm,
client : client.id
}, function(data) {
$scope.server = data;
$scope.createPolicy = function(resource) {
$location.path('/realms/' + $route.current.params.realm + '/clients/' + client.id + '/authz/resource-server/permission/resource/create').search({rsrid: resource._id});
}
ResourceServerResource.query({realm : realm.realm, client : client.id}, function (data) {
$scope.resources = data;
});
});
});
module.controller('ResourceServerResourceDetailCtrl', function($scope, $http, $route, $location, realm, ResourceServer, client, ResourceServerResource, ResourceServerScope, AuthzDialog, Notifications) {
$scope.realm = realm;
$scope.client = client;
ResourceServerScope.query({realm : realm.realm, client : client.id}, function (data) {
$scope.scopes = data;
});
var $instance = this;
ResourceServer.get({
realm : $route.current.params.realm,
client : client.id
}, function(data) {
$scope.server = data;
var resourceId = $route.current.params.rsrid;
if (!resourceId) {
$scope.create = true;
$scope.changed = false;
var resource = {};
resource.scopes = [];
$scope.resource = angular.copy(resource);
$scope.$watch('resource', function() {
if (!angular.equals($scope.resource, resource)) {
$scope.changed = true;
}
}, true);
$scope.save = function() {
$instance.checkNameAvailability(function () {
ResourceServerResource.save({realm : realm.realm, client : $scope.client.id}, $scope.resource, function(data) {
$location.url("/realms/" + realm.realm + "/clients/" + $scope.client.id + "/authz/resource-server/resource/" + data._id);
Notifications.success("The resource has been created.");
});
});
}
$scope.cancel = function() {
$location.url("/realms/" + realm.realm + "/clients/" + $scope.client.id + "/authz/resource-server/resource/");
}
} else {
ResourceServerResource.get({
realm : $route.current.params.realm,
client : client.id,
rsrid : $route.current.params.rsrid,
}, function(data) {
if (!data.scopes) {
data.scopes = [];
}
if (!data.policies) {
data.policies = [];
}
$scope.resource = angular.copy(data);
$scope.changed = false;
for (i = 0; i < $scope.resource.scopes.length; i++) {
$scope.resource.scopes[i] = $scope.resource.scopes[i].name;
}
$scope.originalResource = angular.copy($scope.resource);
$scope.$watch('resource', function() {
if (!angular.equals($scope.resource, data)) {
$scope.changed = true;
}
}, true);
$scope.save = function() {
$instance.checkNameAvailability(function () {
ResourceServerResource.update({realm : realm.realm, client : $scope.client.id, rsrid : $scope.resource._id}, $scope.resource, function() {
$route.reload();
Notifications.success("The resource has been updated.");
});
});
}
$scope.remove = function() {
var msg = "";
if ($scope.resource.policies.length > 0) {
msg = "<p>This resource is referenced in some policies:</p>";
msg += "<ul>";
for (i = 0; i < $scope.resource.policies.length; i++) {
msg+= "<li><strong>" + $scope.resource.policies[i].name + "</strong></li>";
}
msg += "</ul>";
msg += "<p>If you remove this resource, the policies above will be affected and will not be associated with this resource anymore.</p>";
}
AuthzDialog.confirmDeleteWithMsg($scope.resource.name, "Resource", msg, function() {
ResourceServerResource.delete({realm : realm.realm, client : $scope.client.id, rsrid : $scope.resource._id}, null, function() {
$location.url("/realms/" + realm.realm + "/clients/" + $scope.client.id + "/authz/resource-server/resource");
Notifications.success("The resource has been deleted.");
});
});
}
$scope.reset = function() {
$route.reload();
}
});
}
});
$scope.checkNewNameAvailability = function () {
$instance.checkNameAvailability(function () {});
}
this.checkNameAvailability = function (onSuccess) {
ResourceServerResource.search({
realm : $route.current.params.realm,
client : client.id,
rsrid : $route.current.params.rsrid,
name: $scope.resource.name
}, function(data) {
if (data && data._id && data._id != $scope.resource._id) {
Notifications.error("Name already in use by another resource, please choose another one.");
} else {
onSuccess();
}
});
}
});
module.controller('ResourceServerScopeCtrl', function($scope, $http, $route, $location, realm, ResourceServer, ResourceServerScope, client) {
$scope.realm = realm;
$scope.client = client;
ResourceServer.get({
realm : $route.current.params.realm,
client : client.id
}, function(data) {
$scope.server = data;
ResourceServerScope.query({realm : realm.realm, client : client.id}, function (data) {
$scope.scopes = data;
});
$scope.createPolicy = function(scope) {
$location.path('/realms/' + $route.current.params.realm + '/clients/' + client.id + '/authz/resource-server/permission/scope/create').search({scpid: scope.id});
}
});
});
module.controller('ResourceServerScopeDetailCtrl', function($scope, $http, $route, $location, realm, ResourceServer, client, ResourceServerScope, AuthzDialog, Notifications) {
$scope.realm = realm;
$scope.client = client;
var $instance = this;
ResourceServer.get({
realm : $route.current.params.realm,
client : client.id
}, function(data) {
$scope.server = data;
var scopeId = $route.current.params.id;
if (!scopeId) {
$scope.create = true;
$scope.changed = false;
var scope = {};
$scope.scope = angular.copy(scope);
$scope.$watch('scope', function() {
if (!angular.equals($scope.scope, scope)) {
$scope.changed = true;
}
}, true);
$scope.save = function() {
$instance.checkNameAvailability(function () {
ResourceServerScope.save({realm : realm.realm, client : $scope.client.id}, $scope.scope, function(data) {
$location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/scope/" + data.id);
Notifications.success("The scope has been created.");
});
});
}
} else {
ResourceServerScope.get({
realm : $route.current.params.realm,
client : client.id,
id : $route.current.params.id,
}, function(data) {
$scope.scope = angular.copy(data);
$scope.changed = false;
$scope.$watch('scope', function() {
if (!angular.equals($scope.scope, data)) {
$scope.changed = true;
}
}, true);
$scope.originalScope = angular.copy($scope.scope);
$scope.save = function() {
$instance.checkNameAvailability(function () {
ResourceServerScope.update({realm : realm.realm, client : $scope.client.id, id : $scope.scope.id}, $scope.scope, function() {
$scope.changed = false;
Notifications.success("The scope has been updated.");
});
});
}
$scope.remove = function() {
var msg = "";
if ($scope.scope.policies.length > 0) {
msg = "<p>This resource is referenced in some policies:</p>";
msg += "<ul>";
for (i = 0; i < $scope.scope.policies.length; i++) {
msg+= "<li><strong>" + $scope.scope.policies[i].name + "</strong></li>";
}
msg += "</ul>";
msg += "<p>If you remove this resource, the policies above will be affected and will not be associated with this resource anymore.</p>";
}
AuthzDialog.confirmDeleteWithMsg($scope.scope.name, "Scope", msg, function() {
ResourceServerScope.delete({realm : realm.realm, client : $scope.client.id, id : $scope.scope.id}, null, function() {
$location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/scope");
Notifications.success("The scope has been deleted.");
});
});
}
$scope.reset = function() {
$route.reload();
}
});
}
});
$scope.checkNewNameAvailability = function () {
$instance.checkNameAvailability(function () {});
}
this.checkNameAvailability = function (onSuccess) {
ResourceServerScope.search({
realm : $route.current.params.realm,
client : client.id,
name: $scope.scope.name
}, function(data) {
if (data && data.id && data.id != $scope.scope.id) {
Notifications.error("Name already in use by another scope, please choose another one.");
} else {
onSuccess();
}
});
}
});
module.controller('ResourceServerPolicyCtrl', function($scope, $http, $route, $location, realm, ResourceServer, ResourceServerPolicy, PolicyProvider, client) {
$scope.realm = realm;
$scope.client = client;
$scope.policyProviders = [];
PolicyProvider.query({
realm : $route.current.params.realm,
client : client.id
}, function (data) {
for (i = 0; i < data.length; i++) {
if (data[i].type != 'resource' && data[i].type != 'scope') {
$scope.policyProviders.push(data[i]);
}
}
});
ResourceServer.get({
realm : $route.current.params.realm,
client : client.id
}, function(data) {
$scope.server = data;
ResourceServerPolicy.query({realm : realm.realm, client : client.id}, function (data) {
$scope.policies = [];
for (i = 0; i < data.length; i++) {
if (data[i].type != 'resource' && data[i].type != 'scope') {
$scope.policies.push(data[i]);
}
}
});
});
$scope.addPolicy = function(policyType) {
$location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/policy/" + policyType.type + "/create");
}
});
module.controller('ResourceServerPermissionCtrl', function($scope, $http, $route, $location, realm, ResourceServer, ResourceServerPolicy, PolicyProvider, client) {
$scope.realm = realm;
$scope.client = client;
$scope.policyProviders = [];
PolicyProvider.query({
realm : $route.current.params.realm,
client : client.id
}, function (data) {
for (i = 0; i < data.length; i++) {
if (data[i].type == 'resource' || data[i].type == 'scope') {
$scope.policyProviders.push(data[i]);
}
}
});
ResourceServer.get({
realm : $route.current.params.realm,
client : client.id
}, function(data) {
$scope.server = data;
ResourceServerPolicy.query({realm : realm.realm, client : client.id}, function (data) {
$scope.policies = [];
for (i = 0; i < data.length; i++) {
if (data[i].type == 'resource' || data[i].type == 'scope') {
$scope.policies.push(data[i]);
}
}
});
});
$scope.addPolicy = function(policyType) {
$location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/permission/" + policyType.type + "/create");
}
});
module.controller('ResourceServerPolicyDroolsDetailCtrl', function($scope, $http, $route, realm, client, PolicyController) {
PolicyController.onInit({
getPolicyType : function() {
return "drools";
},
onInit : function() {
$scope.drools = {};
$scope.resolveModules = function(policy) {
if (!policy) {
policy = $scope.policy;
}
$http.post(authUrl + '/admin/realms/'+ $route.current.params.realm + '/clients/' + client.id + '/authz/resource-server/policy/drools/resolveModules'
, policy).success(function(data) {
$scope.drools.moduleNames = data;
$scope.resolveSessions();
});
}
$scope.resolveSessions = function() {
$http.post(authUrl + '/admin/realms/'+ $route.current.params.realm + '/clients/' + client.id + '/authz/resource-server/policy/drools/resolveSessions'
, $scope.policy).success(function(data) {
$scope.drools.moduleSessions = data;
});
}
},
onInitUpdate : function(policy) {
policy.config.scannerPeriod = parseInt(policy.config.scannerPeriod);
$scope.resolveModules(policy);
},
onUpdate : function() {
$scope.policy.config.resources = JSON.stringify($scope.policy.config.resources);
},
onInitCreate : function(newPolicy) {
newPolicy.config.scannerPeriod = 1;
newPolicy.config.scannerPeriodUnit = 'Hours';
}
}, realm, client, $scope);
});
module.controller('ResourceServerPolicyResourceDetailCtrl', function($scope, $route, $location, realm, client, PolicyController, ResourceServerPolicy, ResourceServerResource) {
PolicyController.onInit({
getPolicyType : function() {
return "resource";
},
isPermission : function() {
return true;
},
onInit : function() {
ResourceServerResource.query({realm : realm.realm, client : client.id}, function (data) {
$scope.resources = data;
});
ResourceServerPolicy.query({realm : realm.realm, client : client.id}, function (data) {
$scope.policies = [];
for (i = 0; i < data.length; i++) {
if (data[i].type != 'resource' && data[i].type != 'scope') {
$scope.policies.push(data[i]);
}
}
});
$scope.applyToResourceType = function() {
if ($scope.policy.config.default) {
$scope.policy.config.resources = [];
} else {
$scope.policy.config.defaultResourceType = null;
}
}
},
onInitUpdate : function(policy) {
policy.config.default = eval(policy.config.default);
policy.config.resources = eval(policy.config.resources);
policy.config.applyPolicies = eval(policy.config.applyPolicies);
},
onUpdate : function() {
$scope.policy.config.resources = JSON.stringify($scope.policy.config.resources);
$scope.policy.config.applyPolicies = JSON.stringify($scope.policy.config.applyPolicies);
},
onInitCreate : function(newPolicy) {
newPolicy.decisionStrategy = 'UNANIMOUS';
newPolicy.config = {};
newPolicy.config.resources = '';
var resourceId = $location.search()['rsrid'];
if (resourceId) {
newPolicy.config.resources = [resourceId];
}
},
onCreate : function() {
$scope.policy.config.resources = JSON.stringify($scope.policy.config.resources);
$scope.policy.config.applyPolicies = JSON.stringify($scope.policy.config.applyPolicies);
}
}, realm, client, $scope);
});
module.controller('ResourceServerPolicyScopeDetailCtrl', function($scope, $route, $location, realm, client, PolicyController, ResourceServerPolicy, ResourceServerResource, ResourceServerScope) {
PolicyController.onInit({
getPolicyType : function() {
return "scope";
},
isPermission : function() {
return true;
},
onInit : function() {
ResourceServerScope.query({realm : realm.realm, client : client.id}, function (data) {
$scope.scopes = data;
});
ResourceServerResource.query({realm : realm.realm, client : client.id}, function (data) {
$scope.resources = data;
});
ResourceServerPolicy.query({realm : realm.realm, client : client.id}, function (data) {
$scope.policies = [];
for (i = 0; i < data.length; i++) {
if (data[i].type != 'resource' && data[i].type != 'scope') {
$scope.policies.push(data[i]);
}
}
});
$scope.resolveScopes = function(policy, keepScopes) {
if (!keepScopes) {
policy.config.scopes = [];
}
if (!policy) {
policy = $scope.policy;
}
if (policy.config.resources != null) {
ResourceServerResource.get({
realm : $route.current.params.realm,
client : client.id,
rsrid : policy.config.resources
}, function(data) {
$scope.scopes = data.scopes;
});
} else {
ResourceServerScope.query({realm : realm.realm, client : client.id}, function (data) {
$scope.scopes = data;
});
}
}
},
onInitUpdate : function(policy) {
if (policy.config.resources) {
policy.config.resources = eval(policy.config.resources);
if (policy.config.resources.length > 0) {
policy.config.resources = policy.config.resources[0];
} else {
policy.config.resources = null;
}
}
$scope.resolveScopes(policy, true);
policy.config.applyPolicies = eval(policy.config.applyPolicies);
policy.config.scopes = eval(policy.config.scopes);
},
onUpdate : function() {
if ($scope.policy.config.resources != null) {
var resources = undefined;
if ($scope.policy.config.resources.length != 0) {
resources = JSON.stringify([$scope.policy.config.resources])
}
$scope.policy.config.resources = resources;
}
$scope.policy.config.scopes = JSON.stringify($scope.policy.config.scopes);
$scope.policy.config.applyPolicies = JSON.stringify($scope.policy.config.applyPolicies);
},
onInitCreate : function(newPolicy) {
newPolicy.decisionStrategy = 'UNANIMOUS';
newPolicy.config = {};
newPolicy.config.resources = '';
var scopeId = $location.search()['scpid'];
if (scopeId) {
newPolicy.config.scopes = [scopeId];
}
},
onCreate : function() {
if ($scope.policy.config.resources != null) {
var resources = undefined;
if ($scope.policy.config.resources.length != 0) {
resources = JSON.stringify([$scope.policy.config.resources])
}
$scope.policy.config.resources = resources;
}
$scope.policy.config.scopes = JSON.stringify($scope.policy.config.scopes);
$scope.policy.config.applyPolicies = JSON.stringify($scope.policy.config.applyPolicies);
}
}, realm, client, $scope);
});
module.controller('ResourceServerPolicyUserDetailCtrl', function($scope, $route, realm, client, PolicyController, User) {
PolicyController.onInit({
getPolicyType : function() {
return "user";
},
onInit : function() {
$scope.usersUiSelect = {
minimumInputLength: 1,
delay: 500,
allowClear: true,
query: function (query) {
var data = {results: []};
if ('' == query.term.trim()) {
query.callback(data);
return;
}
User.query({realm: $route.current.params.realm, search: query.term.trim(), max: 20}, function(response) {
data.results = response;
query.callback(data);
});
},
formatResult: function(object, container, query) {
return object.username;
}
};
$scope.selectedUsers = [];
$scope.selectUser = function(user) {
if (!user || !user.id) {
return;
}
$scope.selectedUser = null;
for (i = 0; i < $scope.selectedUsers.length; i++) {
if ($scope.selectedUsers[i].id == user.id) {
return;
}
}
$scope.selectedUsers.push(user);
}
$scope.removeFromList = function(list, index) {
list.splice(index, 1);
}
},
onInitUpdate : function(policy) {
var selectedUsers = [];
if (policy.config.users) {
var users = eval(policy.config.users);
for (i = 0; i < users.length; i++) {
User.get({realm: $route.current.params.realm, userId: users[i]}, function(data) {
selectedUsers.push(data);
$scope.selectedUsers = angular.copy(selectedUsers);
});
}
}
$scope.$watch('selectedUsers', function() {
if (!angular.equals($scope.selectedUsers, selectedUsers)) {
$scope.changed = true;
}
}, true);
},
onUpdate : function() {
var users = [];
for (i = 0; i < $scope.selectedUsers.length; i++) {
users.push($scope.selectedUsers[i].id);
}
$scope.policy.config.users = JSON.stringify(users);
},
onCreate : function() {
var users = [];
for (i = 0; i < $scope.selectedUsers.length; i++) {
users.push($scope.selectedUsers[i].id);
}
$scope.policy.config.users = JSON.stringify(users);
}
}, realm, client, $scope);
});
module.controller('ResourceServerPolicyRoleDetailCtrl', function($scope, $route, realm, client, Client, ClientRole, PolicyController, Role, RoleById) {
PolicyController.onInit({
getPolicyType : function() {
return "role";
},
onInit : function() {
Role.query({realm: $route.current.params.realm}, function(data) {
$scope.roles = data;
});
Client.query({realm: $route.current.params.realm}, function (data) {
$scope.clients = data;
});
$scope.selectedRoles = [];
$scope.selectRole = function(role) {
if (!role || !role.id) {
return;
}
$scope.selectedRole = null;
for (i = 0; i < $scope.selectedRoles.length; i++) {
if ($scope.selectedRoles[i].id == role.id) {
return;
}
}
$scope.selectedRoles.push(role);
var clientRoles = [];
if ($scope.clientRoles) {
for (i = 0; i < $scope.clientRoles.length; i++) {
if ($scope.clientRoles[i].id != role.id) {
clientRoles.push($scope.clientRoles[i]);
}
}
$scope.clientRoles = clientRoles;
}
}
$scope.removeFromList = function(role) {
if ($scope.clientRoles && $scope.selectedClient && $scope.selectedClient.id == role.containerId) {
$scope.clientRoles.push(role);
}
var index = $scope.selectedRoles.indexOf(role);
if (index != -1) {
$scope.selectedRoles.splice(index, 1);
}
}
$scope.selectClient = function() {
if (!$scope.selectedClient) {
$scope.clientRoles = [];
return;
}
ClientRole.query({realm: $route.current.params.realm, client: $scope.selectedClient.id}, function(data) {
var roles = [];
for (j = 0; j < data.length; j++) {
var defined = false;
for (i = 0; i < $scope.selectedRoles.length; i++) {
if ($scope.selectedRoles[i].id == data[j].id) {
defined = true;
break;
}
}
if (!defined) {
data[j].container = {};
data[j].container.name = $scope.selectedClient.clientId;
roles.push(data[j]);
}
}
$scope.clientRoles = roles;
});
}
},
onInitUpdate : function(policy) {
var selectedRoles = [];
if (policy.config.roles) {
var roles = eval(policy.config.roles);
for (i = 0; i < roles.length; i++) {
RoleById.get({realm: $route.current.params.realm, role: roles[i].id}, function(data) {
for (i = 0; i < roles.length; i++) {
if (roles[i].id == data.id) {
data.required = roles[i].required ? true : false;
}
}
for (i = 0; i < $scope.clients.length; i++) {
if ($scope.clients[i].id == data.containerId) {
data.container = {};
data.container.name = $scope.clients[i].clientId;
}
}
selectedRoles.push(data);
$scope.selectedRoles = angular.copy(selectedRoles);
});
}
}
$scope.$watch('selectedRoles', function() {
if (!angular.equals($scope.selectedRoles, selectedRoles)) {
$scope.changed = true;
}
}, true);
},
onUpdate : function() {
var roles = [];
for (i = 0; i < $scope.selectedRoles.length; i++) {
var role = {};
role.id = $scope.selectedRoles[i].id;
if ($scope.selectedRoles[i].required) {
role.required = $scope.selectedRoles[i].required;
}
roles.push(role);
}
$scope.policy.config.roles = JSON.stringify(roles);
},
onCreate : function() {
var roles = [];
for (i = 0; i < $scope.selectedRoles.length; i++) {
var role = {};
role.id = $scope.selectedRoles[i].id;
if ($scope.selectedRoles[i].required) {
role.required = $scope.selectedRoles[i].required;
}
roles.push(role);
}
$scope.policy.config.roles = JSON.stringify(roles);
}
}, realm, client, $scope);
$scope.hasRealmRole = function () {
for (i = 0; i < $scope.selectedRoles.length; i++) {
if (!$scope.selectedRoles[i].clientRole) {
return true;
}
}
return false;
}
$scope.hasClientRole = function () {
for (i = 0; i < $scope.selectedRoles.length; i++) {
if ($scope.selectedRoles[i].clientRole) {
return true;
}
}
return false;
}
});
module.controller('ResourceServerPolicyJSDetailCtrl', function($scope, $route, $location, realm, PolicyController, client) {
PolicyController.onInit({
getPolicyType : function() {
return "js";
},
onInit : function() {
$scope.initEditor = function(editor){
var session = editor.getSession();
session.setMode('ace/mode/javascript');
};
},
onInitUpdate : function(policy) {
},
onUpdate : function() {
},
onInitCreate : function(newPolicy) {
newPolicy.config = {};
},
onCreate : function() {
}
}, realm, client, $scope);
});
module.controller('ResourceServerPolicyTimeDetailCtrl', function($scope, $route, $location, realm, PolicyController, client) {
PolicyController.onInit({
getPolicyType : function() {
return "time";
},
onInit : function() {
},
onInitUpdate : function(policy) {
},
onUpdate : function() {
},
onInitCreate : function(newPolicy) {
newPolicy.config.expirationTime = 1;
newPolicy.config.expirationUnit = 'Minutes';
},
onCreate : function() {
}
}, realm, client, $scope);
});
module.controller('ResourceServerPolicyAggregateDetailCtrl', function($scope, $route, $location, realm, PolicyController, ResourceServerPolicy, client) {
PolicyController.onInit({
getPolicyType : function() {
return "aggregate";
},
onInit : function() {
ResourceServerPolicy.query({realm : realm.realm, client : client.id}, function (data) {
$scope.policies = [];
for (i = 0; i < data.length; i++) {
if (data[i].type != 'resource' && data[i].type != 'scope') {
$scope.policies.push(data[i]);
}
}
});
},
onInitUpdate : function(policy) {
policy.config.applyPolicies = eval(policy.config.applyPolicies);
},
onUpdate : function() {
$scope.policy.config.applyPolicies = JSON.stringify($scope.policy.config.applyPolicies);
},
onInitCreate : function(newPolicy) {
newPolicy.config = {};
newPolicy.decisionStrategy = 'UNANIMOUS';
},
onCreate : function() {
$scope.policy.config.applyPolicies = JSON.stringify($scope.policy.config.applyPolicies);
}
}, realm, client, $scope);
});
module.service("PolicyController", function($http, $route, $location, ResourceServer, ResourceServerPolicy, AuthzDialog, Notifications) {
var PolicyController = {};
PolicyController.onInit = function(delegate, realm, client, $scope) {
if (!delegate.isPermission) {
delegate.isPermission = function () {
return false;
}
}
$scope.realm = realm;
$scope.client = client;
$scope.decisionStrategies = ['AFFIRMATIVE', 'UNANIMOUS', 'CONSENSUS'];
$scope.logics = ['POSITIVE', 'NEGATIVE'];
delegate.onInit();
var $instance = this;
ResourceServer.get({
realm : $route.current.params.realm,
client : client.id
}, function(data) {
$scope.server = data;
var policyId = $route.current.params.id;
if (!policyId) {
$scope.create = true;
$scope.changed = false;
var policy = {};
policy.type = delegate.getPolicyType();
policy.config = {};
policy.logic = 'POSITIVE';
if (delegate.onInitCreate) {
delegate.onInitCreate(policy);
}
$scope.policy = angular.copy(policy);
$scope.$watch('policy', function() {
if (!angular.equals($scope.policy, policy)) {
$scope.changed = true;
}
}, true);
$scope.save = function() {
$instance.checkNameAvailability(function () {
if (delegate.onCreate) {
delegate.onCreate();
}
ResourceServerPolicy.save({realm : realm.realm, client : client.id}, $scope.policy, function(data) {
if (delegate.isPermission()) {
$location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/permission/" + $scope.policy.type + "/" + data.id);
Notifications.success("The permission has been created.");
} else {
$location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/policy/" + $scope.policy.type + "/" + data.id);
Notifications.success("The policy has been created.");
}
});
});
}
$scope.cancel = function() {
if (delegate.isPermission()) {
$location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/permission/");
} else {
$location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/policy/");
}
}
} else {
ResourceServerPolicy.get({
realm : $route.current.params.realm,
client : client.id,
id : $route.current.params.id,
}, function(data) {
$scope.originalPolicy = data;
var policy = angular.copy(data);
if (delegate.onInitUpdate) {
delegate.onInitUpdate(policy);
}
$scope.policy = angular.copy(policy);
$scope.changed = false;
$scope.$watch('policy', function() {
if (!angular.equals($scope.policy, policy)) {
$scope.changed = true;
}
}, true);
$scope.save = function() {
$instance.checkNameAvailability(function () {
if (delegate.onUpdate) {
delegate.onUpdate();
}
ResourceServerPolicy.update({realm : realm.realm, client : client.id, id : $scope.policy.id}, $scope.policy, function() {
$route.reload();
if (delegate.isPermission()) {
Notifications.success("The permission has been updated.");
} else {
Notifications.success("The policy has been updated.");
}
});
});
}
$scope.reset = function() {
var freshPolicy = angular.copy(data);
if (delegate.onInitUpdate) {
delegate.onInitUpdate(freshPolicy);
}
$scope.policy = angular.copy(freshPolicy);
$scope.changed = false;
}
});
$scope.remove = function() {
var msg = "";
if ($scope.policy.dependentPolicies.length > 0) {
msg = "<p>This policy is being used by other policies:</p>";
msg += "<ul>";
for (i = 0; i < $scope.policy.dependentPolicies.length; i++) {
msg+= "<li><strong>" + $scope.policy.dependentPolicies[i].name + "</strong></li>";
}
msg += "</ul>";
msg += "<p>If you remove this policy, the policies above will be affected and will not be associated with this policy anymore.</p>";
}
AuthzDialog.confirmDeleteWithMsg($scope.policy.name, "Policy", msg, function() {
ResourceServerPolicy.delete({realm : $scope.realm.realm, client : $scope.client.id, id : $scope.policy.id}, null, function() {
if (delegate.isPermission()) {
$location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/permission");
Notifications.success("The permission has been deleted.");
} else {
$location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/policy");
Notifications.success("The policy has been deleted.");
}
});
});
}
}
});
$scope.checkNewNameAvailability = function () {
$instance.checkNameAvailability(function () {});
}
this.checkNameAvailability = function (onSuccess) {
ResourceServerPolicy.search({
realm: $route.current.params.realm,
client: client.id,
name: $scope.policy.name
}, function(data) {
if (data && data.id && data.id != $scope.policy.id) {
Notifications.error("Name already in use by another policy or permission, please choose another one.");
} else {
onSuccess();
}
});
}
}
return PolicyController;
});
module.controller('PolicyEvaluateCtrl', function($scope, $http, $route, $location, realm, clients, roles, ResourceServer, client, ResourceServerResource, ResourceServerScope, User, Notifications) {
$scope.realm = realm;
$scope.client = client;
$scope.clients = clients;
$scope.roles = roles;
$scope.authzRequest = {};
$scope.authzRequest.resources = [];
$scope.authzRequest.context = {};
$scope.authzRequest.context.attributes = {};
$scope.authzRequest.roleIds = [];
$scope.newResource = {};
$scope.resultUrl = resourceUrl + '/partials/authz/policy/resource-server-policy-evaluate-result.html';
ResourceServerScope.query({realm : realm.realm, client : client.id}, function (data) {
$scope.scopes = data;
});
$scope.addContextAttribute = function() {
if (!$scope.newContextAttribute.value || $scope.newContextAttribute.value == '') {
Notifications.error("You must provide a value to a context attribute.");
return;
}
$scope.authzRequest.context.attributes[$scope.newContextAttribute.key] = $scope.newContextAttribute.value;
delete $scope.newContextAttribute;
}
$scope.removeContextAttribute = function(key) {
delete $scope.authzRequest.context.attributes[key];
}
$scope.getContextAttribute = function(key) {
for (i = 0; i < $scope.defaultContextAttributes.length; i++) {
if ($scope.defaultContextAttributes[i].key == key) {
return $scope.defaultContextAttributes[i];
}
}
return $scope.authzRequest.context.attributes[key];
}
$scope.getContextAttributeName = function(key) {
var attribute = $scope.getContextAttribute(key);
if (!attribute.name) {
return key;
}
return attribute.name;
}
$scope.defaultContextAttributes = [
{
key : "custom",
name : "Custom Attribute...",
custom: true
},
{
key : "kc.identity.authc.method",
name : "Authentication Method",
values: [
{
key : "pwd",
name : "Password"
},
{
key : "otp",
name : "One-Time Password"
},
{
key : "kbr",
name : "Kerberos"
}
]
},
{
key : "kc.realm.name",
name : "Realm"
},
{
key : "kc.time.date_time",
name : "Date/Time (MM/dd/yyyy hh:mm:ss)"
},
{
key : "kc.client.network.ip_address",
name : "Client IPv4 Address"
},
{
key : "kc.client.network.host",
name : "Client Host"
},
{
key : "kc.client.user_agent",
name : "Client/User Agent"
}
];
$scope.isDefaultContextAttribute = function() {
if (!$scope.newContextAttribute) {
return true;
}
if ($scope.newContextAttribute.custom) {
return false;
}
if (!$scope.getContextAttribute($scope.newContextAttribute.key).custom) {
return true;
}
return false;
}
$scope.selectDefaultContextAttribute = function() {
$scope.newContextAttribute = angular.copy($scope.newContextAttribute);
}
$scope.setApplyToResourceType = function() {
if ($scope.applyResourceType) {
ResourceServerScope.query({realm : realm.realm, client : client.id}, function (data) {
$scope.scopes = data;
});
}
delete $scope.newResource;
$scope.authzRequest.resources = [];
}
$scope.addResource = function() {
var resource = {};
resource.id = $scope.newResource._id;
for (i = 0; i < $scope.resources.length; i++) {
if ($scope.resources[i]._id == resource.id) {
resource.name = $scope.resources[i].name;
break;
}
}
resource.scopes = $scope.newResource.scopes;
$scope.authzRequest.resources.push(resource);
delete $scope.newResource;
}
$scope.removeResource = function(index) {
$scope.authzRequest.resources.splice(index, 1);
}
$scope.resolveScopes = function() {
if ($scope.newResource._id) {
$scope.newResource.scopes = [];
$scope.scopes = [];
ResourceServerResource.get({
realm: $route.current.params.realm,
client : client.id,
rsrid: $scope.newResource._id
}, function (data) {
$scope.scopes = data.scopes;
if (data.typedScopes) {
for (i=0;i<data.typedScopes.length;i++) {
$scope.scopes.push(data.typedScopes[i]);
}
}
});
} else {
ResourceServerScope.query({realm : realm.realm, client : client.id}, function (data) {
$scope.scopes = data;
});
}
}
$scope.reevaluate = function() {
if ($scope.authzRequest.entitlements) {
$scope.entitlements();
} else {
$scope.save();
}
}
$scope.showAuthzData = function() {
$scope.showRpt = true;
}
$scope.save = function() {
$scope.authzRequest.entitlements = false;
if ($scope.applyResourceType) {
if (!$scope.newResource) {
$scope.newResource = {};
}
$scope.authzRequest.resources[0].scopes = $scope.newResource.scopes;
}
$http.post(authUrl + '/admin/realms/'+ $route.current.params.realm + '/clients/' + client.id + '/authz/resource-server/policy/evaluate'
, $scope.authzRequest).success(function(data) {
$scope.evaluationResult = data;
$scope.showResultTab();
});
}
$scope.entitlements = function() {
$scope.authzRequest.entitlements = true;
$http.post(authUrl + '/admin/realms/'+ $route.current.params.realm + '/clients/' + client.id + '/authz/resource-server/policy/evaluate'
, $scope.authzRequest).success(function(data) {
$scope.evaluationResult = data;
$scope.showResultTab();
});
}
$scope.showResultTab = function() {
$scope.showResult = true;
$scope.showRpt = false;
}
$scope.showRequestTab = function() {
$scope.showResult = false;
$scope.showRpt = false;
}
$scope.usersUiSelect = {
minimumInputLength: 1,
delay: 500,
allowClear: true,
query: function (query) {
var data = {results: []};
if ('' == query.term.trim()) {
query.callback(data);
return;
}
User.query({realm: $route.current.params.realm, search: query.term.trim(), max: 20}, function(response) {
data.results = response;
query.callback(data);
});
},
formatResult: function(object, container, query) {
object.text = object.username;
return object.username;
}
};
ResourceServerResource.query({realm : realm.realm, client : client.id}, function (data) {
$scope.resources = data;
});
ResourceServer.get({
realm : $route.current.params.realm,
client : client.id
}, function(data) {
$scope.server = data;
});
$scope.selectUser = function(user) {
if (!user || !user.id) {
$scope.selectedUser = null;
$scope.authzRequest.userId = '';
return;
}
$scope.authzRequest.userId = user.id;
}
}); | {
"content_hash": "a12415c0a0d03f0d97bab5126e7506ca",
"timestamp": "",
"source": "github",
"line_count": 1454,
"max_line_length": 202,
"avg_line_length": 35.38445667125172,
"alnum_prop": 0.48755077844078604,
"repo_name": "openfact/openfact-temp",
"id": "ec37854c9cca90a309d1d4b4e8c6d296fc46c2dc",
"size": "51449",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "themes/src/main/resources/theme/base/admin/resources/js/authz/authz-controller.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "346479"
},
{
"name": "FreeMarker",
"bytes": "68800"
},
{
"name": "HTML",
"bytes": "555105"
},
{
"name": "Java",
"bytes": "7445324"
},
{
"name": "JavaScript",
"bytes": "775205"
},
{
"name": "Shell",
"bytes": "1357"
}
],
"symlink_target": ""
} |
<component name="libraryTable">
<library name="appcompat-v7-25.0.0">
<ANNOTATIONS>
<root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/25.0.0/annotations.zip!/" />
<root url="jar://$PROJECT_DIR$/mvp/build/intermediates/exploded-aar/com.android.support/appcompat-v7/25.0.0/annotations.zip!/" />
</ANNOTATIONS>
<CLASSES>
<root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/25.0.0/jars/classes.jar!/" />
<root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/25.0.0/res" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://E:/Android/SDK/extras/android/m2repository/com/android/support/appcompat-v7/25.0.0/appcompat-v7-25.0.0-sources.jar!/" />
<root url="jar://E:/Android/SDK/extras/android/m2repository/com/android/support/appcompat-v7/25.0.0/appcompat-v7-25.0.0-sources.jar!/" />
</SOURCES>
</library>
</component> | {
"content_hash": "cd113ced786c9d70cc7e0475e639f637",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 143,
"avg_line_length": 60.411764705882355,
"alnum_prop": 0.6932814021421616,
"repo_name": "weiwenqiang/GitHub",
"id": "03273aea2d7686b510bb4b3e5a1bd609abe2cc9d",
"size": "1027",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MVP/XDroidMvp-master/.idea/libraries/appcompat_v7_25_0_0.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "87"
},
{
"name": "C",
"bytes": "42062"
},
{
"name": "C++",
"bytes": "12137"
},
{
"name": "CMake",
"bytes": "202"
},
{
"name": "CSS",
"bytes": "75087"
},
{
"name": "Clojure",
"bytes": "12036"
},
{
"name": "FreeMarker",
"bytes": "21704"
},
{
"name": "Groovy",
"bytes": "55083"
},
{
"name": "HTML",
"bytes": "61549"
},
{
"name": "Java",
"bytes": "42222825"
},
{
"name": "JavaScript",
"bytes": "216823"
},
{
"name": "Kotlin",
"bytes": "24319"
},
{
"name": "Makefile",
"bytes": "19490"
},
{
"name": "Perl",
"bytes": "280"
},
{
"name": "Prolog",
"bytes": "1030"
},
{
"name": "Python",
"bytes": "13032"
},
{
"name": "Scala",
"bytes": "310450"
},
{
"name": "Shell",
"bytes": "27802"
}
],
"symlink_target": ""
} |
background:#f0f0f0 url(images/bodybg-black2.jpg) repeat-x;
}
a {
color:#4E4E4E;
}
#leftside ul.box li a {
color:#4E4E4E;
}
#mainmenu a {
color: #4E4E4E;
}
#mainmenu a:hover {
background: url(images/menuhover-black.jpg) center left repeat-x;
}
#mainmenu li.current a, #mainmenu li.current_page_item a {
background: url(images/menuhover-black.jpg) center left repeat-x;
}
#mainmenu li.currentparent a {
background: url(images/menuhover-black.jpg) center left repeat-x;
} | {
"content_hash": "c166e46dfb4eab2d8228d55dc6d3db8b",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 66,
"avg_line_length": 18.5,
"alnum_prop": 0.7214137214137214,
"repo_name": "NewWorldOrderly/portfolio",
"id": "1d5b9483404d12456c5dca5f1c9102b2ac0c7a7a",
"size": "495",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "old-site/wp-content/themes/andreas09/black2.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4763840"
},
{
"name": "JavaScript",
"bytes": "2613430"
},
{
"name": "PHP",
"bytes": "15794892"
},
{
"name": "Shell",
"bytes": "406"
}
],
"symlink_target": ""
} |
"use strict";
let should = require("should");
let sinon = require("sinon");
let eslint = require("../");
let fs = require("fs");
let path = require("path");
let Metalsmith = require("metalsmith");
describe("metalsmith-eslint", function() {
let sandbox = null;
beforeEach(function() {
sandbox = sinon.createSandbox();
sandbox.stub(console, "log");
});
afterEach(function() {
sandbox.restore();
});
it("should work with an eslintrc configuration with env and globals and a formatter, failing on a file with correct console output", function(done) {
Metalsmith("test/fixtures/basic")
.use(eslint({
eslintConfig: JSON.parse(fs.readFileSync(path.join(process.cwd(), "test/fixtures/basic/src/strict-eslint-rules"), "utf8")),
formatter: "unix"
}))
.build(function(err) {
err.should.be.an.Error();
err.message.should.equal("Linting failed with 3 errors!");
sinon.assert.calledOnce(console.log);
sinon.assert.calledWithExactly(console.log, "eslintThisFail.js:1:1: Use the global form of 'use strict'. [Warning/strict]\neslintThisFail.js:1:14: Unexpected space before function parentheses. [Error/space-before-function-paren]\neslintThisFail.js:1:15: There should be no spaces inside this paren. [Error/space-in-parens]\neslintThisFail.js:2:15: Strings must use doublequote. [Error/quotes]\neslintThisWarn.js:1:1: Use the global form of 'use strict'. [Warning/strict]\n\n5 problems");
return done();
});
});
it("should obey file filters, and only warn but not fail if there is no error", function(done) {
Metalsmith("test/fixtures/basic")
.use(eslint({
src: ["**/*.js", "!**Fail**"],
eslintConfig: JSON.parse(fs.readFileSync(path.join(process.cwd(), "test/fixtures/basic/src/strict-eslint-rules"), "utf8")),
formatter: "unix"
}))
.build(function(err) {
should(err).be.null();
sinon.assert.calledOnce(console.log);
sinon.assert.calledWithExactly(console.log, "eslintThisWarn.js:1:1: Use the global form of 'use strict'. [Warning/strict]\n\n1 problem");
return done();
});
});
it("should not output any output and not fail if there is no error and warning", function(done) {
Metalsmith("test/fixtures/basic")
.use(eslint({
src: ["**/*Success.js"],
eslintConfig: JSON.parse(fs.readFileSync(path.join(process.cwd(), "test/fixtures/basic/src/strict-eslint-rules"), "utf8"))
}))
.build(function(err) {
should(err).be.null();
sinon.assert.notCalled(console.log);
return done();
});
});
});
| {
"content_hash": "9eff0e99831519b0bba7a3ecbe204a15",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 495,
"avg_line_length": 42.04761904761905,
"alnum_prop": 0.6515666289165722,
"repo_name": "ubenzer/metalsmith-eslint",
"id": "221dc0968207e8b372e5d87e569293bf334e55f6",
"size": "2649",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/index.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "4669"
}
],
"symlink_target": ""
} |
package org.sakaiproject.portal.render.portlet.services;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.portlet.PortalContext;
import javax.portlet.PortletMode;
import javax.portlet.WindowState;
import org.sakaiproject.component.cover.ServerConfigurationService;
/**
* @author ddwolf
* @author ieb
* @since Sakai 2.4
* @version $Rev: 105079 $
*/
public class SakaiPortalContext implements PortalContext
{
private ArrayList modes;
private ArrayList states;
private Map properties;
public SakaiPortalContext()
{
properties = new HashMap();
modes = new ArrayList();
states = new ArrayList();
modes.add(PortletMode.VIEW);
modes.add(PortletMode.HELP);
modes.add(PortletMode.EDIT);
states.add(WindowState.MAXIMIZED);
states.add(WindowState.MINIMIZED);
states.add(WindowState.NORMAL);
}
public SakaiPortalContext(Map properties)
{
this.properties = properties;
}
public String getProperty(String key)
{
return (String) properties.get(key);
}
public Enumeration getPropertyNames()
{
return new IteratorEnumeration(properties.keySet().iterator());
}
public Enumeration getSupportedPortletModes()
{
return new IteratorEnumeration(modes.iterator());
}
public Enumeration getSupportedWindowStates()
{
return new IteratorEnumeration(states.iterator());
}
/**
* @todo Dynamic
* @return
*/
public String getPortalInfo()
{
return "Sakai-Charon/" + ServerConfigurationService.getString("version.sakai");
}
class IteratorEnumeration implements Enumeration
{
private Iterator iterator;
public IteratorEnumeration(Iterator iterator)
{
this.iterator = iterator;
}
public boolean hasMoreElements()
{
return iterator.hasNext();
}
public Object nextElement()
{
return iterator.next();
}
}
}
| {
"content_hash": "2722bec06c004a6724166c3e0aad19e3",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 81,
"avg_line_length": 18.50980392156863,
"alnum_prop": 0.7409957627118644,
"repo_name": "eemirtekin/Sakai-10.6-TR",
"id": "b8bcf58cb4eae0b24c8b44c8975fe107abb6cda2",
"size": "3044",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "portal/portal-render-impl/impl/src/java/org/sakaiproject/portal/render/portlet/services/SakaiPortalContext.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "59098"
},
{
"name": "Batchfile",
"bytes": "6366"
},
{
"name": "C++",
"bytes": "6402"
},
{
"name": "CSS",
"bytes": "2616828"
},
{
"name": "ColdFusion",
"bytes": "146057"
},
{
"name": "HTML",
"bytes": "5982358"
},
{
"name": "Java",
"bytes": "49585098"
},
{
"name": "JavaScript",
"bytes": "6722774"
},
{
"name": "Lasso",
"bytes": "26436"
},
{
"name": "PHP",
"bytes": "223840"
},
{
"name": "PLSQL",
"bytes": "2163243"
},
{
"name": "Perl",
"bytes": "102776"
},
{
"name": "Python",
"bytes": "87575"
},
{
"name": "Ruby",
"bytes": "3606"
},
{
"name": "Shell",
"bytes": "33041"
},
{
"name": "SourcePawn",
"bytes": "2274"
},
{
"name": "XSLT",
"bytes": "607759"
}
],
"symlink_target": ""
} |
package org.gestern.gringotts.event;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.gestern.gringotts.Language;
import org.gestern.gringotts.accountholder.AccountHolder;
/**
* Event that is thrown after Gringotts detects a vault creation.
* When thrown, it includes the type of the vault, for example "player" or "faction"
* and is set to invalid with an empty message.
* <p>
* Listeners may set the event to valid, which will cause a vault of the given type to be
* created by Gringotts. Optionally, a custom message will be sent to the owner of the account.
*
* @author jast
*/
public class VaultCreationEvent extends Event {
protected static final HandlerList handlers = new HandlerList();
private final Type type;
private boolean isValid = false;
private AccountHolder owner;
/**
* Create VaultCreationEvent for a given vault type.
*
* @param type Type of vault being created
*/
public VaultCreationEvent(Type type) {
this.type = type;
}
public enum Type {
PLAYER,
FACTION,
TOWN,
NATION,
REGION
}
@SuppressWarnings("unused")
public static HandlerList getHandlerList() {
return handlers;
}
public Type getType() {
return type;
}
/**
* Return whether this is a valid vault type.
* false by default. A Listener may set this to true.
*
* @return whether this is a valid vault.
*/
public boolean isValid() {
return isValid;
}
/**
* Set valid status of vault being created. This is false by default.
* A listener that sets this to true must also ensure that an owner is supplied.
*
* @param valid valid status to set
*/
public void setValid(boolean valid) {
this.isValid = valid;
}
/**
* Get message sent to account owner on creation of this vault.
*
* @return message sent to account owner on creation of this vault.
*/
public String getMessage() {
return Language.LANG.vault_created;
}
/**
* Get account holder supplied as owner for the vault being created.
*
* @return account holder supplied as owner for the vault being created.
*/
public AccountHolder getOwner() {
return owner;
}
/**
* Set the account holder acting as the owner of the vault being created.
* When the valid status is also true, this will enable the vault to be registered with Gringotts.
*
* @param owner owner of the vault being created
*/
public void setOwner(AccountHolder owner) {
this.owner = owner;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
}
| {
"content_hash": "ccb669cc2db366c462e0615f4b8129ef",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 102,
"avg_line_length": 26.438095238095237,
"alnum_prop": 0.646613832853026,
"repo_name": "usevalue/Gringotts",
"id": "eb4ea006db9581e4cbd4d29785f3d2516a79a54c",
"size": "2776",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/org/gestern/gringotts/event/VaultCreationEvent.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Java",
"bytes": "192029"
}
],
"symlink_target": ""
} |
<?php
class Google_Service_CertificateAuthorityService_GoogleApiServicecontrolV1QuotaProperties extends Google_Model
{
public $quotaMode;
public function setQuotaMode($quotaMode)
{
$this->quotaMode = $quotaMode;
}
public function getQuotaMode()
{
return $this->quotaMode;
}
}
| {
"content_hash": "b8a855efe99ad615c46bbf745194c1cb",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 110,
"avg_line_length": 18.8125,
"alnum_prop": 0.7408637873754153,
"repo_name": "bshaffer/google-api-php-client-services",
"id": "2a83c4d025bd60b02a11e81ab7bb3ed931372b3b",
"size": "891",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Google/Service/CertificateAuthorityService/GoogleApiServicecontrolV1QuotaProperties.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "9540154"
}
],
"symlink_target": ""
} |
namespace SADFM.Data
{
using System;
using System.Collections.Generic;
public partial class ScaleItemHeader
{
public System.Guid ScaleItemHeaderId { get; set; }
public System.Guid ScaleItemId { get; set; }
public string Name { get; set; }
public virtual ListItem ScaleItem { get; set; }
}
}
| {
"content_hash": "b4f8cc7fabdcfbef6d87a55a057001f6",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 58,
"avg_line_length": 25.214285714285715,
"alnum_prop": 0.6260623229461756,
"repo_name": "developersworkspace/EPONS",
"id": "e28348fa62a5b7d38b2cbabe9061bea1ee3e88fd",
"size": "777",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SourceCode/SADFM/trunk/SADFM.Data/ScaleItemHeader.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "326"
},
{
"name": "Batchfile",
"bytes": "4291"
},
{
"name": "C#",
"bytes": "3191410"
},
{
"name": "CSS",
"bytes": "1420644"
},
{
"name": "Gherkin",
"bytes": "1037"
},
{
"name": "HTML",
"bytes": "6334"
},
{
"name": "JavaScript",
"bytes": "3934231"
},
{
"name": "PLpgSQL",
"bytes": "472130"
},
{
"name": "SQLPL",
"bytes": "721"
},
{
"name": "TypeScript",
"bytes": "4663"
}
],
"symlink_target": ""
} |
@interface CDVAlipay : CDVPlugin
@property(nonatomic,strong)NSString *partner;
@property(nonatomic,strong)NSString *rsa_private;
@property(nonatomic,strong)NSString *rsa_public;
@property(nonatomic,strong)NSString *currentCallbackId;
- (void)pay:(CDVInvokedUrlCommand*)command;
@end
| {
"content_hash": "0609c06f1dd910b5c87a8cc25bb94a0c",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 55,
"avg_line_length": 28.6,
"alnum_prop": 0.8076923076923077,
"repo_name": "Diaosir/WeX5",
"id": "d3429388eb7f335c6b861e4ad05fce5c28dcd358",
"size": "446",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "Native/plugins/com.justep.cordova.plugin.alipay/src/ios/CDVAlipay.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AppleScript",
"bytes": "1208"
},
{
"name": "Batchfile",
"bytes": "11305"
},
{
"name": "C",
"bytes": "2335555"
},
{
"name": "C#",
"bytes": "418354"
},
{
"name": "C++",
"bytes": "1075715"
},
{
"name": "CSS",
"bytes": "3334480"
},
{
"name": "HTML",
"bytes": "182541"
},
{
"name": "Java",
"bytes": "4466548"
},
{
"name": "JavaScript",
"bytes": "11023461"
},
{
"name": "Objective-C",
"bytes": "1401370"
},
{
"name": "Objective-C++",
"bytes": "36131"
},
{
"name": "QML",
"bytes": "14604"
},
{
"name": "Shell",
"bytes": "29370"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>hammer-tactics: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.10.0 / hammer-tactics - 1.3.2+8.12</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
hammer-tactics
<small>
1.3.2+8.12
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2021-12-31 19:49:08 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-12-31 19:49:08 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.10.0 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.09.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.1 Official release 4.09.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/lukaszcz/coqhammer"
dev-repo: "git+https://github.com/lukaszcz/coqhammer.git"
bug-reports: "https://github.com/lukaszcz/coqhammer/issues"
license: "LGPL-2.1-only"
synopsis: "Reconstruction tactics for the hammer for Coq"
description: """
Collection of tactics that are used by the hammer for Coq
to reconstruct proofs found by automated theorem provers. When the hammer
has been successfully applied to a project, only this package needs
to be installed; the hammer plugin is not required.
"""
build: [make "-j%{jobs}%" "tactics"]
install: [
[make "install-tactics"]
[make "test-tactics"] {with-test}
]
depends: [
"ocaml" { >= "4.08" }
"coq" {>= "8.12" & < "8.13~"}
]
conflicts: [
"coq-hammer" {!= version}
]
tags: [
"keyword:automation"
"keyword:hammer"
"keyword:tactics"
"logpath:Hammer.Tactics"
"date:2021-10-01"
]
authors: [
"Lukasz Czajka <[email protected]>"
]
url {
src: "https://github.com/lukaszcz/coqhammer/archive/v1.3.2-coq8.12.tar.gz"
checksum: "sha512=10f7bbf5b03101fda47953fc53981b46b5f368558ce4efa8944b0fa67f220c94f4dd21068a1bcaf0ceb771ba9e94c8c6558c8863720157e27407133c43bf0282"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-hammer-tactics.1.3.2+8.12 coq.8.10.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.10.0).
The following dependencies couldn't be met:
- coq-hammer-tactics -> coq >= 8.12
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-hammer-tactics.1.3.2+8.12</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "beb34be58fc4ea5a9045d0af10847522",
"timestamp": "",
"source": "github",
"line_count": 178,
"max_line_length": 159,
"avg_line_length": 39.92696629213483,
"alnum_prop": 0.5535387645982833,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "e423d754fb4daadb4625682ffabc125f0379bc56",
"size": "7132",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.09.1-2.0.6/released/8.10.0/hammer-tactics/1.3.2+8.12.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
var Hapi = require('hapi');
var Joi = require('joi');
var Boom = require('boom');
var IdeaService = require('../services/ideaService.js');
var TagService = require('../services/tagService.js');
var SkillService = require('../services/skillService.js');
var TechnologyService = require('../services/technologyService.js');
module.exports = function(config) {
var ideaSvc = new IdeaService(config.db);
var tagSvc = new TagService(config.db);
var skillSvc = new SkillService(config.db);
var techSvc = new TechnologyService(config.db);
return [
{
path: '/api/ideas/{id}',
method: 'GET',
handler: function(request, reply) {
ideaSvc.getByID(request.params.id,
function(err) {
reply(Boom.badImplementation());
},
function(obj) {
reply(obj || Boom.notFound());
}
);
},
config: {
description: 'Get a single idea by id',
auth: 'session',
validate: {
params: {
id: Joi.string().required()
}
}
}
},
{
path: '/api/ideas',
method: 'GET',
handler: function(request, reply) {
var search = request.query.search;
if (search) {
ideaSvc.search(search, error, success);
} else {
ideaSvc.getAll(error, success);
}
function error(err) {
reply(Boom.badImplementation());
}
function success(obj) {
reply(obj || []);
}
},
config: {
description: 'Get all ideas',
auth: 'session',
validate: { }
}
},
{
path: '/api/ideas',
method: 'POST',
handler: function(request, reply) {
ideaSvc.insert(request.payload,
function(err) {
reply(Boom.badImplementation());
},
function(idea) {
if (idea === null) {
reply(Boom.badImplementation());
}
else {
var j;
for (j = 0; j < idea.tags.length; j++) {
tagSvc.save(idea.tags[j]);
}
for (j = 0; j < idea.skills.length; j++) {
skillSvc.save(idea.skills[j]);
}
for (j = 0; j < idea.technologies.length; j++) {
techSvc.save(idea.technologies[j]);
}
reply(idea).created('/api/ideas/' + idea.id);
}
}
);
},
config: {
description: 'Create a new idea',
auth: 'session',
validate: {
payload: {
name: Joi.string().required(),
summary: Joi.string().required().allow(''),
benefits: Joi.string().required().allow(''),
details: Joi.string().required().allow(''),
state: Joi.string().required(),
tags: Joi.array().required(),
skills: Joi.array().required(),
technologies: Joi.array().required(),
repo: Joi.string().required().allow(''),
proposers: Joi.array().required(),
contributors: Joi.array().required(),
contributorRequests: Joi.array().required(),
isPublic: Joi.boolean().required(),
votes: Joi.array().required(),
voteCount: Joi.number().required(),
comments: Joi.array().required(),
createdDate: Joi.string().required(),
updatedDate: Joi.string().required()
}
}
}
},
{
path: '/api/ideas/{id}',
method: 'PUT',
handler: function(request, reply) {
if (request.payload.hasOwnProperty('id') && request.params.id !== request.payload.id) {
return reply(Boom.badRequest(
'Unable to change the id on the resource. Please ensure the id in the path matches the id in the payload.'));
}
var idea = request.payload;
ideaSvc.update(idea,
function(err) {
reply(Boom.badImplementation());
},
function(successful) {
if (!successful) {
reply(Boom.notFound());
} else {
var j;
for (j = 0; j < idea.tags.length; j++) {
tagSvc.save(idea.tags[j]);
}
for (j = 0; j < idea.skills.length; j++) {
skillSvc.save(idea.skills[j]);
}
for (j = 0; j < idea.technologies.length; j++) {
techSvc.save(idea.technologies[j]);
}
reply().code(204);
}
}
);
},
config: {
description: 'Updates an existing idea',
auth: 'session',
validate: {
params: {
id: Joi.string().required()
},
payload: {
id: Joi.string().required(),
name: Joi.string().required(),
summary: Joi.string().required().allow(''),
benefits: Joi.string().required().allow(''),
details: Joi.string().required().allow(''),
state: Joi.string().required(),
tags: Joi.array().required(),
skills: Joi.array().required(),
technologies: Joi.array().required(),
repo: Joi.string().required().allow(''),
proposers: Joi.array().required(),
contributors: Joi.array().required(),
contributorRequests: Joi.array().required(),
isPublic: Joi.boolean().required(),
votes: Joi.array().required(),
voteCount: Joi.number().required(),
comments: Joi.array().required(),
createdDate: Joi.string().required(),
updatedDate: Joi.string().required()
}
}
}
},
{
path: '/api/ideas/{id}',
method: 'DELETE',
handler: function(request, reply) {
ideaSvc.remove(request.params.id,
function(err) {
reply(Boom.badImplementation());
},
function(successful) {
if (!successful) {
reply(Boom.notFound());
} else {
reply().code(204);
}
}
);
},
config: {
description: 'Remove an existing idea',
auth: 'session',
validate: {
params: {
id: Joi.string().required()
}
}
}
}
];
};
| {
"content_hash": "e8275751cd2d224e2f739dc599f0099f",
"timestamp": "",
"source": "github",
"line_count": 212,
"max_line_length": 133,
"avg_line_length": 39.39622641509434,
"alnum_prop": 0.3703304597701149,
"repo_name": "davelaursen/idealogue",
"id": "c84ae7b731500234f70812dd6609e24f71c614db",
"size": "8352",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "angular1-node-hapi-mongodb/src/server/routes/ideaRoutes.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "51634"
},
{
"name": "HTML",
"bytes": "54706"
},
{
"name": "JavaScript",
"bytes": "200640"
},
{
"name": "TypeScript",
"bytes": "194642"
}
],
"symlink_target": ""
} |
package org.jbpm.compiler.xml.processes;
import java.util.HashSet;
import org.drools.core.xml.BaseAbstractHandler;
import org.drools.core.xml.ExtensibleXmlParser;
import org.drools.core.xml.Handler;
import org.jbpm.workflow.core.Constraint;
import org.jbpm.workflow.core.impl.ConnectionRef;
import org.jbpm.workflow.core.impl.ConstraintImpl;
import org.jbpm.workflow.core.impl.NodeImpl;
import org.jbpm.workflow.core.node.Constrainable;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
public class ConstraintHandler extends BaseAbstractHandler implements Handler {
public ConstraintHandler() {
if ((this.validParents == null) && (this.validPeers == null)) {
this.validParents = new HashSet<Class<?>>();
this.validParents.add(Constrainable.class);
this.validPeers = new HashSet<Class<?>>();
this.validPeers.add(null);
this.allowNesting = false;
}
}
public Object start(final String uri,
final String localName,
final Attributes attrs,
final ExtensibleXmlParser parser) throws SAXException {
parser.startElementBuilder( localName,
attrs );
return null;
}
public Object end(final String uri,
final String localName,
final ExtensibleXmlParser parser) throws SAXException {
final Element element = parser.endElementBuilder();
Constrainable parent = (Constrainable) parser.getParent();
Constraint constraint = new ConstraintImpl();
final String toNodeIdString = element.getAttribute("toNodeId");
String toType = element.getAttribute("toType");
ConnectionRef connectionRef = null;
if (toNodeIdString != null && toNodeIdString.trim().length() > 0) {
int toNodeId = new Integer(toNodeIdString);
if (toType == null || toType.trim().length() == 0) {
toType = NodeImpl.CONNECTION_DEFAULT_TYPE;
}
connectionRef = new ConnectionRef(toNodeId, toType);
}
final String name = element.getAttribute("name");
constraint.setName(name);
final String priority = element.getAttribute("priority");
if (priority != null && priority.length() != 0) {
constraint.setPriority(new Integer(priority));
}
final String type = element.getAttribute("type");
constraint.setType(type);
final String dialect = element.getAttribute("dialect");
constraint.setDialect(dialect);
String text = ((Text)element.getChildNodes().item( 0 )).getWholeText();
if (text != null) {
text = text.trim();
if ("".equals(text)) {
text = null;
}
}
constraint.setConstraint(text);
parent.addConstraint(connectionRef, constraint);
return null;
}
@SuppressWarnings("unchecked")
public Class generateNodeFor() {
return Constraint.class;
}
}
| {
"content_hash": "6a395f49cbf630fc1c9baf90c2c1c87a",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 79,
"avg_line_length": 34.91208791208791,
"alnum_prop": 0.6216556499842619,
"repo_name": "xingguang2013/jbpm-1",
"id": "3ac23110a1882915fcc13f24f5f4da7f2244073c",
"size": "3727",
"binary": false,
"copies": "14",
"ref": "refs/heads/master",
"path": "jbpm-flow-builder/src/main/java/org/jbpm/compiler/xml/processes/ConstraintHandler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "251"
},
{
"name": "Java",
"bytes": "10382223"
},
{
"name": "Protocol Buffer",
"bytes": "6420"
},
{
"name": "Shell",
"bytes": "98"
}
],
"symlink_target": ""
} |
<?php
namespace Sender;
use Zend\Stdlib\Parameters;
use Zend\Http\Request,
Zend\Http\Client;
/**
* Description of Sender
*
* @author seyfer
*/
class Sender {
/**
*
* @var Client
*/
private $client;
private $url;
public function __construct()
{
$this->client = new Client();
$this->client->setAdapter('Zend\Http\Client\Adapter\Curl');
}
/**
* отправить пост
* @param \Zend\Stdlib\Parameters|array $post
* @return type
* @throws \Auth\Model\Exception
*/
public function sendPost($url, $post = array())
{
$this->url = $url;
if (!$post instanceof Parameters) {
if (is_array($post)) {
$post = new Parameters($post);
} else {
throw new Exception(__METHOD__ . " param need: Parameters or array");
}
}
$postRequest = $this->preparePostRequest($post);
try {
$response = $this->client->send($postRequest);
$result = $response->getBody();
return $result;
} catch (\Exception $exc) {
throw $exc;
}
}
private function preparePostRequest($post)
{
$postRequest = new Request();
$postRequest->setMethod(Request::METHOD_POST);
$postRequest->setPost($post);
$postRequest->setUri($this->url);
$postRequest->getHeaders()->addHeaders([
'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'
]);
return $postRequest;
}
}
| {
"content_hash": "ee40bc9dd3395b9bd765e17796e91a5d",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 85,
"avg_line_length": 22,
"alnum_prop": 0.5321969696969697,
"repo_name": "seyfer/zend2-tutorial.me",
"id": "006511e8fbe714bf2791c3fe850ad945d55e9088",
"size": "1597",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "module/Sender/src/Sender/Sender.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "711"
},
{
"name": "CSS",
"bytes": "5675"
},
{
"name": "HTML",
"bytes": "77503"
},
{
"name": "JavaScript",
"bytes": "163747"
},
{
"name": "PHP",
"bytes": "220888"
}
],
"symlink_target": ""
} |
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/gollum.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/gollum.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/gollum"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/gollum"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
| {
"content_hash": "6b0abc72ec18bc96727bb828438f54f1",
"timestamp": "",
"source": "github",
"line_count": 173,
"max_line_length": 343,
"avg_line_length": 38.5606936416185,
"alnum_prop": 0.706490780992355,
"repo_name": "skyportsystems/gollum",
"id": "6aebeb8ee31a5e165aa59d4dd76e2655c98f5f0c",
"size": "6763",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "docs/Makefile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "341828"
},
{
"name": "Makefile",
"bytes": "883"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "0856dabc3943d2746b2b5d95766a4a17",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "cdf79790c08e1cd6460e8a20654f44f678d5b6eb",
"size": "178",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ranunculales/Papaveraceae/Hesperomecon/Hesperomecon strictum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package com.netflix.hollow.core.read.missing;
import com.netflix.hollow.api.objects.HollowRecord;
import com.netflix.hollow.api.objects.delegate.HollowRecordDelegate;
import com.netflix.hollow.core.read.dataaccess.HollowTypeDataAccess;
import com.netflix.hollow.core.schema.HollowSchema;
public class FakeMissingHollowRecord implements HollowRecord {
private final HollowTypeDataAccess dataAccess;
private final int ordinal;
public FakeMissingHollowRecord(HollowTypeDataAccess dataAccess, int ordinal) {
this.dataAccess = dataAccess;
this.ordinal = ordinal;
}
@Override
public int getOrdinal() {
return ordinal;
}
@Override
public HollowSchema getSchema() {
return dataAccess.getSchema();
}
@Override
public HollowTypeDataAccess getTypeDataAccess() {
return dataAccess;
}
@Override
public HollowRecordDelegate getDelegate() {
throw new UnsupportedOperationException();
}
}
| {
"content_hash": "9185a14b50cda4d9983a5e6781f49f78",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 82,
"avg_line_length": 26.157894736842106,
"alnum_prop": 0.7303822937625755,
"repo_name": "Netflix/hollow",
"id": "f744a859d93af0b6ead1b94b32568324802f5fae",
"size": "1635",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hollow/src/test/java/com/netflix/hollow/core/read/missing/FakeMissingHollowRecord.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "4299"
},
{
"name": "Java",
"bytes": "4694590"
},
{
"name": "JavaScript",
"bytes": "1703"
},
{
"name": "Shell",
"bytes": "1730"
}
],
"symlink_target": ""
} |
/*eslint no-console:0 */
define(
'tinymce.themes.modern.demo.NotificationDemo',
[
'ephox.katamari.api.Arr',
'global!console',
'global!document',
'global!setTimeout',
'tinymce.core.EditorManager',
'tinymce.themes.modern.Theme'
],
function (Arr, console, document, setTimeout, EditorManager, ModernTheme) {
ModernTheme();
var notifyShort = function (type) {
var notification = EditorManager.activeEditor.notificationManager.open({
type: type,
text: 'This is an example ' + (type ? type : 'blank') + ' message.'
});
setTimeout(function () {
notification.text('Message changed.');
}, 5000);
console.log(notification);
};
var notifyLong = function (len) {
var longTextMessage = [];
for (var i = 0; i < len; i++) {
longTextMessage.push('bla');
}
var notification = EditorManager.activeEditor.notificationManager.open({
text: longTextMessage.join(' ')
});
console.log(notification);
};
var notifyExtraLong = function (len) {
var longTextMessage = ['this is text '];
for (var i = 0; i < len; i++) {
longTextMessage.push('bla');
}
var notification = EditorManager.activeEditor.notificationManager.open({
text: longTextMessage.join('')
});
console.log(notification);
};
var notifyProgress = function (percent) {
var notification = EditorManager.activeEditor.notificationManager.open({
text: 'Progress text',
progressBar: true
});
notification.progressBar.value(percent);
setTimeout(function () {
notification.progressBar.value(90);
}, 5000);
console.log(notification);
};
var notifyTimeout = function (time) {
var notification = EditorManager.activeEditor.notificationManager.open({
text: 'Timeout: ' + time,
timeout: time
});
console.log(notification);
};
var notifyIcon = function () {
var notification = EditorManager.activeEditor.notificationManager.open({
text: 'Text',
icon: 'bold'
});
console.log(notification);
};
Arr.each([
{ title: 'success', action: notifyShort, value: 'success' },
{ title: 'error', action: notifyShort, value: 'error' },
{ title: 'warn', action: notifyShort, value: 'warning' },
{ title: 'info', action: notifyShort, value: 'info' },
{ title: 'blank', action: notifyShort },
{ title: 'notifyLong', action: notifyLong, value: 100 },
{ title: 'notifyExtraLong', action: notifyExtraLong, value: 100 },
{ title: 'notifyProgress', action: notifyProgress, value: 50 },
{ title: 'notifyTimeout', action: notifyTimeout, value: 3000 },
{ title: 'notifyIcon', action: notifyIcon }
], function (notification) {
var btn = document.createElement('button');
btn.innerHTML = notification.title;
btn.onclick = function () {
notification.action(notification.value);
};
document.querySelector('#ephox-ui').appendChild(btn);
});
EditorManager.init({
selector: 'textarea.tinymce',
skin_url: '../../../../../skins/lightgray/dist/lightgray',
codesample_content_css: '../../../../../plugins/codesample/dist/codesample/css/prism.css'
});
EditorManager.init({
selector: 'div.tinymce',
inline: true,
skin_url: '../../../../../skins/lightgray/dist/lightgray',
codesample_content_css: '../../../../../plugins/codesample/dist/codesample/css/prism.css'
});
return function () {
};
}
);
| {
"content_hash": "f934996b35309e9e5bbc35b7158a7926",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 95,
"avg_line_length": 29.868852459016395,
"alnum_prop": 0.6029088913282108,
"repo_name": "wael-Fadlallah/overflow",
"id": "91719146e766c79dc1b4e789bc21aa1854209c8d",
"size": "3867",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "asset/tinymce/src/themes/modern/src/demo/js/demo/NotificationDemo.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "154260"
},
{
"name": "HTML",
"bytes": "8541750"
},
{
"name": "JavaScript",
"bytes": "9129178"
},
{
"name": "PHP",
"bytes": "1842793"
}
],
"symlink_target": ""
} |
if is_osx; then
export MAKEFLAGS=-j1
export CFLAGS=-I$MP_PREFIX/include/
export LIBS=$MP_PREFIX/lib/libiconv.a
export LDFLAGS="-L${HB_PREFIX}/opt/openssl/lib"
export CPPFLAGS=-I${HB_PREFIX}/opt/openssl/include
export PKG_CONFIG_PATH=${HB_PREFIX}/opt/openssl/lib/pkgconfig
fi
### Download and compile source...
[ ! -d $DOTFILES/build ] && mkdir -p $DOTFILES/build
cd $DOTFILES/build
[ -d nmh ] || git clone git://git.savannah.nongnu.org/nmh.git
cd nmh &&
git pull &&
./autogen.sh &&
./configure --prefix=/usr/local --with-tls --with-mts=smtp &&
make &&
make install
#git clone [email protected]:nicm/fdm.git &&
# cd fdm &&
# ./autogen.sh &&
# ./configure --prefix=/usr/local &&
# make &&
# make install
| {
"content_hash": "dd634d3efd1c302aac506cab303b7199",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 65,
"avg_line_length": 27.214285714285715,
"alnum_prop": 0.6351706036745407,
"repo_name": "viklund/dotfiles",
"id": "06b44bbbd774a5a5802dea96cb4fa52e0bdff015",
"size": "783",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "init/81_nmh.sh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Perl",
"bytes": "59575"
},
{
"name": "Python",
"bytes": "7447"
},
{
"name": "Shell",
"bytes": "63096"
},
{
"name": "Vim script",
"bytes": "95626"
}
],
"symlink_target": ""
} |
class ArtefactsController < ApplicationController
before_filter :find_artefact, :except => %i(index new)
helper_method :sort_column, :sort_direction
respond_to :html
ITEMS_PER_PAGE = 100
def index
@filters = params.slice(:kind, :state, :search, :owned_by)
scope = artefact_scope.without(:actions)
scope = FilteredScope.new(scope, @filters).scope
scope = scope.order_by([[sort_column, sort_direction]])
@artefacts = scope.page(params[:page]).per(ITEMS_PER_PAGE)
respond_with @artefacts
end
def show
respond_with @artefact do |format|
format.html { redirect_to admin_url_for_edition(@artefact) }
end
end
def history
@actions = build_actions
end
def withdraw
@publisher_edition_url = publisher_edition_url(@artefact)
if @artefact.archived? || @artefact.owning_app != OwningApp::PUBLISHER
redirect_to root_path
end
end
def new
@artefact = Artefact.new
redirect_to_show_if_need_met
end
def edit
end
# it is only possible to change the Maslow Need IDs for a given artefact
def update
saved = @artefact.update_attributes_as(current_user, need_ids)
if saved
flash[:success] = 'Panopticon item updated'
else
flash[:danger] = 'Failed to save item'
end
if saved && continue_editing?
redirect_to edit_artefact_path(@artefact)
elsif saved
redirect_to artefact_path(@artefact)
else
@actions = build_actions
render :edit
end
end
private
def continue_editing?
params[:commit] == 'Save and continue editing' ||
@artefact.owning_app != OwningApp::PUBLISHER
end
def publisher_edition_url(artefact)
edition = Edition.where(panopticon_id: artefact.id).order_by(version_number: :desc).first
if edition
Plek.find('publisher') + "/editions/#{edition.id}/unpublish"
else
admin_url_for_edition(artefact)
end
end
def admin_url_for_edition(artefact, options = {})
[
"#{Plek.current.find(artefact.owning_app)}/admin/publications/#{artefact.id}",
options.to_query
].reject(&:blank?).join("?")
end
def artefact_scope
# This is here so that we can stub this out a bit more easily in the
# functional tests.
Artefact
end
def redirect_to_show_if_need_met
if params[:artefact] && params[:artefact][:need_id]
artefact = Artefact.any_in(need_ids: [params[:artefact][:need_id]]).first
redirect_to artefact if artefact
end
end
def find_artefact
@artefact = Artefact.from_param(params[:id])
end
def need_ids
need_ids = params.require(:artefact)
.fetch(:need_ids, "")
.split(",")
.map(&:strip)
.reject(&:blank?)
{ need_ids: need_ids }
end
def build_actions
# Construct a list of actions, with embedded diffs
# The reason for appending the nil is so that the initial action is
# included: the DiffEnabledAction class handles the case where the
# previous action does not exist
reverse_actions = @artefact.actions.reverse
(reverse_actions + [nil]).each_cons(2).map { |action, previous|
DiffEnabledAction.new(action, previous)
}
end
def sort_column
Artefact.fields.keys.include?(params[:sort]) ? params[:sort] : :name
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : :asc
end
end
| {
"content_hash": "76cf9a376f3475f7356941e18d552c1d",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 93,
"avg_line_length": 25.066666666666666,
"alnum_prop": 0.6631205673758865,
"repo_name": "alphagov/panopticon",
"id": "91fe689cb172cc137ac352c0291b58938c66dbe7",
"size": "3384",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/artefacts_controller.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4055"
},
{
"name": "Gherkin",
"bytes": "287"
},
{
"name": "HTML",
"bytes": "11677"
},
{
"name": "JavaScript",
"bytes": "3307"
},
{
"name": "Ruby",
"bytes": "154774"
},
{
"name": "Shell",
"bytes": "56"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.