Dataset Preview
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed
Error code: DatasetGenerationError
Exception: ArrowInvalid
Message: JSON parse error: Missing a closing quotation mark in string. in row 1215
Traceback: Traceback (most recent call last):
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 145, in _generate_tables
dataset = json.load(f)
File "/usr/local/lib/python3.9/json/__init__.py", line 293, in load
return loads(fp.read(),
File "/usr/local/lib/python3.9/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "/usr/local/lib/python3.9/json/decoder.py", line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 4488)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1995, in _prepare_split_single
for _, table in generator:
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 148, in _generate_tables
raise e
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 122, in _generate_tables
pa_table = paj.read_json(
File "pyarrow/_json.pyx", line 308, in pyarrow._json.read_json
File "pyarrow/error.pxi", line 154, in pyarrow.lib.pyarrow_internal_check_status
File "pyarrow/error.pxi", line 91, in pyarrow.lib.check_status
pyarrow.lib.ArrowInvalid: JSON parse error: Missing a closing quotation mark in string. in row 1215
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1529, in compute_config_parquet_and_info_response
parquet_operations = convert_to_parquet(builder)
File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1154, in convert_to_parquet
builder.download_and_prepare(
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1027, in download_and_prepare
self._download_and_prepare(
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1122, in _download_and_prepare
self._prepare_split(split_generator, **prepare_split_kwargs)
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1882, in _prepare_split
for job_id, done, content in self._prepare_split_single(
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2038, in _prepare_split_single
raise DatasetGenerationError("An error occurred while generating the dataset") from e
datasets.exceptions.DatasetGenerationError: An error occurred while generating the datasetNeed help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.
text
string | meta
dict |
|---|---|
package uk.gov.hmrc.play.audit.http.connector
import play.api.Logger
import play.api.libs.json.{JsValue, Json}
import uk.gov.hmrc.play.audit.http.config.AuditingConfig
import uk.gov.hmrc.play.audit.model.{AuditEvent, MergedDataEvent}
import uk.gov.hmrc.play.connectors.Connector
import uk.gov.hmrc.play.http.{HeaderCarrier, HttpResponse}
import uk.gov.hmrc.play.http.logging.{ConnectionTracing, LoggingDetails}
import uk.gov.hmrc.play.http.logging.MdcLoggingExecutionContext._
import uk.gov.hmrc.play.http.ws.WSHttpResponse
import scala.concurrent.{ExecutionContext, Future}
trait AuditEventFailureKeys {
private val EventMissed = "DS_EventMissed"
val LoggingAuditRequestFailureKey : String = EventMissed + "_AuditFailureResponse"
val LoggingAuditFailureResponseKey : String = EventMissed + "_AuditRequestFailure"
}
object AuditEventFailureKeys extends AuditEventFailureKeys
sealed trait AuditResult
object AuditResult {
case object Success extends AuditResult
case object Disabled extends AuditResult
case class Failure(msg: String, nested: Option[Throwable] = None) extends Exception(msg, nested.orNull) with AuditResult
}
trait AuditConnector extends Connector with AuditEventFailureKeys with ConnectionTracing {
def auditingConfig: AuditingConfig
protected def callAuditConsumer(url:String , body: JsValue)(implicit hc: HeaderCarrier, ec : ExecutionContext): Future[HttpResponse] =
withTracing("Post", url) {
buildRequest(url).post(body).map(new WSHttpResponse(_))(ec)
}
protected def logError(s: String) = Logger.warn(s)
protected def logError(s: String, t: Throwable) = Logger.warn(s, t)
def sendEvent(event: AuditEvent)(implicit hc: HeaderCarrier = HeaderCarrier(), ec : ExecutionContext): Future[AuditResult] =
sendEvent(auditingConfig.consumer.map(_.singleEventUrl), Json.toJson(event))
def sendMergedEvent(event: MergedDataEvent)(implicit hc: HeaderCarrier = HeaderCarrier(), ec : ExecutionContext): Future[AuditResult] =
sendEvent(auditingConfig.consumer.map(_.mergedEventUrl), Json.toJson(event))
def sendLargeMergedEvent(event: MergedDataEvent)(implicit hc: HeaderCarrier = HeaderCarrier()): Future[AuditResult] =
sendEvent(auditingConfig.consumer.map(_.largeMergedEventUrl), Json.toJson(event))
private def sendEvent(urlOption: Option[String], body: JsValue)(implicit hc: HeaderCarrier) = {
if (auditingConfig.enabled) {
val url = urlOption.getOrElse( throw new Exception("Missing event consumer URL") )
handleResult(callAuditConsumer(url, body), body).map { _ => AuditResult.Success }
} else {
Logger.info(s"auditing disabled for request-id ${hc.requestId}, session-id: ${hc.sessionId}")
Future.successful(AuditResult.Disabled)
}
}
protected[connector] def handleResult(resultF: Future[HttpResponse], body: JsValue)(implicit ld: LoggingDetails): Future[HttpResponse] = {
resultF
.recoverWith { case t =>
val message = makeFailureMessage(body)
logError(message, t)
Future.failed(AuditResult.Failure(message, Some(t)))
}
.map { response =>
checkResponse(body, response) match {
case Some(error) =>
logError(error)
throw AuditResult.Failure(error)
case None => response
}
}
}
private[connector] def makeFailureMessage(body: JsValue): String = s"$LoggingAuditRequestFailureKey : audit item : $body"
private[connector] def checkResponse(body: JsValue, response: HttpResponse): Option[String] = {
if (response.status >= 300) Some(s"$LoggingAuditFailureResponseKey : status code : ${response.status} : audit item : $body")
else None
}
}
object AuditConnector {
def apply(config: AuditingConfig) = new AuditConnector { def auditingConfig = config }
}
|
{
"content_hash": "e37f324fc21515a7727862b2484c1a37",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 140,
"avg_line_length": 42.233333333333334,
"alnum_prop": 0.7437516443041305,
"repo_name": "beyond-code-github/play-auditing",
"id": "6eb98158e8aa0776321067fa3171bb2edeb8a584",
"size": "4404",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/scala/uk/gov/hmrc/play/audit/http/connector/AuditConnector.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "112228"
}
]
}
|
package lu.gab.com.alertapet;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("lu.gab.com.alertapet", appContext.getPackageName());
}
}
|
{
"content_hash": "8002254d0cacce49c30c6517228cfea0",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 78,
"avg_line_length": 28.615384615384617,
"alnum_prop": 0.7446236559139785,
"repo_name": "luanacereja/alertaPet",
"id": "a4f9d322e1ec60d37ccd1d303cff05b337284cf0",
"size": "744",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/androidTest/java/lu/gab/com/alertapet/ExampleInstrumentedTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": []
}
|
'use strict';
let harvesterPort = process.env.HARVESTER_PORT || 8000;
module.exports = {
baseUrl: 'http://localhost:' + harvesterPort,
harvester: {
port: harvesterPort,
options: {
adapter: 'mongodb',
connectionString: process.env.MONGODB_URL ||
'mongodb://127.0.0.1:27017/test',
db: process.env.MONGODB || 'test',
inflect: true,
oplogConnectionString: (process.env.OPLOG_MONGODB_URL ||
'mongodb://127.0.0.1:27017/local') + '?slaveOk=true',
},
},
};
|
{
"content_hash": "f3f0bc61b4bd38c0517dbcc21209bf2f",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 62,
"avg_line_length": 28.555555555555557,
"alnum_prop": 0.6167315175097277,
"repo_name": "agco/harvesterjs",
"id": "1aa8b8deb5834eb6467a68e5a3336589b2cdd5f2",
"size": "514",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "test/config.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "227663"
}
]
}
|
package com.webcohesion.ofx4j.domain.data.creditcard;
import com.webcohesion.ofx4j.domain.data.TransactionWrappedRequestMessage;
import com.webcohesion.ofx4j.meta.Aggregate;
import com.webcohesion.ofx4j.meta.ChildAggregate;
/**
* @author Ryan Heaton
*/
@Aggregate ("CCSTMTTRNRQ")
public class CreditCardStatementRequestTransaction extends TransactionWrappedRequestMessage<CreditCardStatementRequest> {
private CreditCardStatementRequest message;
/**
* The message.
*
* @return The message.
*/
@ChildAggregate( required = true, order = 30 )
public CreditCardStatementRequest getMessage() {
return message;
}
/**
* The message.
*
* @param message The message.
*
*/
public void setMessage(CreditCardStatementRequest message) {
this.message = message;
}
// Inherited.
public void setWrappedMessage(CreditCardStatementRequest message) {
setMessage(message);
}
}
|
{
"content_hash": "05cdc1d91d2c49ddc4f10d76f12b214d",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 121,
"avg_line_length": 22.609756097560975,
"alnum_prop": 0.7400215749730313,
"repo_name": "stoicflame/ofx4j",
"id": "d2ae95aa058613b6d65aacdd51566535ca201a65",
"size": "1520",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/webcohesion/ofx4j/domain/data/creditcard/CreditCardStatementRequestTransaction.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "979108"
}
]
}
|
package io.sarl.lang.ui.labeling;
import java.lang.reflect.Method;
import javax.inject.Singleton;
import com.google.inject.Inject;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.Diagnostician;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.BaseLabelProvider;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.xtend.core.xtend.XtendMember;
import org.eclipse.xtext.diagnostics.AbstractDiagnostic;
import org.eclipse.xtext.nodemodel.ICompositeNode;
import org.eclipse.xtext.nodemodel.INode;
import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
import org.eclipse.xtext.ui.IImageHelper;
import org.eclipse.xtext.ui.IImageHelper.IImageDescriptorHelper;
/**
* A decorator that add the diagnotic results on Ecore elements.
*
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
*/
@Singleton
public class SARLDiagnosticLabelDecorator extends BaseLabelProvider implements ILabelDecorator {
private static final Method GET_NODE_METHOD;
static {
try {
GET_NODE_METHOD = AbstractDiagnostic.class.getDeclaredMethod("getNode"); //$NON-NLS-1$
GET_NODE_METHOD.setAccessible(true);
} catch (Exception e) {
throw new Error(e);
}
}
@Inject
private IImageHelper imageHelper;
@Inject
private IImageDescriptorHelper imageDescriptorHelper;
private static boolean inside(INode node, ICompositeNode parentCandidate) {
INode current = node;
while (current != null) {
if (current.equals(parentCandidate)) {
return true;
}
current = current.getParent();
}
return false;
}
/** Replies the image that corresponds to the given object.
*
* @param imageDescription
* a {@link String}, an {@link ImageDescriptor} or an {@link Image}
* @return the {@link Image} associated with the description or <code>null</code>
*/
protected Image convertToImage(Object imageDescription) {
if (imageDescription instanceof Image) {
return (Image) imageDescription;
} else if (imageDescription instanceof ImageDescriptor) {
return this.imageHelper.getImage((ImageDescriptor) imageDescription);
} else if (imageDescription instanceof String) {
return this.imageHelper.getImage((String) imageDescription);
}
return null;
}
private static boolean hasParserIssue(ICompositeNode node, Iterable<Resource.Diagnostic> issues) {
for (final Resource.Diagnostic resourceDiagnostic : issues) {
if (resourceDiagnostic instanceof AbstractDiagnostic) {
final AbstractDiagnostic diag = (AbstractDiagnostic) resourceDiagnostic;
final INode diagNode;
try {
diagNode = (INode) GET_NODE_METHOD.invoke(diag);
} catch (Exception e) {
throw new Error(e);
}
if (inside(diagNode, node)) {
return true;
}
}
}
return false;
}
/** Replies the diagnotic adornment for the given element.
*
* @param element the model element.
* @return the adornment.
*/
@SuppressWarnings("static-method")
protected int getIssueAdornment(XtendMember element) {
final ICompositeNode node = NodeModelUtils.getNode(element);
if (node == null) {
return 0;
}
// Error markers are more important than warning markers.
// Order of checks:
// - parser error (from the resource) or semantic error (from Diagnostician)
// - parser warning or semantic warning
final Resource resource = element.eResource();
if (hasParserIssue(node, resource.getErrors())) {
return JavaElementImageDescriptor.ERROR;
}
final Diagnostic diagnostic = Diagnostician.INSTANCE.validate(element);
switch (diagnostic.getSeverity()) {
case Diagnostic.ERROR:
return JavaElementImageDescriptor.ERROR;
case Diagnostic.WARNING:
return JavaElementImageDescriptor.WARNING;
default:
}
if (hasParserIssue(node, resource.getWarnings())) {
return JavaElementImageDescriptor.WARNING;
}
return 0;
}
/**Replies the size of the images.
*
* @return {@link JavaElementImageProvider#SMALL_SIZE} or {@link JavaElementImageProvider#BIG_SIZE}
*/
@SuppressWarnings("static-method")
protected Point imagesSize() {
return JavaElementImageProvider.BIG_SIZE;
}
@Override
public Image decorateImage(Image image, Object element) {
if (element instanceof XtendMember) {
final int adornment = getIssueAdornment((XtendMember) element);
if (adornment != 0) {
final ImageDescriptor descriptor = this.imageDescriptorHelper.getImageDescriptor(image);
final ImageDescriptor newDescriptor = new JavaElementImageDescriptor(descriptor, adornment, imagesSize());
return convertToImage(newDescriptor);
}
}
return image;
}
@Override
public String decorateText(String text, Object element) {
return text;
}
}
|
{
"content_hash": "face2550618392c5b84395f933b9b141",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 110,
"avg_line_length": 31.28395061728395,
"alnum_prop": 0.7452644041041832,
"repo_name": "jgfoster/sarl",
"id": "86ab965958c32468e7c34aa4a49baa1514669cd3",
"size": "5803",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/labeling/SARLDiagnosticLabelDecorator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "178"
},
{
"name": "GAP",
"bytes": "1483810"
},
{
"name": "HTML",
"bytes": "287"
},
{
"name": "Java",
"bytes": "16931375"
},
{
"name": "JavaScript",
"bytes": "5968"
},
{
"name": "Shell",
"bytes": "7592"
},
{
"name": "TeX",
"bytes": "11189"
}
]
}
|
package org.onosproject.oxp.protocol.ver10;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.junit.Test;
import org.onosproject.oxp.protocol.*;
import org.onosproject.oxp.types.OXPVport;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.core.Is.is;
/**
* Created by cr on 16-7-22.
*/
public class OXPVportStatusMsgTest extends TestBaseVer10 {
@Test
public void OXPTopologyReplyMsgTest() throws Exception{
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
OXPVport vport = OXPVport.ofShort((short) 1);
Set<OXPVportState> state = new HashSet<>();
state.add(OXPVportState.LIVE);
OXPVportDesc vportDesc = new OXPVportDescVer10.Builder().setPortNo(vport)
.setState(state)
.build();
OXPVportStatus vportStatus = getMsgFactory()
.buildVportStatus()
.setReason(OXPVportReason.MODIFY)
.setVportDesc(vportDesc)
.build();
vportStatus.writeTo(buffer);
assertThat(vportStatus, instanceOf(OXPVportStatusVer10.class));
OXPMessage message = getMsgReader().readFrom(buffer);
assertThat(message, instanceOf(vportStatus.getClass()));
OXPVportStatus messageRev = (OXPVportStatus) vportStatus;
assertThat(vportStatus, is(messageRev));
}
}
|
{
"content_hash": "f135e9e8ddf47d619202ff8c78f9b6b3",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 81,
"avg_line_length": 35.2093023255814,
"alnum_prop": 0.6948480845442536,
"repo_name": "paradisecr/ONOS-OXP",
"id": "7b68e99078561971fa5360d5b28d4ad238e20bdd",
"size": "1514",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "apps/oxp/protocol/src/test/java/org/onosproject/oxp/protocol/ver10/OXPVportStatusMsgTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": []
}
|
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
{
"content_hash": "cedc9a5d3bed323a59ce6bf8aec80092",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "c7fa08948ed6228906b1b057db65561c9e710a8f",
"size": "183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Alismatales/Araceae/Anthurium/Anthurium loretense/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": []
}
|
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
{
"content_hash": "d31ffc2e42464e6e4c4f3f6163ee2480",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "aadeb317ea1c7cc9b63f80ef7d9533b947b48fe4",
"size": "184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Picris/Picris cupuligera/ Syn. Spitzelia cupuligera/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": []
}
|
package uk.co.seanotoole.qwery.clauses.ansi;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import uk.co.seanotoole.qwery.clauses.Statement;
import uk.co.seanotoole.qwery.clauses.sql.Select;
public class AnsiSqlFactoryTest {
private final AnsiSqlFactory factory = new AnsiSqlFactory();
@Test
public void createsAnsiSelect() {
Select select = factory.select(new Statement.Builder(), "column1");
assertThat(select).isInstanceOf(AnsiSelect.class);
}
}
|
{
"content_hash": "f18c9922039f25a3456e8309968b9f4b",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 71,
"avg_line_length": 26.57894736842105,
"alnum_prop": 0.7722772277227723,
"repo_name": "SeanOToole/Qwery",
"id": "c6ec5420f714e8d584ac1adde7e4d7827478c4e8",
"size": "505",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/uk/co/seanotoole/qwery/clauses/ansi/AnsiSqlFactoryTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "110087"
}
]
}
|
import json
import shutil
from pathlib import Path
import pytest
from eodatasets3 import serialise
from eodatasets3.scripts import tostac
from tests.common import run_prepare_cli, assert_same
TO_STAC_DATA: Path = Path(__file__).parent.joinpath("data/tostac")
ODC_METADATA_FILE: str = "ga_ls8c_ard_3-1-0_088080_2020-05-25_final.odc-metadata.yaml"
STAC_TEMPLATE_FILE: str = "ga_ls_ard_3_stac_item.json"
STAC_EXPECTED_FILE: str = (
"ga_ls8c_ard_3-1-0_088080_2020-05-25_final.stac-item_expected.json"
)
def test_tostac(input_doc_folder: Path):
input_metadata_path = input_doc_folder.joinpath(ODC_METADATA_FILE)
assert input_metadata_path.exists()
run_tostac(input_metadata_path)
name = input_metadata_path.stem.replace(".odc-metadata", "")
actual_stac_path = input_metadata_path.with_name(f"{name}.stac-item.json")
assert actual_stac_path.exists()
expected_stac_path = input_doc_folder.joinpath(STAC_EXPECTED_FILE)
assert expected_stac_path.exists()
actual_doc = json.load(actual_stac_path.open())
expected_doc = json.load(expected_stac_path.open())
assert_same(expected_doc, actual_doc)
def test_add_property(input_doc_folder: Path):
input_metadata_path = input_doc_folder.joinpath(ODC_METADATA_FILE)
assert input_metadata_path.exists()
input_doc = serialise.load_yaml(input_metadata_path)
input_doc["properties"]["test"] = "testvalue"
serialise.dump_yaml(input_metadata_path, input_doc)
assert input_metadata_path.exists()
run_tostac(input_metadata_path)
name = input_metadata_path.stem.replace(".odc-metadata", "")
actual_stac_path = input_metadata_path.with_name(f"{name}.stac-item.json")
assert actual_stac_path.exists()
actual_doc = json.load(actual_stac_path.open())
assert actual_doc["properties"]["test"] == input_doc["properties"]["test"]
def test_invalid_crs(input_doc_folder: Path):
input_metadata_path = input_doc_folder.joinpath(ODC_METADATA_FILE)
assert input_metadata_path.exists()
input_doc = serialise.load_yaml(input_metadata_path)
del input_doc["crs"]
serialise.dump_yaml(input_metadata_path, input_doc)
assert input_metadata_path.exists()
with pytest.raises(RuntimeError) as exp:
run_tostac(input_metadata_path)
assert (
str(exp.value) == "Expect string or any object with "
"`.to_epsg()` or `.to_wkt()` method"
)
def run_tostac(input_metadata_path: Path):
run_prepare_cli(
tostac.run,
"-u",
"http://dea-public-data-dev.s3-ap-southeast-2.amazonaws.com/"
"analysis-ready-data/ga_ls8c_ard_3/088/080/2020/05/25/",
"-e",
"https://explorer.dev.dea.ga.gov.au/",
"--validate",
input_metadata_path,
)
@pytest.fixture
def input_doc_folder(tmp_path: Path) -> Path:
tmp_input_path = tmp_path / TO_STAC_DATA.name
if TO_STAC_DATA.is_file():
shutil.copy(TO_STAC_DATA, tmp_input_path)
else:
shutil.copytree(TO_STAC_DATA, tmp_input_path)
return tmp_input_path
|
{
"content_hash": "a2e9d3da5b3a56df8f43778c689ec252",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 86,
"avg_line_length": 32.3936170212766,
"alnum_prop": 0.683415435139573,
"repo_name": "GeoscienceAustralia/eo-datasets",
"id": "f11a0eb64622cbdf253357dca5dc0271c46afb8d",
"size": "3045",
"binary": false,
"copies": "1",
"ref": "refs/heads/eodatasets3",
"path": "tests/integration/test_tostac.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "501206"
},
{
"name": "Shell",
"bytes": "244"
}
]
}
|
/* eslint max-params: [2, 11] */
define([
'underscore',
'shared/views/BaseView',
'shared/util/TemplateUtil',
'./AppDescriptionView',
'./tab/ModalTabs',
'./MappingsViewContent',
'shared/models/ud/ProfileAppInstance',
'shared/models/ud/AppUserProfile',
'shared/models/ud/OktaUserProfile',
'shared/models/ud/ProfilesMapping'
], function (_, BaseView, TemplateUtil, AppDescriptionView, ModalTabs, MappingsViewContent,
ProfileAppInstance, AppUserProfile, OktaUserProfile, ProfilesMapping) {
return BaseView.extend({
className: 'attributes-mapping-modal-content',
initialize: function () {
_.bindAll(this, '_setAppProfile', '_setOktaProfile');
this._updateMappingDirection();
this.appModel = new ProfileAppInstance.Model();
this._initModel();
this.listenTo(this.state, 'change:tabId', function () {
this._updateMappingDirection();
});
},
_updateMappingDirection: function () {
/* eslint max-statements: [2, 20] */
var source,
sourceId = this.model.get('sourceId'),
targetId = this.model.get('targetId');
if (sourceId && targetId && this.sourceTarget) {
// from changing tab, swap source and target
source = this.source;
this.source = this.target;
this.target = source;
/**
* set both sourceId and targetId will trigger retrieve fetch mapping.
* silence one to avoid duplicated fetching.
* @see this._initModel
*/
this.model.set({sourceId: targetId}, {silent: true});
this.model.set({targetId: sourceId});
var appRole = this.sourceTarget.app;
this.sourceTarget = {app: this.sourceTarget.okta, okta: appRole};
} else {
// from initialize
// initialize source and target value base on the mapping direction
source = 'appProfile';
var target = 'oktaProfile',
sourceName = 'sourceId',
targetName = 'targetId';
if (this.state.get('tabId') === 'oktaToApp') {
// should not run into this case, unless we decided to swap the mapping direction (tabs)
var tempSource = source,
tempSourceName = sourceName;
source = target;
target = tempSource;
sourceName = targetName;
targetName = tempSourceName;
}
this.source = source;
this.target = target;
this.sourceTarget = {app: sourceName, okta: targetName};
}
},
/**
* Notes to main data flow:
*
* 1. appProfile.fetch + oktaProfile.fetch
* 2. set sourceId and targetId,
* 3. trigger `this.model.change` event
* 4. invoke this._retrieveMapping
* 5. trigger `this.model.reset` event
* 6. invoke the reset handler (line 98)
* 7. invoke this._addContentView
*
*/
_initModel: function () {
this.sourceTargetData = {};
this.sourceTargetData.appProfile = new AppUserProfile.Model({id: 'default'}, {
instanceId: this.state.get('appInstanceId'),
expand: ['schema', 'app', 'appLogo']
});
this.sourceTargetData.appProfile.fetch().then(this._setAppProfile);
this.sourceTargetData.oktaProfile = new OktaUserProfile.Model({id: 'default'}, {expand: ['schema']});
this.sourceTargetData.oktaProfile.fetch().then(this._setOktaProfile);
this.listenTo(this.model, 'change:sourceId change:targetId', this._retrieveMapping);
this.listenTo(this.model, 'reset', function () {
this._updatePreviewModel();
this._addAppDescriptionView();
this._addTabs();
this._addContentView();
});
},
_setAppProfile: function (appProfile) {
this.model.set(this.sourceTarget.app, appProfile.id);
this.appModel.set(
_.extend({}, appProfile['_embedded'].app, {logoHref: appProfile['_embedded'].appLogo.href})
);
},
_setOktaProfile: function (oktaProfile) {
this.model.set(this.sourceTarget.okta, oktaProfile.id);
},
_retrieveMapping: function () {
if (this.model.get('sourceId') && this.model.get('targetId') &&
(this.model.get('sourceId') !== this.model.get('targetId'))
) {
var self = this;
this.model
.fetch({
reset: true,
data: {source: this.model.get('sourceId'), target: this.model.get('targetId')}
})
.fail(function () {
self.model.set('propertyMappings', new ProfilesMapping.ProfileMappingCollection());
})
.always(function () {
self.model.trigger('reset');
});
}
},
_addAppDescriptionView: function () {
this.appDescriptionView && this.appDescriptionView.remove();
this.appDescriptionView = new AppDescriptionView({
state: this.state,
appModel: this.appModel
});
this.add(this.appDescriptionView);
},
_addTabs: function () {
this.tabs && this.tabs.remove();
var toOktaTemplate = TemplateUtil.tpl('{{appInstanceName}} to Okta'),
fromOktaTemplate = TemplateUtil.tpl('Okta to {{appInstanceName}}'),
appLabel = this.appModel.get('label');
var tabs = [
{ id: 'appToOkta',
disp: toOktaTemplate({appInstanceName: appLabel}),
link: '',
selected: this.state.get('tabId') === 'appToOkta'
},
{ id: 'oktaToApp',
disp: fromOktaTemplate({appInstanceName: appLabel}),
link: '',
selected: this.state.get('tabId') === 'oktaToApp'
}
];
var showOnlyTabId = this.options.showOnlyTabId;
if (showOnlyTabId) {
var showOnlyTabIndex = _.findIndex(tabs, function (tab) {
return tab.id === showOnlyTabId;
});
if (showOnlyTabIndex > -1) {
this.state.set({tabId: showOnlyTabId});
tabs = [tabs[showOnlyTabIndex]];
}
}
this.tabs = new ModalTabs({
state: this.state,
settings: this.settings,
tabs: tabs
});
this.add(this.tabs);
},
_addContentView: function () {
this._initMappingData();
this._processMappingData();
this.content && this.content.remove();
this.content = this.add(
MappingsViewContent,
{
options: {
systemPropertyMappings: this.systemPropertyMappings,
previewModel: this.options.previewModel,
collection: new ProfilesMapping.ProfileMappingCollection(this.mappingList),
sourceOptions: this.sourceOptions,
appModel: this.appModel
},
bubble: true
}
).last();
this.state.trigger('mappingsViewReady');
},
_initMappingData: function () {
var source = this.source,
target = this.target,
targetAttributes,
sourceAttributes;
this.mappingList = [];
this.sourceOptions = {};
if (this.sourceTargetData[source] && this.sourceTargetData[target]) {
// 1. get the original target and source lists
targetAttributes = this.sourceTargetData[target].get('properties');
sourceAttributes = this.sourceTargetData[source].get('properties');
// 2. map source attributes to target attributes
// put all the attributes from all the schemas to targetList
var self = this;
targetAttributes.each(function (targetAttribute) {
if (!targetAttribute.get('__isReadOnly__')) {
var name = targetAttribute.get('name');
self.mappingList.push({
'__targetAttribute__': targetAttribute.toJSON({verbose: true}),
'targetField': name,
'sourceExpression': ''
});
}
});
// 2.1 preserve SYSTEM mappings
this.systemPropertyMappings = this._getSystemPropertyMappings(targetAttributes);
// 3. compose source dropdown list
sourceAttributes.each(function (sourceAttribute) {
if (!sourceAttribute.get('__isWriteOnly__')) {
var newSourceAttr = {};
newSourceAttr[sourceAttribute.get('name')] = _.omit(sourceAttribute.toJSON({verbose: true}), 'name');
self.sourceOptions = _.extend(self.sourceOptions, newSourceAttr);
}
});
}
},
/*
* SYSTEM attributes may have mappings but those attributes will not be in the `targetAttributes` list
* since schema API only fetch attributes having scope NONE and SELF but not SYSTEM.
* fixed for OKTA-88195
*/
_getSystemPropertyMappings: function (targetAttributes) {
if (!targetAttributes) {
return [];
}
var allMappings = [];
if (this.model.get('propertyMappings') instanceof ProfilesMapping.ProfileMappingCollection) {
allMappings = this.model.get('propertyMappings').toJSON() || [];
}
var allTargetAttributes = targetAttributes.reduce(function (init, m) {
init[m.get('name')] = true;
return init;
}, {});
return _.reject(allMappings, function (mapping) {
return allTargetAttributes[mapping.targetField];
});
},
_processMappingData: function () {
// put existing mappings to the init mapping list
// example:
// init mapping: [{targetField: 'login', sourceExpression: ''}, {targetField: 'email', sourceExpression: ''}]
// existing mapping: [{targetField: 'email', sourceExpression: 'source.email'}]
// output mapping: [{targetField: 'login', sourceExpression: ''},
// {targetField: 'email', sourceExpression: 'source.email'}]
if (this.model.get('propertyMappings') instanceof ProfilesMapping.ProfileMappingCollection) {
var existingMappings = this.model.get('propertyMappings').toJSON({verbose: true}),
self = this;
_.each(existingMappings, function (existingMapping) {
var defaultMapping = _.find(self.mappingList, function (completeMapping) {
return completeMapping.targetField === existingMapping.targetField;
});
if (defaultMapping) {
defaultMapping.sourceExpression = existingMapping.sourceExpression;
defaultMapping.pushStatus = existingMapping.pushStatus;
}
});
}
},
_updatePreviewModel: function () {
this.options.previewModel.set({
sourceId: this.model.get('sourceId'),
targetId: this.model.get('targetId')
}).unset('userId').unset('propertyMappings');
}
});
});
|
{
"content_hash": "25d4b8b623ec635220fd647d4acc22ec",
"timestamp": "",
"source": "github",
"line_count": 303,
"max_line_length": 115,
"avg_line_length": 35.026402640264024,
"alnum_prop": 0.6025628945632715,
"repo_name": "alanzhou-okta/okta-signin-widget",
"id": "7542231aabdf9cb692ff9029e50a3c9ba2d2f117",
"size": "10613",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/@okta/courage/src/views/ud/mappings/MappingsView.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "173037"
},
{
"name": "JavaScript",
"bytes": "960169"
},
{
"name": "Ruby",
"bytes": "1057"
},
{
"name": "Shell",
"bytes": "2823"
},
{
"name": "Smarty",
"bytes": "5124"
}
]
}
|
#include "battery.h"
#include "charge_state.h"
#include "charger.h"
#include "chipset.h"
#include "common.h"
#include "console.h"
#include "extpower.h"
#include "gpio.h"
#include "hooks.h"
#include "host_command.h"
#include "printf.h"
#include "sb_fw_update.h"
#include "system.h"
#include "task.h"
#include "timer.h"
#include "util.h"
/* Console output macros */
#define CPUTS(outstr) cputs(CC_CHARGER, outstr)
#define CPRINTS(format, args...) cprints(CC_CHARGER, format, ## args)
/* Voltage debounce time */
#define DEBOUNCE_TIME (10 * SECOND)
#define LOW_BATTERY_SHUTDOWN_TIMEOUT_US \
(CONFIG_BATTERY_CRITICAL_SHUTDOWN_TIMEOUT * SECOND)
#ifndef BATTERY_AP_OFF_LEVEL
#define BATTERY_AP_OFF_LEVEL 0
#endif
static const char * const state_name[] = CHARGE_STATE_NAME_TABLE;
static int state_machine_force_idle;
static unsigned user_current_limit = -1U;
static int fake_state_of_charge = -1;
/* Current power state context */
static struct charge_state_context task_ctx;
static inline int is_charger_expired(
struct charge_state_context *ctx, timestamp_t now)
{
return now.val - ctx->charger_update_time.val > CHARGER_UPDATE_PERIOD;
}
static inline void update_charger_time(
struct charge_state_context *ctx, timestamp_t now)
{
ctx->charger_update_time.val = now.val;
}
/**
* Update memory-mapped battery information, used by ACPI _BIF and/or _BIX.
*/
static void update_battery_info(void)
{
char *batt_str;
int batt_serial;
/* Design Capacity of Full */
battery_design_capacity((int *)host_get_memmap(EC_MEMMAP_BATT_DCAP));
/* Design Voltage */
battery_design_voltage((int *)host_get_memmap(EC_MEMMAP_BATT_DVLT));
/* Last Full Charge Capacity */
battery_full_charge_capacity(
(int *)host_get_memmap(EC_MEMMAP_BATT_LFCC));
/* Cycle Count */
battery_cycle_count((int *)host_get_memmap(EC_MEMMAP_BATT_CCNT));
/* Battery Manufacturer string */
batt_str = (char *)host_get_memmap(EC_MEMMAP_BATT_MFGR);
memset(batt_str, 0, EC_MEMMAP_TEXT_MAX);
battery_manufacturer_name(batt_str, EC_MEMMAP_TEXT_MAX);
/* Battery Model string */
batt_str = (char *)host_get_memmap(EC_MEMMAP_BATT_MODEL);
memset(batt_str, 0, EC_MEMMAP_TEXT_MAX);
battery_device_name(batt_str, EC_MEMMAP_TEXT_MAX);
/* Battery Type string */
batt_str = (char *)host_get_memmap(EC_MEMMAP_BATT_TYPE);
battery_device_chemistry(batt_str, EC_MEMMAP_TEXT_MAX);
/* Smart battery serial number is 16 bits */
batt_str = (char *)host_get_memmap(EC_MEMMAP_BATT_SERIAL);
memset(batt_str, 0, EC_MEMMAP_TEXT_MAX);
if (battery_serial_number(&batt_serial) == 0)
snprintf(batt_str, EC_MEMMAP_TEXT_MAX, "%04X", batt_serial);
/* Battery data is now present */
*host_get_memmap(EC_MEMMAP_BATTERY_VERSION) = 1;
}
/**
* Prevent battery from going into deep discharge state
*/
static void low_battery_shutdown(struct charge_state_context *ctx)
{
if (chipset_in_state(CHIPSET_STATE_ANY_OFF)) {
/* AP is off, so shut down the EC now */
CPRINTS("charge force EC hibernate due to low battery");
system_hibernate(0, 0);
} else if (!ctx->shutdown_warning_time.val) {
/* Warn AP battery level is so low we'll shut down */
CPRINTS("charge warn shutdown due to low battery");
ctx->shutdown_warning_time = get_time();
host_set_single_event(EC_HOST_EVENT_BATTERY_SHUTDOWN);
} else if (get_time().val > ctx->shutdown_warning_time.val +
LOW_BATTERY_SHUTDOWN_TIMEOUT_US) {
/* Timeout waiting for AP to shut down, so kill it */
CPRINTS("charge force shutdown due to low battery");
chipset_force_shutdown();
}
}
int charge_keep_power_off(void)
{
int charge;
if (BATTERY_AP_OFF_LEVEL == 0)
return 0;
if (battery_remaining_capacity(&charge))
return charge_get_state() != PWR_STATE_ERROR;
return charge <= BATTERY_AP_OFF_LEVEL;
}
#ifdef CONFIG_CHARGER_EN_GPIO
#ifdef CONFIG_CHARGER_EN_ACTIVE_LOW
static void charge_set_charger_en_gpio(int level)
{
gpio_set_level(GPIO_CHARGER_EN_L, !level);
}
static int charge_get_charger_en_gpio(void)
{
return !gpio_get_level(GPIO_CHARGER_EN_L);
}
#else
static void charge_set_charger_en_gpio(int level)
{
gpio_set_level(GPIO_CHARGER_EN, level);
}
static int charge_get_charger_en_gpio(void)
{
return gpio_get_level(GPIO_CHARGER_EN);
}
#endif
#endif
/**
* Enable or disable charging, and set requested voltage and current. If either
* of voltage and current is set to 0, charging is disable.
*
* @param voltage Requested voltage in mV. Set -1 to preserve current value.
* @param current Requested current in mA. Set -1 to preserve current value.
*/
static int charge_request(int voltage, int current)
{
int rv = EC_SUCCESS;
if (voltage == -1 && current == -1)
return EC_SUCCESS;
#ifdef CONFIG_CHARGER_EN_GPIO
if (voltage == 0 || current == 0) {
charge_set_charger_en_gpio(0);
return EC_SUCCESS;
} else {
charge_set_charger_en_gpio(1);
}
#endif
if (voltage != -1)
rv |= charger_set_voltage(voltage);
if (current != -1)
rv |= charger_set_current(current);
return rv;
}
/**
* Common handler for charging states.
*
* This handler gets battery charging parameters, charger state, ac state, and
* timestamp. It also fills memory map and issues power events on state change.
*/
static int state_common(struct charge_state_context *ctx)
{
int rv, d;
struct charge_state_data *curr = &ctx->curr;
struct charge_state_data *prev = &ctx->prev;
struct batt_params *batt = &ctx->curr.batt;
uint8_t *batt_flags = ctx->memmap_batt_flags;
/* Copy previous state and init new state */
ctx->prev = ctx->curr;
curr->ts = get_time();
curr->error = 0;
/* Detect AC change */
curr->ac = charge_get_flags() & CHARGE_FLAG_EXTERNAL_POWER;
if (curr->ac != prev->ac) {
if (curr->ac) {
/* AC on
* Initialize charger to power on reset mode
*/
rv = charger_post_init();
if (rv)
curr->error |= F_CHARGER_INIT;
}
}
if (curr->ac) {
*batt_flags |= EC_BATT_FLAG_AC_PRESENT;
if (charger_get_voltage(&curr->charging_voltage)) {
charge_request(0, 0);
curr->error |= F_CHARGER_VOLTAGE;
}
if (charger_get_current(&curr->charging_current)) {
charge_request(0, 0);
curr->error |= F_CHARGER_CURRENT;
}
#ifdef CONFIG_CHARGER_EN_GPIO
if (!charge_get_charger_en_gpio()) {
curr->charging_voltage = 0;
curr->charging_current = 0;
}
#endif
} else {
*batt_flags &= ~EC_BATT_FLAG_AC_PRESENT;
/* AC disconnected should get us out of force idle mode. */
state_machine_force_idle = 0;
}
#if defined(CONFIG_BATTERY_PRESENT_CUSTOM) || \
defined(CONFIG_BATTERY_PRESENT_GPIO)
if (battery_is_present() == BP_NO) {
curr->error |= F_BATTERY_NOT_CONNECTED;
return curr->error;
}
#endif
/* Read params and see if battery is responsive */
battery_get_params(batt);
if (!(batt->flags & BATT_FLAG_RESPONSIVE)) {
/* Check low battery condition and retry */
if (curr->ac && ctx->battery_responsive &&
!(curr->error & F_CHARGER_MASK)) {
ctx->battery_responsive = 0;
/*
* Try to revive ultra low voltage pack. Charge
* battery pack with minimum current and maximum
* voltage for 30 seconds.
*/
charge_request(ctx->battery->voltage_max,
ctx->battery->precharge_current);
for (d = 0; d < PRECHARGE_TIMEOUT; d++) {
sleep(1);
battery_get_params(batt);
if (batt->flags & BATT_FLAG_RESPONSIVE) {
ctx->battery_responsive = 1;
break;
}
}
}
/* Set error if battery is still unresponsive */
if (!(batt->flags & BATT_FLAG_RESPONSIVE)) {
curr->error |= F_BATTERY_UNRESPONSIVE;
return curr->error;
}
} else {
ctx->battery_responsive = 1;
}
/* Translate flags */
if (batt->flags & BATT_FLAG_BAD_ANY)
curr->error |= F_BATTERY_GET_PARAMS;
if (batt->flags & BATT_FLAG_BAD_VOLTAGE)
curr->error |= F_BATTERY_VOLTAGE;
if (batt->flags & BATT_FLAG_BAD_STATE_OF_CHARGE)
curr->error |= F_BATTERY_STATE_OF_CHARGE;
*ctx->memmap_batt_volt = batt->voltage;
/* Memory mapped value: discharge rate */
*ctx->memmap_batt_rate = batt->current < 0 ?
-batt->current : batt->current;
/* Fake state of charge if necessary */
if (fake_state_of_charge >= 0) {
batt->state_of_charge = fake_state_of_charge;
curr->error &= ~F_BATTERY_STATE_OF_CHARGE;
}
if (batt->state_of_charge != prev->batt.state_of_charge) {
rv = battery_full_charge_capacity(&d);
if (!rv && d != *(int *)host_get_memmap(EC_MEMMAP_BATT_LFCC)) {
*(int *)host_get_memmap(EC_MEMMAP_BATT_LFCC) = d;
/* Notify host to re-read battery information */
host_set_single_event(EC_HOST_EVENT_BATTERY);
}
}
/* Prevent deep discharging */
if (!curr->ac) {
if ((batt->state_of_charge < BATTERY_LEVEL_SHUTDOWN &&
!(curr->error & F_BATTERY_STATE_OF_CHARGE)) ||
(batt->voltage <= ctx->battery->voltage_min &&
!(curr->error & F_BATTERY_VOLTAGE)))
low_battery_shutdown(ctx);
}
/* Check battery presence */
if (curr->error & F_BATTERY_MASK) {
*ctx->memmap_batt_flags &= ~EC_BATT_FLAG_BATT_PRESENT;
return curr->error;
}
*ctx->memmap_batt_flags |= EC_BATT_FLAG_BATT_PRESENT;
/* Battery charge level low */
if (batt->state_of_charge <= BATTERY_LEVEL_LOW &&
prev->batt.state_of_charge > BATTERY_LEVEL_LOW)
host_set_single_event(EC_HOST_EVENT_BATTERY_LOW);
/* Battery charge level critical */
if (batt->state_of_charge <= BATTERY_LEVEL_CRITICAL) {
*ctx->memmap_batt_flags |= EC_BATT_FLAG_LEVEL_CRITICAL;
/* Send battery critical host event */
if (prev->batt.state_of_charge > BATTERY_LEVEL_CRITICAL)
host_set_single_event(EC_HOST_EVENT_BATTERY_CRITICAL);
} else {
*ctx->memmap_batt_flags &= ~EC_BATT_FLAG_LEVEL_CRITICAL;
}
#ifdef CONFIG_BATTERY_OVERRIDE_PARAMS
/* Apply battery pack vendor charging method */
battery_override_params(batt);
#endif
#ifdef CONFIG_CHARGER_CURRENT_LIMIT
if (batt->desired_current > CONFIG_CHARGER_CURRENT_LIMIT)
batt->desired_current = CONFIG_CHARGER_CURRENT_LIMIT;
#endif
if (batt->desired_current > user_current_limit)
batt->desired_current = user_current_limit;
if (fake_state_of_charge >= 0)
*ctx->memmap_batt_cap =
fake_state_of_charge *
*(int *)host_get_memmap(EC_MEMMAP_BATT_LFCC) / 100;
else if (battery_remaining_capacity(&d))
ctx->curr.error |= F_BATTERY_CAPACITY;
else
*ctx->memmap_batt_cap = d;
return ctx->curr.error;
}
/**
* Init state handler
*
* - check ac, charger, battery and temperature
* - initialize charger
* - new states: DISCHARGE, IDLE
*/
static enum charge_state state_init(struct charge_state_context *ctx)
{
/* Stop charger, unconditionally */
charge_request(0, 0);
/* if battery was not detected initially, get battery info again */
if (ctx->battery == NULL)
ctx->battery = battery_get_info();
/* Update static battery info */
update_battery_info();
/* Clear shutdown timer */
ctx->shutdown_warning_time.val = 0;
/* If AC is not present, switch to discharging state */
if (!ctx->curr.ac)
return PWR_STATE_DISCHARGE;
/* Check general error conditions */
if (ctx->curr.error)
return PWR_STATE_ERROR;
/* Send battery event to host */
host_set_single_event(EC_HOST_EVENT_BATTERY);
return PWR_STATE_IDLE0;
}
/**
* Idle state handler
*
* - both charger and battery are online
* - detect charger and battery status change
* - new states: CHARGE, INIT
*/
static enum charge_state state_idle(struct charge_state_context *ctx)
{
struct batt_params *batt = &ctx->curr.batt;
/* If we are forcing idle mode, then just stay in IDLE. */
if (state_machine_force_idle)
return PWR_STATE_UNCHANGE;
if (!ctx->curr.ac)
return PWR_STATE_REINIT;
if (ctx->curr.error)
return PWR_STATE_ERROR;
/* Prevent charging in idle mode */
if (ctx->curr.charging_voltage ||
ctx->curr.charging_current)
return PWR_STATE_REINIT;
if (batt->state_of_charge >= BATTERY_LEVEL_FULL)
return PWR_STATE_UNCHANGE;
/* Configure init charger state and switch to charge state */
if (batt->flags & BATT_FLAG_WANT_CHARGE) {
int want_current =
charger_closest_current(batt->desired_current);
CPRINTS("Charge start %dmV %dmA",
batt->desired_voltage, want_current);
if (charge_request(batt->desired_voltage, want_current))
return PWR_STATE_ERROR;
update_charger_time(ctx, get_time());
if (ctx->curr.batt.state_of_charge < BATTERY_LEVEL_NEAR_FULL)
return PWR_STATE_CHARGE;
else
return PWR_STATE_CHARGE_NEAR_FULL;
}
return PWR_STATE_UNCHANGE;
}
/**
* Charge state handler
*
* - detect battery status change
* - new state: INIT
*/
static enum charge_state state_charge(struct charge_state_context *ctx)
{
struct charge_state_data *curr = &ctx->curr;
struct batt_params *batt = &ctx->curr.batt;
int debounce = 0;
int want_current;
int want_voltage;
timestamp_t now;
if (curr->error)
return PWR_STATE_ERROR;
/*
* Some chargers will reset out from underneath us. If this happens,
* reinitialize charging.
*/
if (curr->charging_voltage == 0 ||
curr->charging_current == 0)
return PWR_STATE_REINIT;
if (!curr->ac)
return PWR_STATE_REINIT;
/* Stop charging if charging is no longer allowed */
if (!(batt->flags & BATT_FLAG_WANT_CHARGE)) {
if (charge_request(0, 0))
return PWR_STATE_ERROR;
return PWR_STATE_IDLE;
}
now = get_time();
/*
* Adjust desired voltage to one the charger can actually supply
* or else we'll keep asking for a voltage the charger can't actually
* supply.
*/
want_voltage = charger_closest_voltage(batt->desired_voltage);
if (want_voltage != curr->charging_voltage) {
CPRINTS("Charge voltage %dmV", want_voltage);
if (charge_request(want_voltage, -1))
return PWR_STATE_ERROR;
update_charger_time(ctx, now);
}
/*
* Adjust desired current to one the charger can actually supply before
* we do debouncing, or else we'll keep asking for a current the
* charger can't actually supply.
*/
want_current = charger_closest_current(batt->desired_current);
if (want_current == curr->charging_current) {
/* Tick charger watchdog */
if (!is_charger_expired(ctx, now))
return PWR_STATE_UNCHANGE;
} else if (want_current > curr->charging_current) {
if (!timestamp_expired(ctx->voltage_debounce_time, &now))
return PWR_STATE_UNCHANGE;
} else {
debounce = 1;
}
if (want_current != curr->charging_current) {
CPRINTS("Charge current %dmA @ %dmV",
want_current, batt->desired_voltage);
}
if (charge_request(-1, want_current))
return PWR_STATE_ERROR;
/* Update charger watchdog timer and debounce timer */
update_charger_time(ctx, now);
if (debounce)
ctx->voltage_debounce_time.val = now.val + DEBOUNCE_TIME;
return PWR_STATE_UNCHANGE;
}
/**
* Discharge state handler
*
* - detect ac status
* - new state: INIT
*/
static enum charge_state state_discharge(struct charge_state_context *ctx)
{
struct batt_params *batt = &ctx->curr.batt;
int8_t bat_temp_c = DECI_KELVIN_TO_CELSIUS(batt->temperature);
if (ctx->curr.ac)
return PWR_STATE_REINIT;
if (ctx->curr.error)
return PWR_STATE_ERROR;
/* Handle overtemp in discharging state by powering off host */
if ((bat_temp_c >= ctx->battery->discharging_max_c ||
bat_temp_c < ctx->battery->discharging_min_c) &&
chipset_in_state(CHIPSET_STATE_ON)) {
CPRINTS("charge force shutdown due to battery temp");
chipset_force_shutdown();
host_set_single_event(EC_HOST_EVENT_BATTERY_SHUTDOWN);
}
return PWR_STATE_UNCHANGE;
}
/**
* Error state handler
*
* - check charger and battery communication
* - log error
* - new state: INIT
*/
static enum charge_state state_error(struct charge_state_context *ctx)
{
static int logged_error;
if (!ctx->curr.error) {
logged_error = 0;
return PWR_STATE_REINIT;
}
charge_request(0, 0);
/* Debug output */
if (ctx->curr.error != logged_error) {
CPRINTS("Charge error: flag[%08b -> %08b], ac %d, "
" charger %s, battery %s",
logged_error, ctx->curr.error, ctx->curr.ac,
(ctx->curr.error & F_CHARGER_MASK) ? "(err)" : "ok",
(ctx->curr.error & F_BATTERY_MASK) ? "(err)" : "ok");
logged_error = ctx->curr.error;
}
return PWR_STATE_UNCHANGE;
}
/**
* Print charging progress
*/
static void charging_progress(struct charge_state_context *ctx)
{
int seconds, minutes;
if (ctx->curr.batt.state_of_charge != ctx->prev.batt.state_of_charge) {
if (ctx->curr.ac)
battery_time_to_full(&minutes);
else
battery_time_to_empty(&minutes);
CPRINTS("Battery %3d%% / %dh:%d",
ctx->curr.batt.state_of_charge,
minutes / 60, minutes % 60);
return;
}
if (ctx->curr.charging_voltage != ctx->prev.charging_voltage &&
ctx->trickle_charging_time.val) {
/* Calculate minutes by dividing usec by 60 million. GNU
* toolchain generates architecture dependent calls instead of
* machine code when the divisor is large, so break the
* calculation into 2 lines.
*/
seconds = (int)(get_time().val -
ctx->trickle_charging_time.val) / (int)SECOND;
minutes = seconds / 60;
CPRINTS("Precharge CHG(%dmV) BATT(%dmV %dmA) "
"%dh:%d", ctx->curr.charging_voltage,
ctx->curr.batt.voltage, ctx->curr.batt.current,
minutes / 60, minutes % 60);
}
}
enum charge_state charge_get_state(void)
{
return task_ctx.curr.state;
}
uint32_t charge_get_flags(void)
{
uint32_t flags = 0;
if (state_machine_force_idle)
flags |= CHARGE_FLAG_FORCE_IDLE;
if (extpower_is_present())
flags |= CHARGE_FLAG_EXTERNAL_POWER;
return flags;
}
int charge_get_percent(void)
{
return task_ctx.curr.batt.state_of_charge;
}
int charge_temp_sensor_get_val(int idx, int *temp_ptr)
{
const struct batt_params *batt = &task_ctx.curr.batt;
if (!(batt->flags & BATT_FLAG_RESPONSIVE))
return EC_ERROR_UNKNOWN;
*temp_ptr = C_TO_K(DECI_KELVIN_TO_CELSIUS(batt->temperature));
return EC_SUCCESS;
}
int charge_want_shutdown(void)
{
return (charge_get_state() == PWR_STATE_DISCHARGE) &&
charge_get_percent() < BATTERY_LEVEL_SHUTDOWN;
}
int charge_prevent_power_on(void)
{
int prevent_power_on = 0;
#ifdef CONFIG_CHARGER_MIN_BAT_PCT_FOR_POWER_ON
/* Require a minimum battery level to power on */
if (battery_is_present() == BP_NO ||
charge_get_percent() < CONFIG_CHARGER_MIN_BAT_PCT_FOR_POWER_ON)
prevent_power_on = 1;
#endif
/* Factory override: Always allow power on if WP is disabled */
return prevent_power_on && system_is_locked();
}
static int charge_force_idle(int enable)
{
if (enable) {
/*
* Force-idle state is only meaningful if external power is
* present. If it's not present we can't charge anyway...
*/
if (!(charge_get_flags() & CHARGE_FLAG_EXTERNAL_POWER))
return EC_ERROR_UNKNOWN;
charger_post_init();
}
state_machine_force_idle = enable;
return EC_SUCCESS;
}
const struct batt_params *charger_current_battery_params(void)
{
return &task_ctx.curr.batt;
}
/**
* Battery charging task
*/
void charger_task(void)
{
struct charge_state_context *ctx = &task_ctx;
timestamp_t ts;
int sleep_usec = CHARGE_POLL_PERIOD_SHORT, diff_usec, sleep_next;
enum charge_state new_state;
uint8_t batt_flags;
while (1) {
#ifdef CONFIG_SB_FIRMWARE_UPDATE
if (sb_fw_update_in_progress()) {
task_wait_event(CHARGE_MAX_SLEEP_USEC);
continue;
}
#endif
state_common(ctx);
#ifdef CONFIG_CHARGER_TIMEOUT_HOURS
if (ctx->curr.state == PWR_STATE_CHARGE &&
ctx->charge_state_updated_time.val +
CONFIG_CHARGER_TIMEOUT_HOURS * HOUR < ctx->curr.ts.val) {
CPRINTS("Charge timed out after %d hours",
CONFIG_CHARGER_TIMEOUT_HOURS);
charge_force_idle(1);
}
#endif /* CONFIG_CHARGER_TIMEOUT_HOURS */
switch (ctx->prev.state) {
case PWR_STATE_INIT:
case PWR_STATE_REINIT:
new_state = state_init(ctx);
break;
case PWR_STATE_IDLE0:
new_state = state_idle(ctx);
/* If still idling, move from IDLE0 to IDLE */
if (new_state == PWR_STATE_UNCHANGE)
new_state = PWR_STATE_IDLE;
break;
case PWR_STATE_IDLE:
new_state = state_idle(ctx);
break;
case PWR_STATE_DISCHARGE:
new_state = state_discharge(ctx);
break;
case PWR_STATE_CHARGE:
new_state = state_charge(ctx);
if (new_state == PWR_STATE_UNCHANGE &&
(ctx->curr.batt.state_of_charge >=
BATTERY_LEVEL_NEAR_FULL)) {
/* Almost done charging */
new_state = PWR_STATE_CHARGE_NEAR_FULL;
}
break;
case PWR_STATE_CHARGE_NEAR_FULL:
new_state = state_charge(ctx);
if (new_state == PWR_STATE_UNCHANGE &&
(ctx->curr.batt.state_of_charge <
BATTERY_LEVEL_NEAR_FULL)) {
/* Battery below almost-full threshold. */
new_state = PWR_STATE_CHARGE;
}
break;
case PWR_STATE_ERROR:
new_state = state_error(ctx);
break;
default:
CPRINTS("Charge state %d undefined",
ctx->curr.state);
ctx->curr.state = PWR_STATE_ERROR;
new_state = PWR_STATE_ERROR;
}
if (state_machine_force_idle &&
ctx->prev.state != PWR_STATE_IDLE0 &&
ctx->prev.state != PWR_STATE_IDLE &&
ctx->prev.state != PWR_STATE_INIT &&
ctx->prev.state != PWR_STATE_REINIT)
new_state = PWR_STATE_REINIT;
if (new_state) {
ctx->curr.state = new_state;
CPRINTS("Charge state %s -> %s after %.6ld sec",
state_name[ctx->prev.state],
state_name[new_state],
ctx->curr.ts.val -
ctx->charge_state_updated_time.val);
ctx->charge_state_updated_time = ctx->curr.ts;
hook_notify(HOOK_CHARGE_STATE_CHANGE);
}
switch (new_state) {
case PWR_STATE_IDLE0:
/*
* First time transitioning from init -> idle. Don't
* set the flags or LED yet because we may transition
* to charging on the next call and we don't want to
* blink the LED green.
*/
sleep_usec = CHARGE_POLL_PERIOD_SHORT;
break;
case PWR_STATE_CHARGE_NEAR_FULL:
/*
* Battery is almost charged. The last few percent
* take a loooong time, so fall through and look like
* we're charged. This mirrors similar hacks at the
* ACPI/kernel/UI level.
*/
case PWR_STATE_IDLE:
batt_flags = *ctx->memmap_batt_flags;
batt_flags &= ~EC_BATT_FLAG_CHARGING;
batt_flags &= ~EC_BATT_FLAG_DISCHARGING;
*ctx->memmap_batt_flags = batt_flags;
/* Charge done */
sleep_usec = (new_state == PWR_STATE_IDLE
? CHARGE_POLL_PERIOD_LONG
: CHARGE_POLL_PERIOD_CHARGE);
break;
case PWR_STATE_DISCHARGE:
batt_flags = *ctx->memmap_batt_flags;
batt_flags &= ~EC_BATT_FLAG_CHARGING;
batt_flags |= EC_BATT_FLAG_DISCHARGING;
*ctx->memmap_batt_flags = batt_flags;
sleep_usec = CHARGE_POLL_PERIOD_LONG;
break;
case PWR_STATE_CHARGE:
batt_flags = *ctx->memmap_batt_flags;
batt_flags |= EC_BATT_FLAG_CHARGING;
batt_flags &= ~EC_BATT_FLAG_DISCHARGING;
*ctx->memmap_batt_flags = batt_flags;
/* Charging */
sleep_usec = CHARGE_POLL_PERIOD_CHARGE;
break;
case PWR_STATE_ERROR:
/* Error */
sleep_usec = CHARGE_POLL_PERIOD_CHARGE;
break;
case PWR_STATE_UNCHANGE:
/* Don't change sleep duration */
break;
default:
/* Other state; poll quickly and hope it goes away */
sleep_usec = CHARGE_POLL_PERIOD_SHORT;
}
/* Show charging progress in console */
charging_progress(ctx);
ts = get_time();
diff_usec = (int)(ts.val - ctx->curr.ts.val);
sleep_next = sleep_usec - diff_usec;
if (ctx->curr.state == PWR_STATE_DISCHARGE &&
chipset_in_state(CHIPSET_STATE_ANY_OFF |
CHIPSET_STATE_SUSPEND)) {
/*
* Discharging and system is off or suspended, so no
* need to poll frequently. charge_hook() will wake us
* up if anything important changes.
*/
sleep_next = CHARGE_POLL_PERIOD_VERY_LONG - diff_usec;
} else if (sleep_next < CHARGE_MIN_SLEEP_USEC) {
sleep_next = CHARGE_MIN_SLEEP_USEC;
} else if (sleep_next > CHARGE_MAX_SLEEP_USEC) {
sleep_next = CHARGE_MAX_SLEEP_USEC;
}
task_wait_event(sleep_next);
}
}
/*****************************************************************************/
/* Hooks */
/**
* Chipset notification hook.
*
* This is triggered when the system boots or resumes, so that we can update
* our charging state.
*/
static void chipset_hook(void)
{
/* Wake up the task now */
task_wake(TASK_ID_CHARGER);
}
DECLARE_HOOK(HOOK_CHIPSET_RESUME, chipset_hook, HOOK_PRIO_DEFAULT);
/**
* AC change notification hook.
*
* This is triggered when the AC state changes, so that we can update the
* memory-mapped AC status and our charging state.
*/
static void ac_change_hook(void)
{
/**
* Update the memory-mapped AC_PRESENT flag immediately so the
* state is correct prior to the host being notified of the AC
* change event.
*/
if (extpower_is_present())
*task_ctx.memmap_batt_flags |= EC_BATT_FLAG_AC_PRESENT;
else
*task_ctx.memmap_batt_flags &= ~EC_BATT_FLAG_AC_PRESENT;
/* Wake up the task now */
task_wake(TASK_ID_CHARGER);
}
DECLARE_HOOK(HOOK_AC_CHANGE, ac_change_hook, HOOK_PRIO_DEFAULT);
static void charge_init(void)
{
struct charge_state_context *ctx = &task_ctx;
ctx->prev.state = PWR_STATE_INIT;
ctx->curr.state = PWR_STATE_INIT;
ctx->trickle_charging_time.val = 0;
ctx->battery = battery_get_info();
ctx->charger = charger_get_info();
/* Assume the battery is responsive until proven otherwise */
ctx->battery_responsive = 1;
/* Set up LPC direct memmap */
ctx->memmap_batt_volt =
(uint32_t *)host_get_memmap(EC_MEMMAP_BATT_VOLT);
ctx->memmap_batt_rate =
(uint32_t *)host_get_memmap(EC_MEMMAP_BATT_RATE);
ctx->memmap_batt_cap =
(uint32_t *)host_get_memmap(EC_MEMMAP_BATT_CAP);
ctx->memmap_batt_flags = host_get_memmap(EC_MEMMAP_BATT_FLAG);
}
DECLARE_HOOK(HOOK_INIT, charge_init, HOOK_PRIO_DEFAULT);
static void charge_shutdown(void)
{
/* Hibernate immediately if battery level is too low */
if (charge_want_shutdown()) {
CPRINTS("charge force EC hibernate after "
"shutdown due to low battery");
system_hibernate(0, 0);
}
}
/*
* Run the charge shutdown hook last, since when it hibernates no subsequent
* hooks would be run.
*/
DECLARE_HOOK(HOOK_CHIPSET_SHUTDOWN, charge_shutdown, HOOK_PRIO_LAST);
/*****************************************************************************/
/* Host commands */
static int charge_command_charge_control(struct host_cmd_handler_args *args)
{
const struct ec_params_charge_control *p = args->params;
int rv;
if (system_is_locked())
return EC_RES_ACCESS_DENIED;
rv = charge_force_idle(p->mode != CHARGE_CONTROL_NORMAL);
if (rv != EC_SUCCESS)
return rv;
#ifdef CONFIG_CHARGER_DISCHARGE_ON_AC
rv = board_discharge_on_ac(p->mode == CHARGE_CONTROL_DISCHARGE);
if (rv != EC_SUCCESS)
return rv;
#endif
return EC_RES_SUCCESS;
}
/*
* TODO(crbug.com/239197) : Adding both versions to the version mask is a
* temporary workaround for a problem in the cros_ec driver. Drop
* EC_VER_MASK(0) once cros_ec driver can send the correct version.
*/
DECLARE_HOST_COMMAND(EC_CMD_CHARGE_CONTROL, charge_command_charge_control,
EC_VER_MASK(0) | EC_VER_MASK(1));
static void reset_current_limit(void)
{
user_current_limit = -1;
}
DECLARE_HOOK(HOOK_CHIPSET_SUSPEND, reset_current_limit, HOOK_PRIO_DEFAULT);
DECLARE_HOOK(HOOK_CHIPSET_SHUTDOWN, reset_current_limit, HOOK_PRIO_DEFAULT);
static int charge_command_current_limit(struct host_cmd_handler_args *args)
{
const struct ec_params_current_limit *p = args->params;
user_current_limit = p->limit;
return EC_RES_SUCCESS;
}
DECLARE_HOST_COMMAND(EC_CMD_CHARGE_CURRENT_LIMIT, charge_command_current_limit,
EC_VER_MASK(0));
/*****************************************************************************/
/* Console commands */
static int command_battfake(int argc, char **argv)
{
char *e;
int v;
if (argc == 2) {
v = strtoi(argv[1], &e, 0);
if (*e || v < -1 || v > 100)
return EC_ERROR_PARAM1;
fake_state_of_charge = v;
}
if (fake_state_of_charge < 0)
ccprintf("Reporting real battery level\n");
else
ccprintf("Reporting fake battery level %d%%\n",
fake_state_of_charge);
/* Wake charger task immediately to see new level */
task_wake(TASK_ID_CHARGER);
return EC_SUCCESS;
}
DECLARE_CONSOLE_COMMAND(battfake, command_battfake,
"percent (-1 = use real level)",
"Set fake battery level",
NULL);
|
{
"content_hash": "9821f3b1378ecf81a3b275a79c0104d3",
"timestamp": "",
"source": "github",
"line_count": 1046,
"max_line_length": 79,
"avg_line_length": 26.719885277246654,
"alnum_prop": 0.6715088196357651,
"repo_name": "md5555/ec",
"id": "90d93446a2866a441d56bfd786ab2e24081fea91",
"size": "28171",
"binary": false,
"copies": "1",
"ref": "refs/heads/factory-smaug-7265.B",
"path": "common/charge_state_v1.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "83537"
},
{
"name": "C",
"bytes": "6522247"
},
{
"name": "C++",
"bytes": "77153"
},
{
"name": "Makefile",
"bytes": "56309"
},
{
"name": "Objective-C",
"bytes": "722"
},
{
"name": "Python",
"bytes": "35013"
},
{
"name": "Shell",
"bytes": "14131"
},
{
"name": "Tcl",
"bytes": "3816"
}
]
}
|
package com.spotify.missinglink.datamodel;
import com.google.common.collect.ImmutableMap;
import io.norberg.automatter.AutoMatter;
@AutoMatter
public interface Artifact {
/** "Name" of artifact, for example a directory path or jar file or something else symbolic. */
ArtifactName name();
/**
* Map of classname to class object. Names are com/foo/bar/Baz
*/
ImmutableMap<ClassTypeDescriptor, DeclaredClass> classes();
}
|
{
"content_hash": "74e9097085671c2eada8c6e752f5313a",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 97,
"avg_line_length": 24.38888888888889,
"alnum_prop": 0.7494305239179955,
"repo_name": "dflemstr/missinglink",
"id": "75f59941529b59ab9583c0c198e48c8f5e98c49e",
"size": "1032",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/src/main/java/com/spotify/missinglink/datamodel/Artifact.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "160617"
},
{
"name": "Shell",
"bytes": "1026"
}
]
}
|
<?php
namespace AppBundle\Service;
use AppBundle\Document\TrackImpression;
use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Component\VarDumper\VarDumper;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use GuzzleHttp\Client;
class TrackServiceMongo
{
protected $dm;
protected $client;
public function __construct(DocumentManager $documentManager, Client $client){
$this->dm = $documentManager;
$this->client = $client;
}
/**
* Return 1x1 gif.
*
* @return Response
*/
public function get1PxGifResponse()
{
$headers = array(
'Content-Control' => 'no-cache',
'Content-Type' => 'image/gif',
'Content-Length' => '43',
);
return new Response(base64_decode('R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='), 200, $headers);
}
/**
* @param $publisherId
* @param $linkId
*
* @return mixed
*/
public function getCampaignFromTrackArgs($publisherId, $linkId)
{
$cacheHash = 'trackImpression:'.$linkId;
$cacheKey = $publisherId;
$dm = $this->dm;
$campaignPublisherRepository = $dm->getRepository('AppBundle\Document\Campaign\CampaignPublisher');
$campaignLinkRepository = $dm->getRepository('AppBundle\Document\Campaign\CampaignLink');
$campaignPublisher = $campaignPublisherRepository->createQueryBuilder()
->field('publisher._id')
->equals($publisherId)
->getQuery()
->getSingleResult();
if(is_null($campaignPublisher))
return json_decode(null, 1);
$campaignId = $campaignPublisher->getCampaign()->getId();
$campaignLink = $campaignLinkRepository->createQueryBuilder()
->field('campaign._id')->equals($campaignId)
->getQuery()
->getSingleResult();
if(is_null($campaignLink))
return json_decode(null, 1);
$data['id'] = $campaignLink->getId();
$data['campaignId'] = $campaignId;
return $data;
}
/**
* @param $request
* @param $publisherId
* @param $linkId
*/
public function addImpression($request, $publisherId, $linkId)
{
$dm = $this->dm;
$now = new \DateTime();
$impression = new TrackImpression();
$impression->ip = $request->server->get('REMOTE_ADDR');
$impression->referer = $request->server->get('HTTP_REFERER', null);
$impression->publisher = $publisherId;
$impression->campaignLink = $linkId;
$impression->updatedTs = $now->format('Y-m-d H:i:s');
$impression->visible = true;
$dm->persist($impression);
$dm->flush();
}
}
|
{
"content_hash": "df2729c3e5837f8d8451255340c92298",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 122,
"avg_line_length": 28.896907216494846,
"alnum_prop": 0.6022119158044952,
"repo_name": "tulik/symfony-micro",
"id": "a652bbf1b0e9732e3210db56f7e3bf570f9fc16f",
"size": "2803",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/AppBundle/Service/TrackServiceMongo.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "419"
},
{
"name": "PHP",
"bytes": "330750"
}
]
}
|
using System;
namespace UnitTestingWithoutIoC
{
public class OperationFactory
{
public IOperation Create(string token)
{
switch (token)
{
case "+":
return new Plus();
case "-":
return new Minus();
case "*":
return new Multiply();
case "/":
return new Divide();
default:
throw new NotImplementedException();
}
}
}
}
|
{
"content_hash": "bc551972d832e338eabf328f0fe74abc",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 56,
"avg_line_length": 24.625,
"alnum_prop": 0.38071065989847713,
"repo_name": "IoCHowTo/IoCTasksSolutions",
"id": "a9f5a322c0cb96b7b31fed1eb7fc450510943b3f",
"size": "593",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "090_UnitTestingWithoutIoC/OperationFactory.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "128710"
}
]
}
|
+++
hook = "It's 2017, and the state of instant messaging is in worse shape than ever before."
published_at = 2017-01-17T15:33:00Z
title = "The state of messaging"
+++
I recently had a friend switch from iPhone to Android, and
it was an unpleasant wakeup call to see just how subdivided
the world of instant messaging is today. Because we were in
the Valley, and the overwhelming number of developers here
seem to own iPhones, we'd been able to get away up to that
point with a group iMessage chat. There's no excuse for
iMessage's horrible lock-in, but it tends to work well,
produces a conspicuous "double vibrate" on phones (so
people know they got a message), and has a pretty good
desktop client just as long as you're also on Mac.
The list of new possibilities is almost without end. SMS is
the classic lowest common denominator, but it doesn't have
good group support, is generally horrible, and doesn't work
with anything that's not a phone. Google Hangouts (Or is it
Allo? Previously also GTalk.) and Facebook Messenger are
also top possibilities, but depend on people being on each
service, and are painful to use on a desktop. Based off its
client support alone, Slack is also a contender.
Somewhat incredibly, because it came from a tiny upstart
compared to the other networks, WhatsApp may still be the
best option. It's interoperable, has a great desktop
client, and its attempts to keep the network secure are
laudable.
Twenty years ago in 1997, you had one option: ICQ. It had
its share of problems, but everyone was on it, and the
protocol was simple enough to cultivate a thriving
ecosystem of clients. As we hurdle into the future, deep
fractures have had the effect of making things broadly just
worse, even if we do now have faster networks and more
emoji.
The fact that SMS still exists and that telcos can still
gouge for its use is a testament to how broken things are.
Apple and Google would do the world a huge favor by getting
together and authoring an open standard (preferably one
that's simpler than XMPP) that any phone could dial into.
New features would be harder to add, but given that even
twenty years later instant messaging is still just text and
basic media, it's easily a worthwhile trade off.
|
{
"content_hash": "2cf348ede2199a1160b75fdf29207811",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 90,
"avg_line_length": 46.645833333333336,
"alnum_prop": 0.7865118356409111,
"repo_name": "brandur/sorg",
"id": "6221d79e439783839bd8dd9505f92d51b91b280e",
"size": "2239",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "content/fragments/state-of-messaging.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "66672"
},
{
"name": "Go",
"bytes": "156866"
},
{
"name": "HTML",
"bytes": "13370"
},
{
"name": "JavaScript",
"bytes": "39889"
},
{
"name": "Makefile",
"bytes": "12076"
},
{
"name": "Procfile",
"bytes": "42"
},
{
"name": "Ruby",
"bytes": "9207"
},
{
"name": "Sass",
"bytes": "31832"
},
{
"name": "Shell",
"bytes": "5469"
}
]
}
|
/********************************************************************
Popup Windows - V 4.5
Author: Brian Gosselin
Site URL: http://scriptasylum.com
Read the "releasenotes.txt" for supported features and release notes.
************** EDIT THE LINES BELOW AT YOUR OWN RISK ****************/
var w3c=(document.getElementById)? true: false;
var ns4=(document.layers)?true:false;
var ie5=(w3c && document.all)? true : false;
var ns6=(w3c && !document.all)? true: false;
var d=document;
currIDb=null; xoff=0; yoff=0;
currRS=null; rsxoff=0; rsyoff=0;
oldac=null; newac=null; zdx=1; mx=0; my=0;
var currFb=null; var currFs=null; var currFID=0; var currFcnt=0;
var cidlist=new Array();
//******* START OF EXPOSED FUNCTIONS. THESE CAN BE USED IN HYPERLINKS. *******\\
function fadeboxin(id){
if((currFb==null) && w3c){
clearInterval(currFID);
currFb=d.getElementById(id+'_b');
currFs=d.getElementById(id+'_s');
if(currFb.style.display=='none'){
currFcnt=0;
if(ie5)currFb.style.filter=currFs.style.filter="alpha(opacity=0)";
else currFb.style.MozOpacity=currFs.style.MozOpacity=0;
setAllScrollbars(true);
currFb.style.display=currFs.style.display='block';
changez(currFb);
currFID=setInterval('sub_fadein()',20);
}else currFb=null;
}}
function fadeboxout(id){
if((currFb==null) && w3c){
clearInterval(currFID);
currFb=d.getElementById(id+'_b');
currFs=d.getElementById(id+'_s');
if(currFb.style.display=='block'){
currFcnt=100;
if(ie5){
currFb.style.filter="alpha(opacity=100)";
currFs.style.filter="alpha(opacity=50)";
}else{
currFb.style.MozOpacity=1;
currFs.style.MozOpacity=.5;
}
setAllScrollbars(true);
currFb.style.display=currFs.style.display='block';
changez(currFb);
currFID=setInterval('sub_fadeout()',20);
}else currFb=null;
}}
function hidebox(id){
if(w3c){
//if(currFb!=d.getElementById(id+'_b')){
d.getElementById(id+'_b').style.display='none';
d.getElementById(id+'_s').style.display='none';
//}
}}
function showbox(id){
if(w3c){
var bx=d.getElementById(id+'_b');
var sh=d.getElementById(id+'_s');
bx.style.display='block';
sh.style.display='block';
sh.style.zIndex=++zdx;
bx.style.zIndex=++zdx;
if(ns6){
bx.style.MozOpacity=1;
sh.style.MozOpacity=.5;
}else{
bx.style.filter="alpha(opacity=100)";
sh.style.filter="alpha(opacity=50)";
}
changez(bx);
}}
function changecontent(id,text){
if(!document.getElementById(id+'_b').isExt){
var d=document.getElementById(id+'_c');
if(ns6)d.style.overflow="hidden";
d.innerHTML=text;
if(ns6)d.style.overflow="block";
}else document.getElementById(id+'_ifrm').src=text;
}
function movePopup(ids,x,y){
if(w3c){
var idb=document.getElementById(ids+'_b');
var ids=document.getElementById(ids+'_s');
idb.style.left=x+'px';
ids.style.left=x+8+'px';
idb.style.top=y+'px';
ids.style.top=y+8+'px';
}}
function resizePopup(ids,rx,ry){
if(w3c){
if(d.getElementById(ids+'_rs').rsEnable){
d.gEl=d.getElementById;
d.gEl(ids+"_extWA").style.display="block";
d.gEl(ids+"_rs").style.left=Math.max(rx,((ie5)?88:92))+'px';
d.gEl(ids+"_rs").style.top=Math.max(ry,((ie5)?68:72))+'px';
d.gEl(ids+"_b").style.width=Math.max(rx+((ie5)?12:8),100)+'px';
d.gEl(ids+"_b").style.height=Math.max(ry+((ie5)?12:8),80)+'px';
d.gEl(ids+"_t").style.width=Math.max(rx+((ie5)?4:3),((ns6)?95:92))+'px';
d.gEl(ids+"_btt").style.left=parseInt(d.gEl(ids+"_t").style.width)-48+'px';
d.gEl(ids+"_s").style.width=Math.max(rx+12,((ie5)?100:104))+'px';
d.gEl(ids+"_s").style.height=Math.max(ry+((ie5)?12:13),((ie5)?80:86))+'px';
d.gEl(ids+"_c").style.width=Math.max(rx-((ie5)?-5:5),((ie5)?92:87))+'px';
d.gEl(ids+"_c").style.height=Math.max(ry-((ie5)?24:28),44)+'px';
d.gEl(ids+"_max").h=parseInt(d.gEl(ids+"_b").style.height);
}}}
//******* END OF EXPOSED FUNCTIONS *******\\
function setAllScrollbars(ishide){
if(document.all){
var id;
for(i=0;i<cidlist.length;i++){
id=cidlist[i];
if(!document.getElementById(id+'_b').isExt)document.getElementById(id+'_c').style.overflow=(ishide)?"hidden":"auto";
}}}
function sub_fadein(){
currFcnt+=4;
if(ie5){
currFb.style.filter="alpha(opacity="+currFcnt+")";
currFs.style.filter="alpha(opacity="+(currFcnt/2)+")";
}else{
currFb.style.MozOpacity=currFcnt/100;
currFs.style.MozOpacity=(currFcnt/2)/100;
}
if(currFcnt>=99){
currFb.style.display=currFs.style.display='block';
setAllScrollbars(false)
currFb=null;
clearInterval(currFID);
}}
function sub_fadeout(){
currFcnt=currFcnt-4;
if(ie5){
currFb.style.filter="alpha(opacity="+currFcnt+")";
currFs.style.filter="alpha(opacity="+(currFcnt/2)+")";
}else{
currFb.style.MozOpacity=currFcnt/100;
currFs.style.MozOpacity=(currFcnt/2)/100;
}
if(currFcnt<=0){
currFb.style.display=currFs.style.display='none';
setAllScrollbars(false)
currFb=null;
clearInterval(currFID);
}}
function preloadBttns(){
var btns=new Array();
btns[0]=new Image(); btns[0].src="min.gif";
btns[1]=new Image(); btns[1].src="max.gif";
btns[2]=new Image(); btns[2].src="close.gif";
btns[3]=new Image(); btns[3].src="resize.gif";
}
preloadBttns();
function minimize(){
if(w3c){
d.getElementById(this.cid+"_b").style.height=(ie5)? '28px':'24px';
d.getElementById(this.cid+"_s").style.height='28px';
d.getElementById(this.cid+"_c").style.display='none';
d.getElementById(this.cid+"_rs").style.display='none';
ns6bugfix();
}}
function restore(){
if(w3c){
d.getElementById(this.cid+"_b").style.height=this.h+'px';
d.getElementById(this.cid+"_s").style.height=(ie5)? this.h+'px':this.h+5+'px';
d.getElementById(this.cid+"_c").style.display='block';
d.getElementById(this.cid+"_rs").style.display='block';
ns6bugfix();
}}
function ns6bugfix(){
if(navigator.userAgent.indexOf("Netscape/6")>0)setTimeout('self.resizeBy(0,1); self.resizeBy(0,-1);', 100);
}
function trackmouse(evt){
mx=(ie5)?event.clientX+d.body.scrollLeft:evt.pageX;
my=(ie5)?event.clientY+d.body.scrollTop:evt.pageY;
if(!ns6)movepopup();
if((currIDb!=null)||(currRS!=null))return false;
}
function movepopup(){
if((currIDb!=null)&&w3c)movePopup(currIDb.cid,mx+xoff,my+yoff);
if((currRS!=null)&&w3c)resizePopup(currRS.cid,mx+rsxoff,my+rsyoff);
return false;
}
function stopRS(){
d.getElementById(this.cid+"_extWA").style.display="none";
currRS=null;
}
function startRS(evt){
var ex=(ie5)?event.clientX+d.body.scrollLeft:evt.pageX;
var ey=(ie5)?event.clientY+d.body.scrollTop:evt.pageY;
rsxoff=parseInt(this.style.left)-ex;
rsyoff=parseInt(this.style.top)-ey;
currRS=this;
if(ns6)d.getElementById(this.cid+"_c").style.overflow='hidden';
return false;
}
function changez(v){
var th=(v!=null)?v:this;
if(oldac!=null)d.getElementById(oldac.cid+"_t").style.backgroundColor=oldac.inactivecolor;
if(ns6)d.getElementById(th.cid+"_c").style.overflow='auto';
oldac=th;
d.getElementById(th.cid+"_t").style.backgroundColor=th.activecolor;
d.getElementById(th.cid+"_s").style.zIndex=++zdx;
th.style.zIndex=++zdx;
d.getElementById(th.cid+"_rs").style.zIndex=++zdx;
}
function stopdrag(){
currIDb=null;
document.getElementById(this.cid+"_extWA").style.display="none";
ns6bugfix();
}
function grab_id(evt){
var ex=(ie5)?event.clientX+d.body.scrollLeft:evt.pageX;
var ey=(ie5)?event.clientY+d.body.scrollTop:evt.pageY;
xoff=parseInt(d.getElementById(this.cid+"_b").style.left)-ex;
yoff=parseInt(d.getElementById(this.cid+"_b").style.top)-ey;
currIDb=d.getElementById(this.cid+"_b");
currIDs=d.getElementById(this.cid+"_s");
d.getElementById(this.cid+"_extWA").style.display="block";
return false;
}
function subBox(x,y,w,h,bgc,id){
var v=d.createElement('div');
v.setAttribute('id',id);
v.style.position='absolute';
v.style.left=x+'px';
v.style.top=y+'px';
v.style.width=w+'px';
v.style.height=h+'px';
if(bgc!='')v.style.backgroundColor=bgc;
v.style.visibility='visible';
v.style.padding='0px';
return v;
}
function get_cookie(Name) {
var search=Name+"=";
var returnvalue="";
if(d.cookie.length>0){
offset=d.cookie.indexOf(search);
if(offset!=-1){
offset+=search.length;
end=d.cookie.indexOf(";",offset);
if(end==-1)end=d.cookie.length;
returnvalue=unescape(d.cookie.substring(offset,end));
}}
return returnvalue;
}
function popUp(x,y,w,h,cid,text,bgcolor,textcolor,fontstyleset,title,titlecolor,titletextcolor,bordercolor,scrollcolor,shadowcolor,showonstart,isdrag,isresize,oldOK,isExt,popOnce,minImg,maxImg,clsImg,rsImg){
var okPopUp=false;
if (popOnce){
if (get_cookie(cid)==""){
okPopUp=true;
d.cookie=cid+"=yes"
}}
else okPopUp=true;
if(okPopUp){
if(w3c){
cidlist[cidlist.length]=cid;
w=Math.max(w,100);
h=Math.max(h,80);
var rdiv=new subBox(w-((ie5)?12:8),h-((ie5)?12:8),7,7,'',cid+'_rs');
if(isresize){
rdiv.innerHTML='<img src="'+rsImg+'" width="7" height="7">';
rdiv.style.cursor='move';
}
rdiv.rsEnable=isresize;
var tw=(ie5)?w:w+4;
var th=(ie5)?h:h+6;
var shadow=new subBox(x+8,y+8,tw,th,shadowcolor,cid+'_s');
if(ie5)shadow.style.filter="alpha(opacity=50)";
else shadow.style.MozOpacity=.5;
shadow.style.zIndex=++zdx;
var outerdiv=new subBox(x,y,w,h,bordercolor,cid+'_b');
outerdiv.style.display="block";
outerdiv.style.borderStyle="outset";
outerdiv.style.borderWidth="2px";
outerdiv.style.borderColor=bordercolor;
outerdiv.style.zIndex=++zdx;
tw=(ie5)?w-8:w-5;
th=(ie5)?h+4:h-4;
var titlebar=new subBox(2,2,tw,20,titlecolor,cid+'_t');
titlebar.style.overflow="hidden";
titlebar.style.cursor="default";
var tmp=(isresize)?'<img src="'+minImg+'" width="16" height="16" id="'+cid+'_min"><img src="'+maxImg+'" width="16" height="16" id="'+cid+'_max">':'';
titlebar.innerHTML='<span style="position:absolute; left:3px; top:1px; font:bold 10pt sans-serif; color:'+titletextcolor+'; height:18px; overflow:hidden; clip-height:16px;">'+title+'</span><div id="'+cid+'_btt" style="position:absolute; width:48px; height:16px; left:'+(tw-48)+'px; top:2px; text-align:right">'+tmp+'<img src="'+clsImg+'" width="16" height="16" id="'+cid+'_cls"></div>';
tw=(ie5)?w-7:w-13;
var content=new subBox(2,24,tw,h-36,bgcolor,cid+'_c');
content.style.borderColor=bordercolor;
content.style.borderWidth="2px";
if(isExt){
content.innerHTML='<iframe id="'+cid+'_ifrm" src="'+text+'" width="100%" height="100%"></iframe>';
content.style.overflow="hidden";
}else{
if(ie5)content.style.scrollbarBaseColor=scrollcolor;
content.style.borderStyle="inset";
content.style.overflow="auto";
content.style.padding="0px 2px 0px 4px";
content.innerHTML=text;
content.style.font=fontstyleset;
content.style.color=textcolor;
}
var extWA=new subBox(2,24,0,0,'',cid+'_extWA');
extWA.style.display="none";
extWA.style.width='100%';
extWA.style.height='100%';
outerdiv.appendChild(titlebar);
outerdiv.appendChild(content);
outerdiv.appendChild(extWA);
outerdiv.appendChild(rdiv);
d.body.appendChild(shadow);
d.body.appendChild(outerdiv);
d.gEl=d.getElementById;
if(!showonstart)hidebox(cid);
var wB=d.gEl(cid+'_b');
wB.cid=cid;
wB.isExt=(isExt)?true:false;
var wT=d.gEl(cid+'_t');
wT.cid=cid;
if(isresize){
var wRS=d.gEl(cid+'_rs');
wRS.cid=cid;
var wMIN=d.gEl(cid+'_min');
wMIN.cid=cid;
var wMAX=d.gEl(cid+'_max');
wMAX.h=h;
wMAX.cid=cid;
wMIN.onclick=minimize;
wMAX.onclick=restore;
wRS.onmousedown=startRS;
wRS.onmouseup=stopRS;
}
var wCLS=d.gEl(cid+'_cls');
var wEXTWA=d.gEl(cid+'_extWA');
wB.activecolor=titlecolor;
wB.inactivecolor=scrollcolor;
if(oldac!=null)d.gEl(oldac.cid+"_t").style.backgroundColor=oldac.inactivecolor;
oldac=wB;
wCLS.onclick=new Function("hidebox('"+cid+"');");
wB.onmousedown=function(){ changez(this) }
if(isdrag){
wT.onmousedown=grab_id;
wT.onmouseup=stopdrag;
}
}else{
if(oldOK){
var ctr=new Date();
ctr=ctr.getTime();
var t=(isExt)?text:'';
var posn=(ns4)? 'screenX='+x+',screenY='+y: 'left='+x+',top='+y;
var win=window.open(t , "abc"+ctr , "status=no,menubar=no,width="+w+",height="+h+",resizable="+((isresize)?"yes":"no")+",scrollbars=yes,"+posn);
if(!isExt){
t='<html><head><title>'+title+'</title></head><body bgcolor="'+bgcolor+'"><font style="font:'+fontstyleset+'; color:'+textcolor+'">'+text+'</font></body></html>';
win.document.write(t);
win.document.close();
}}}}}
if(ns6)setInterval('movepopup()',40);
if(w3c){
d.onmousemove=trackmouse;
d.onmouseup=new Function("currRS=null");
}
|
{
"content_hash": "d1aadacad6426dadb9a938381f7ae4cb",
"timestamp": "",
"source": "github",
"line_count": 394,
"max_line_length": 386,
"avg_line_length": 31.253807106598984,
"alnum_prop": 0.6780087705051161,
"repo_name": "moodboom/Reusable",
"id": "54607ceab4de64394096701466e3efbebd27c4fa",
"size": "12314",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "JavaScript/old/iframe_movable_resizable_closable/popup.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2831"
},
{
"name": "C",
"bytes": "993356"
},
{
"name": "C++",
"bytes": "5190946"
},
{
"name": "CMake",
"bytes": "3091"
},
{
"name": "CSS",
"bytes": "15796"
},
{
"name": "GLSL",
"bytes": "912"
},
{
"name": "HTML",
"bytes": "121467"
},
{
"name": "JavaScript",
"bytes": "280800"
},
{
"name": "Kotlin",
"bytes": "3340"
},
{
"name": "Makefile",
"bytes": "11067"
},
{
"name": "Objective-C",
"bytes": "15130"
},
{
"name": "PHP",
"bytes": "221795"
},
{
"name": "Perl",
"bytes": "8995"
},
{
"name": "QMake",
"bytes": "809"
},
{
"name": "Scala",
"bytes": "11093"
},
{
"name": "Shell",
"bytes": "545"
}
]
}
|
@interface MyTextView : UITextView
- (void)setUndoManager:(NSUndoManager *)undoManager;
@end
@interface MessageViewControler : UITableViewController <UITextViewDelegate>
@property (nonatomic, strong) MyTextView * textView;
@property (nonatomic, strong) Countdown * countdown;
- (IBAction)clear:(id)sender;
@end
|
{
"content_hash": "9e6ae16f2e026291161c0b680f9db672",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 76,
"avg_line_length": 21.2,
"alnum_prop": 0.779874213836478,
"repo_name": "Lisapple/Closer",
"id": "5dd29dc1b8802fe6f633e5c8c17f89bb807ed5dc",
"size": "450",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "View Controllers/MessageViewControler.h",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "425"
},
{
"name": "C++",
"bytes": "1068"
},
{
"name": "Objective-C",
"bytes": "398834"
},
{
"name": "Swift",
"bytes": "52395"
}
]
}
|
var fs = require('fs');
var path = require('path');
var _ = require('underscore');
var Promise = require('promise');
var exec = require('child_process').exec;
var FfmpegTask = function(videoPath, config) {
this.videoPath = videoPath;
this.config = config;
var log = this.log = '';
this.run = function() {
var promise = new Promise(function(resolver, rejecter) {
var videoKey = videoPath.split('-')[0]; // grab the capture UUID
fs.readdir(config.paths.incoming, function(err, files) {
var fragments = _.filter(files, function(file) {
return ~file.indexOf(videoKey);
});
var outputPath = path.join(config.paths.outgoing, '/' + videoKey + '.mp4');
var cmd = config.ffmpeg.cmd;
var args = config.ffmpeg.args({ inputs: fragments, output: outputPath });
var ffmpeg = exec([cmd, args].join(' '), {
cwd: config.paths.incoming
});
ffmpeg.stdout.on('data', function (data) { log += data; });
ffmpeg.stderr.on('data', function (data) { log += data; });
ffmpeg.on('close', function(code) {
console.log('[ffmpeg]', 'process exit', code);
if(~code) {
resolver(outputPath);
_.each(fragments, function(fragment) {
console.log('[ffmpeg]', 'cleaning up', 'removing ' + fragment);
fs.unlink(path.join(config.paths.incoming, '/' + fragment));
});
}
return rejecter(log);
});
});
});
return promise;
};
};
module.exports = FfmpegTask;
|
{
"content_hash": "ffe938f47e0957ec3a6cc6b4792bb308",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 83,
"avg_line_length": 31.5,
"alnum_prop": 0.566984126984127,
"repo_name": "codeimpossible/node-tcp-socket",
"id": "506e627b94d7da99921b7fe7e9817621b3aa8158",
"size": "1575",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ext/video-finalizer/ffmpeg-task.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "270"
},
{
"name": "JavaScript",
"bytes": "12285"
}
]
}
|
using Xunit;
using SecurionPay.Exception;
using SecurionPay.Request;
using SecurionPayTests.ModelBuilders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SecurionPayTests.Integration
{
public class CustomerTests : IntegrationTest
{
private CustomerRequestBuilder _customerRequestBuilder = new CustomerRequestBuilder();
private CardRequestBuilder _cardRequestBuilder = new CardRequestBuilder();
private TokenRequestBuilder _tokenRequestBuilder = new TokenRequestBuilder();
[Fact]
public async Task CustomerWithNewCardTest()
{
try
{
var customerRequest = _customerRequestBuilder.WithCard(_cardRequestBuilder).Build();
var customer = await _gateway.CreateCustomer(customerRequest);
Assert.Single(customer.Cards);
Assert.Equal(customerRequest.Card.CardholderName, customer.Cards.First().CardholderName);
}
catch (SecurionPayException exc)
{
HandleApiException(exc);
}
}
[Fact]
public async Task CustomerWithCardTokenTest()
{
try
{
var createTokenRequest = _tokenRequestBuilder.Build();
var token = await _gateway.CreateToken(createTokenRequest);
token = await _gateway.RetrieveToken(token.Id);
var customerRequest = _customerRequestBuilder.WithCard(_cardRequestBuilder.WithId(token.Id)).Build();
var customer = await _gateway.CreateCustomer(customerRequest);
Assert.Single(customer.Cards);
Assert.Equal(createTokenRequest.CardholderName, customer.Cards.First().CardholderName);
}
catch (SecurionPayException exc)
{
HandleApiException(exc);
}
}
[Fact]
public async Task ListCustomersWithGivenEmailTest()
{
try
{
var customerRequest = _customerRequestBuilder.Build();
var customer = await _gateway.CreateCustomer(customerRequest);
var customerListRequest = new CustomerListRequest()
{
Email = customerRequest.Email
};
var list = await _gateway.ListCustomers(customerListRequest);
Assert.True(list.List.Count > 0);
Assert.True(list.List.All(item => item.Email == customerRequest.Email));
}
catch (SecurionPayException exc)
{
HandleApiException(exc);
}
}
}
}
|
{
"content_hash": "8a44afd105ec17259fa5ac7eca20bd42",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 117,
"avg_line_length": 34.135802469135804,
"alnum_prop": 0.5956600361663653,
"repo_name": "securionpay/securionpay-net",
"id": "9cd80f579cf7c8346c632c0132f5a1662289f817",
"size": "2767",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SecurionPayTests/Integration/CustomerTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "260992"
}
]
}
|
package stashkins
import (
"testing"
"github.com/xoom/jenkins"
)
var maven string = `<?xml version='1.0' encoding='UTF-8'?>
<maven2-moduleset plugin="maven-plugin@2.7.1">
<description>Build maven</description>
</maven2-moduleset>`
var freestyle string = `<?xml version='1.0' encoding='UTF-8'?>
<project>
<description>Builds freestyle</description>
</project>`
var unknown string = `<?xml version='1.0' encoding='UTF-8'?>
<nope>
<description>Builds freestyle</description>
</nope>`
func TestDocumentType(t *testing.T) {
if jobType, _ := jobType([]byte(maven)); jobType != jenkins.Maven {
t.Fatalf("Want jenkins.Maven type but got %v\n", jobType)
}
if jobType, _ := jobType([]byte(freestyle)); jobType != jenkins.Freestyle {
t.Fatalf("Want jenkins.Freestyle type but got %v\n", jobType)
}
if jobType, _ := jobType([]byte(unknown)); jobType != jenkins.Unknown {
t.Fatalf("Want jenkins.Unknown type but got %v\n", jobType)
}
if jobType, _ := jobType([]byte("")); jobType != jenkins.Unknown {
t.Fatalf("Want jenkins.Unknown type but got %v\n", jobType)
}
if _, err := jobType([]byte("{}")); err == nil {
t.Fatalf("Expecting an error parsing not-XMLt %v\n", err)
}
}
|
{
"content_hash": "290c5b776022477adf28add2fdd80bfb",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 76,
"avg_line_length": 27.386363636363637,
"alnum_prop": 0.6647302904564315,
"repo_name": "xoom/stashkins",
"id": "b095e253f16d8d6737862ae2aee1eac5448d07d5",
"size": "1205",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "stashkins/templateType_test.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "61865"
},
{
"name": "Makefile",
"bytes": "1662"
}
]
}
|
package com.mycompany.myapp.service.mapper;
import com.mycompany.myapp.domain.Authority;
import com.mycompany.myapp.domain.User;
import com.mycompany.myapp.service.dto.UserDTO;
import org.mapstruct.*;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Mapper for the entity User and its DTO UserDTO.
*/
@Mapper(componentModel = "spring", uses = {})
public interface UserMapper {
UserDTO userToUserDTO(User user);
List<UserDTO> usersToUserDTOs(List<User> users);
@Mapping(target = "createdBy", ignore = true)
@Mapping(target = "createdDate", ignore = true)
@Mapping(target = "lastModifiedBy", ignore = true)
@Mapping(target = "lastModifiedDate", ignore = true)
@Mapping(target = "persistentTokens", ignore = true)
@Mapping(target = "id", ignore = true)
@Mapping(target = "activationKey", ignore = true)
@Mapping(target = "resetKey", ignore = true)
@Mapping(target = "resetDate", ignore = true)
@Mapping(target = "password", ignore = true)
User userDTOToUser(UserDTO userDTO);
List<User> userDTOsToUsers(List<UserDTO> userDTOs);
default User userFromId(Long id) {
if (id == null) {
return null;
}
User user = new User();
user.setId(id);
return user;
}
default Set<String> stringsFromAuthorities (Set<Authority> authorities) {
return authorities.stream().map(Authority::getName)
.collect(Collectors.toSet());
}
default Set<Authority> authoritiesFromStrings(Set<String> strings) {
return strings.stream().map(string -> {
Authority auth = new Authority();
auth.setName(string);
return auth;
}).collect(Collectors.toSet());
}
}
|
{
"content_hash": "2e7a82bbbd5d330fe4ffcc0b3df2dd56",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 77,
"avg_line_length": 31.12280701754386,
"alnum_prop": 0.6567080045095829,
"repo_name": "cfaddict/jhipster-course",
"id": "011e947eda71fba878652ef0d75639ed9c3831b4",
"size": "1774",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/bookstore/src/main/java/com/mycompany/myapp/service/mapper/UserMapper.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "45042"
},
{
"name": "CSS",
"bytes": "221662"
},
{
"name": "Gherkin",
"bytes": "501"
},
{
"name": "Groovy",
"bytes": "1502"
},
{
"name": "HTML",
"bytes": "877809"
},
{
"name": "Java",
"bytes": "2493191"
},
{
"name": "JavaScript",
"bytes": "3397788"
},
{
"name": "PowerShell",
"bytes": "471"
},
{
"name": "Ruby",
"bytes": "1030"
},
{
"name": "Scala",
"bytes": "27206"
},
{
"name": "Shell",
"bytes": "62932"
},
{
"name": "TypeScript",
"bytes": "563340"
}
]
}
|
<project default="help" name="Vibrator">
<property file="build.system.properties"/>
<property file="build.properties"/>
<property name="src.dir" value="src"/>
<property name="build.dir" value="build"/>
<property name="lib.dir" value="lib"/>
<property name="doc.dir" value="docs"/>
<property name="javadoc.dir.name" value="javadoc"/>
<property name="javadoc.dir" value="${doc.dir}/${javadoc.dir.name}"/>
<property name="javadoc.subdir" value="${doc.dir}/${javadoc.dir.name}/${project.name}-${project.version}-javadoc"/>
<property name="javadoc.file" value="${doc.dir}/${project.name}-${project.version}-javadoc.zip"/>
<property name="classes.dir" value="${build.dir}/classes"/>
<property name="jar.dir" value="${build.dir}/jar"/>
<taskdef resource="antenna.properties" classpath="${antenna.jar}"/>
<target name="help">
<echo message="Avaiable tasks: ${line.separator}"/>
<echo message=" help - Display this help message ${line.separator}"/>
<echo message=" clean - Clean the build directories${line.separator}"/>
<echo message=" build - Build the class files${line.separator}"/>
<echo message=" package - Build jar file${line.separator}"/>
<echo message=" clean-javadoc - Clean the javadoc directory${line.separator}"/>
<echo message=" javadoc - Build the javadoc${line.separator}"/>
<echo message=" eclipse - Convert files to an eclipse project t${line.separator}"/>
</target>
<target name="clean">
<delete includeemptydirs="true" failonerror="false">
<fileset dir="${classes.dir}" includes="**/*"/>
</delete>
<delete includeemptydirs="true" failonerror="false">
<fileset dir="${jar.dir}" includes="**/*"/>
</delete>
</target>
<target name="build">
<mkdir dir="${classes.dir}"/>
<wtkbuild excludes="**/.svn/*" srcdir="src" destdir="${classes.dir}" />
</target>
<target name="package" depends="build">
<mkdir dir="${jar.dir}"/>
<jar destfile="build/jar/${project.name}-${project.version}.jar" basedir="${classes.dir}"/>
</target>
<target name="clean-javadoc">
<delete includeemptydirs="true" failonerror="false">
<fileset dir="${javadoc.dir}" includes="**/*"/>
</delete>
<delete file="${javadoc.file}" failonerror="false" />
</target>
<target name="javadoc" depends="clean-javadoc">
<mkdir dir="${javadoc.dir}"/>
<mkdir dir="${javadoc.subdir}"/>
<javadoc sourcepath="${src.dir}"
destdir="${javadoc.subdir}"
linksource="true"
packagenames="*"
defaultexcludes="yes"
/>
<zip destfile="${javadoc.file}"
basedir="${javadoc.dir}"
update="true"
includes="**/*">
</zip>
</target>
<target name="eclipse">
<echo file=".classpath"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="${src.dir}"/>
<classpathentry kind="lib" path="${wtk.home}/lib/cldcapi11.jar"/>
<classpathentry kind="lib" path="${wtk.home}/lib/midpapi21.jar"/>
<classpathentry kind="lib" path="${lib.dir}"/>
<classpathentry kind="output" path="${classes.dir}"/>
</classpath>]]></echo>
<echo file=".project"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>${project.name}</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>eclipseme.core.nature</nature>
</natures>
</projectDescription>]]></echo>
</target>
</project>
|
{
"content_hash": "5fd97dfb5d0bc789b9c0a19d0f0c6526",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 121,
"avg_line_length": 40.386138613861384,
"alnum_prop": 0.5687668546212307,
"repo_name": "wjsrobertson/j2menace",
"id": "33800b73840120d0d560f9509f61e6a9b2e52282",
"size": "4079",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Vibrator/build.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "477499"
}
]
}
|
// This file is automatically generated.
package adila.db;
/*
* HTC Desire 626s
*
* DEVICE: htc_a32ewhl
* MODEL: HTC Desire 626s
*/
final class htc5fa32ewhl_htc20desire20626s {
public static final String DATA = "HTC|Desire 626s|";
}
|
{
"content_hash": "6bb40344a12b434c28584eab0c5c61ba",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 57,
"avg_line_length": 18.76923076923077,
"alnum_prop": 0.7049180327868853,
"repo_name": "karim/adila",
"id": "96a73878013527c66cf4d865875994b65332b038",
"size": "244",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "database/src/main/java/adila/db/htc5fa32ewhl_htc20desire20626s.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "2903103"
},
{
"name": "Prolog",
"bytes": "489"
},
{
"name": "Python",
"bytes": "3280"
}
]
}
|
import Component from './component'
import Controller from './controller'
import Event from './event'
import dom from './dom'
import locale from './locale'
import router from './router'
import utils from './utils/main'
export default {
Component,
Controller,
Event,
dom,
locale,
router,
utils
}
|
{
"content_hash": "5a008c84b6e5aa22770e5fbabdb1aca1",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 37,
"avg_line_length": 18.235294117647058,
"alnum_prop": 0.7064516129032258,
"repo_name": "SuneBear/Email-Catcher",
"id": "ae57bc2e688c89be843a3b5fce2c55c7846b25d3",
"size": "310",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/scripts/framework/main.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "6228"
},
{
"name": "HTML",
"bytes": "10466"
},
{
"name": "JavaScript",
"bytes": "138640"
}
]
}
|
This repository provides an [`istio-manifests`](/istio-manifests) directory containing ingress resources (an Istio `Gateway` and `VirtualService`) needed to expose the app frontend running inside a Kubernetes cluster.
You can apply these resources to your cluster in addition to the `kubernetes-manifests`, then use the Istio IngressGateway's external IP to view the app frontend. See the following instructions for Istio steps.
## Steps
1. Create a GKE cluster with at least 4 nodes, machine type `e2-standard-4`.
```
PROJECT_ID="<your-project-id>"
ZONE="<your-GCP-zone>"
gcloud container clusters create onlineboutique \
--project=${PROJECT_ID} --zone=${ZONE} \
--machine-type=e2-standard-4 --num-nodes=4
```
2. [Install Istio](https://istio.io/latest/docs/setup/getting-started/) on your cluster.
3. Enable Istio sidecar proxy injection in the `default` Kubernetes namespace.
```sh
kubectl label namespace default istio-injection=enabled
```
4. Apply all the manifests in the `/release` directory. This includes the Istio and Kubernetes manifests.
```sh
kubectl apply -f ./release
```
5. Run `kubectl get pods` to see pods are in a healthy and ready state.
6. Find the IP address of your Istio gateway Ingress or Service, and visit the
application frontend in a web browser.
```sh
INGRESS_HOST="$(kubectl -n istio-system get service istio-ingressgateway \
-o jsonpath='{.status.loadBalancer.ingress[0].ip}')"
echo "$INGRESS_HOST"
```
```sh
curl -v "http://$INGRESS_HOST"
```
## Additional service mesh demos using OnlineBoutique
- [Canary deployment](https://github.com/GoogleCloudPlatform/istio-samples/tree/master/istio-canary-gke)
- [Security (mTLS, JWT, Authorization)](https://github.com/GoogleCloudPlatform/istio-samples/tree/master/security-intro)
- [Cloud Operations (Stackdriver)](https://github.com/GoogleCloudPlatform/istio-samples/tree/master/istio-stackdriver)
- [Stackdriver metrics (Open source Istio)](https://github.com/GoogleCloudPlatform/istio-samples/tree/master/stackdriver-metrics)
|
{
"content_hash": "3dbf88b52a750fe050e17e41cce5d21d",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 217,
"avg_line_length": 38.72222222222222,
"alnum_prop": 0.7388809182209469,
"repo_name": "GoogleCloudPlatform/training-data-analyst",
"id": "676bddb5e181d2dbdfbe0587219edfc50e03620d",
"size": "2133",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "blogs/microservices-demo-1/docs/service-mesh.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "39536"
},
{
"name": "C#",
"bytes": "23445"
},
{
"name": "C++",
"bytes": "30926"
},
{
"name": "CSS",
"bytes": "53087"
},
{
"name": "Dockerfile",
"bytes": "90856"
},
{
"name": "Go",
"bytes": "93755"
},
{
"name": "HCL",
"bytes": "73891"
},
{
"name": "HTML",
"bytes": "2342167"
},
{
"name": "Java",
"bytes": "2441030"
},
{
"name": "JavaScript",
"bytes": "3957504"
},
{
"name": "Jinja",
"bytes": "257585"
},
{
"name": "Jsonnet",
"bytes": "5696"
},
{
"name": "Jupyter Notebook",
"bytes": "242016061"
},
{
"name": "Makefile",
"bytes": "12642"
},
{
"name": "PigLatin",
"bytes": "11558"
},
{
"name": "Pug",
"bytes": "457977"
},
{
"name": "Python",
"bytes": "18543833"
},
{
"name": "R",
"bytes": "68"
},
{
"name": "Scala",
"bytes": "27161"
},
{
"name": "Shell",
"bytes": "763259"
},
{
"name": "TypeScript",
"bytes": "66858"
}
]
}
|
package com.amazonaws.services.simplesystemsmanagement.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/UpdateDocumentDefaultVersion" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateDocumentDefaultVersionRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The name of a custom document that you want to set as the default version.
* </p>
*/
private String name;
/**
* <p>
* The version of a custom document that you want to set as the default version.
* </p>
*/
private String documentVersion;
/**
* <p>
* The name of a custom document that you want to set as the default version.
* </p>
*
* @param name
* The name of a custom document that you want to set as the default version.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* The name of a custom document that you want to set as the default version.
* </p>
*
* @return The name of a custom document that you want to set as the default version.
*/
public String getName() {
return this.name;
}
/**
* <p>
* The name of a custom document that you want to set as the default version.
* </p>
*
* @param name
* The name of a custom document that you want to set as the default version.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateDocumentDefaultVersionRequest withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The version of a custom document that you want to set as the default version.
* </p>
*
* @param documentVersion
* The version of a custom document that you want to set as the default version.
*/
public void setDocumentVersion(String documentVersion) {
this.documentVersion = documentVersion;
}
/**
* <p>
* The version of a custom document that you want to set as the default version.
* </p>
*
* @return The version of a custom document that you want to set as the default version.
*/
public String getDocumentVersion() {
return this.documentVersion;
}
/**
* <p>
* The version of a custom document that you want to set as the default version.
* </p>
*
* @param documentVersion
* The version of a custom document that you want to set as the default version.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateDocumentDefaultVersionRequest withDocumentVersion(String documentVersion) {
setDocumentVersion(documentVersion);
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 (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getDocumentVersion() != null)
sb.append("DocumentVersion: ").append(getDocumentVersion());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof UpdateDocumentDefaultVersionRequest == false)
return false;
UpdateDocumentDefaultVersionRequest other = (UpdateDocumentDefaultVersionRequest) obj;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getDocumentVersion() == null ^ this.getDocumentVersion() == null)
return false;
if (other.getDocumentVersion() != null && other.getDocumentVersion().equals(this.getDocumentVersion()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getDocumentVersion() == null) ? 0 : getDocumentVersion().hashCode());
return hashCode;
}
@Override
public UpdateDocumentDefaultVersionRequest clone() {
return (UpdateDocumentDefaultVersionRequest) super.clone();
}
}
|
{
"content_hash": "9d0d0f270d467d493b026643423df554",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 131,
"avg_line_length": 30.64457831325301,
"alnum_prop": 0.619028897188913,
"repo_name": "jentfoo/aws-sdk-java",
"id": "1738188688e39c4858eb09e53933684a6b11b8ef",
"size": "5667",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/UpdateDocumentDefaultVersionRequest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "270"
},
{
"name": "FreeMarker",
"bytes": "173637"
},
{
"name": "Gherkin",
"bytes": "25063"
},
{
"name": "Java",
"bytes": "356214839"
},
{
"name": "Scilab",
"bytes": "3924"
},
{
"name": "Shell",
"bytes": "295"
}
]
}
|
End of preview.
No dataset card yet
- Downloads last month
- 3