text
stringlengths
2
1.04M
meta
dict
<?php /** * Swift_PropelSpool is a spool that uses Propel. * * Example schema: * * mail_message: * message: { type: clob } * created_at: ~ * * @package symfony * @subpackage mailer * @author Fabien Potencier <fabien.potencier@symfony-project.com> * @version SVN: $Id: Swift_PropelSpool.class.php 23810 2010-11-12 11:07:44Z Kris.Wallsmith $ */ class Swift_PropelSpool extends Swift_ConfigurableSpool { protected $model = null, $column = null, $method = null; /** * Constructor. * * @param string The Propel model to use to store the messages (MailMessage by default) * @param string The column name to use for message storage (message by default) * @param string The method to call to retrieve the messages to send (optional) */ public function __construct($model = 'MailMessage', $column = 'message', $method = 'doSelect') { $this->model = $model; $this->column = $column; $this->method = $method; } /** * Tests if this Transport mechanism has started. * * @return boolean */ public function isStarted() { return true; } /** * Starts this Transport mechanism. */ public function start() { } /** * Stops this Transport mechanism. */ public function stop() { } /** * Stores a message in the queue. * * @param Swift_Mime_Message $message The message to store */ public function queueMessage(Swift_Mime_Message $message) { $object = new $this->model; if (!$object instanceof BaseObject) { throw new InvalidArgumentException('The mailer message object must be a BaseObject object.'); } $model = constant($this->model.'::PEER'); $method = 'set'.call_user_func(array($model, 'translateFieldName'), $this->column, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME); $object->$method(serialize($message)); $object->save(); } /** * Sends messages using the given transport instance. * * @param Swift_Transport $transport A transport instance * @param string[] &$failedRecipients An array of failures by-reference * * @return int The number of sent emails */ public function flushQueue(Swift_Transport $transport, &$failedRecipients = null) { $criteria = new Criteria(); $criteria->setLimit($this->getMessageLimit()); $model = constant($this->model.'::PEER'); $objects = call_user_func(array($model, $this->method), $criteria); if (!$transport->isStarted()) { $transport->start(); } $method = 'get'.call_user_func(array($model, 'translateFieldName'), $this->column, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME); $count = 0; $time = time(); foreach ($objects as $object) { $message = unserialize($object->$method()); $object->delete(); try { $count += $transport->send($message, $failedRecipients); } catch (Exception $e) { // TODO: What to do with errors? } if ($this->getTimeLimit() && (time() - $time) >= $this->getTimeLimit()) { break; } } return $count; } }
{ "content_hash": "a7c08fd7418aa69b344348c90a0272a9", "timestamp": "", "source": "github", "line_count": 132, "max_line_length": 137, "avg_line_length": 23.96212121212121, "alnum_prop": 0.6139740752450206, "repo_name": "italinux/Authentication", "id": "94275b46665b99fb209c31fc2275469719d6f647", "size": "3407", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/vendor/symfony/lib/plugins/sfPropelPlugin/lib/mailer/Swift_PropelSpool.class.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "721" }, { "name": "PHP", "bytes": "219653" } ], "symlink_target": "" }
package io.cdap.mmds.data; /** * Split states. */ public enum SplitStatus { SPLITTING("Splitting"), COMPLETE("Complete"), FAILED("Failed"); private final String label; SplitStatus(String label) { this.label = label; } @Override public String toString() { return label; } }
{ "content_hash": "876e5fe83f7195ecec2221325bf278ad", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 29, "avg_line_length": 13.909090909090908, "alnum_prop": 0.6437908496732027, "repo_name": "cdap-solutions/mmds", "id": "7bfc9f661fbcfc3a7abcb627a92f227da1493a74", "size": "908", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "mmds-model/src/main/java/io/cdap/mmds/data/SplitStatus.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "410417" } ], "symlink_target": "" }
/** * Unit test for the hookable-textarea component */ import {expect} from 'chai' import {HookMixin} from 'ember-hook' import {unit} from 'ember-test-utils/test-support/setup-component-test' import {beforeEach, describe, it} from 'mocha' const test = unit('hookable-textarea') describe(test.label, function () { test.setup() let component beforeEach(function () { component = this.subject({ hook: 'myTextarea' }) }) it('should have the HookMixin', function () { expect(HookMixin.detect(component)).to.equal(true) }) })
{ "content_hash": "588db11593e3ba3275f923d5bfebf228", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 71, "avg_line_length": 22.28, "alnum_prop": 0.6804308797127468, "repo_name": "dafortin/ember-frost-core", "id": "166950f3d6f130452feb181b6689b0eebc42a00a", "size": "557", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "tests/unit/components/hookable-textarea-test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "83916" }, { "name": "HTML", "bytes": "140840" }, { "name": "JavaScript", "bytes": "507539" }, { "name": "Shell", "bytes": "2166" } ], "symlink_target": "" }
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.engine.impl; import static org.camunda.bpm.engine.impl.util.EnsureUtil.ensureNotNull; import java.util.List; import org.camunda.bpm.engine.history.HistoricCaseActivityStatistics; import org.camunda.bpm.engine.history.HistoricCaseActivityStatisticsQuery; import org.camunda.bpm.engine.impl.interceptor.CommandContext; import org.camunda.bpm.engine.impl.interceptor.CommandExecutor; /** * @author smirnov * */ public class HistoricCaseActivityStatisticsQueryImpl extends AbstractQuery<HistoricCaseActivityStatisticsQuery, HistoricCaseActivityStatistics> implements HistoricCaseActivityStatisticsQuery { private static final long serialVersionUID = 1L; protected String caseDefinitionId; public HistoricCaseActivityStatisticsQueryImpl(String caseDefinitionId, CommandExecutor commandExecutor) { super(commandExecutor); this.caseDefinitionId = caseDefinitionId; } public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getHistoricStatisticsManager() .getHistoricStatisticsCountGroupedByCaseActivity(this); } public List<HistoricCaseActivityStatistics> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getHistoricStatisticsManager() .getHistoricStatisticsGroupedByCaseActivity(this, page); } protected void checkQueryOk() { super.checkQueryOk(); ensureNotNull("No valid case definition id supplied", "caseDefinitionId", caseDefinitionId); } public String getCaseDefinitionId() { return caseDefinitionId; } }
{ "content_hash": "ca067f2ead8e138963397065bb3c17b2", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 154, "avg_line_length": 33.815384615384616, "alnum_prop": 0.7779799818016379, "repo_name": "plexiti/camunda-bpm-platform", "id": "d37fcf21a22c4c9ae91b68cac7449731790ae0db", "size": "2198", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "engine/src/main/java/org/camunda/bpm/engine/impl/HistoricCaseActivityStatisticsQueryImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "6657" }, { "name": "CSS", "bytes": "1301" }, { "name": "Groovy", "bytes": "1594" }, { "name": "HTML", "bytes": "35196" }, { "name": "Java", "bytes": "19788553" }, { "name": "JavaScript", "bytes": "43" }, { "name": "PLpgSQL", "bytes": "3405" }, { "name": "Python", "bytes": "187" }, { "name": "Ruby", "bytes": "60" }, { "name": "Shell", "bytes": "4048" } ], "symlink_target": "" }
<Type Name="CFNetworkHandler" FullName="System.Net.Http.CFNetworkHandler"> <TypeSignature Language="C#" Value="public class CFNetworkHandler : System.Net.Http.HttpMessageHandler" /> <TypeSignature Language="ILAsm" Value=".class public auto ansi beforefieldinit CFNetworkHandler extends System.Net.Http.HttpMessageHandler" /> <AssemblyInfo> <AssemblyName>System.Net.Http</AssemblyName> <AssemblyVersion>2.0.5.0</AssemblyVersion> </AssemblyInfo> <Base> <BaseTypeName>System.Net.Http.HttpMessageHandler</BaseTypeName> </Base> <Interfaces /> <Docs> <summary>An Http Message Handler for HttpClient that is powered by iOS/MacOS CFNetwork stack.</summary> <remarks preserve-mono="true"> <para> This handler allows the HttpClient API to use Apple's CFNetwork as the HTTP transport as opposed to the default (which is to use <see cref="T:System.Net.HttpWebRequest"/>). </para> <para> To use this, you need to pass an instance of the CFNetworkHandler to your HttpClient constructor, like this: </para> <example> <code lang="c#"> var client = new HttpClient (new CFNetworkHandler ()); </code> </example> <para> Using CFNetwork for your http client has the following differences from HttpWebRequest: (a) On iOS, CFNetwork will automatically turn on the phone's radio if it is off before starting the HTTP request. This means that it is not necessary to manually use the StartWWAN methods; (b) Connection pooling is managed by CFNetwork as opposed to the settings in .NET's stack; (c) Will automatically track proxy and network settings done to iOS; (d) Operations are performed on the CFNetwork dispatch queues/threads instead of consuming threads from Mono's own managed thread pool. </para> </remarks> </Docs> <Members> <Member MemberName=".ctor"> <MemberSignature Language="C#" Value="public CFNetworkHandler ();" /> <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor() cil managed" /> <MemberType>Constructor</MemberType> <AssemblyInfo> <AssemblyVersion>2.0.5.0</AssemblyVersion> </AssemblyInfo> <Parameters /> <Docs> <summary preserve-mono="true">Creates an instance of the CFNetwork-based http handler..</summary> <remarks></remarks> </Docs> </Member> <Member MemberName="AllowAutoRedirect"> <MemberSignature Language="C#" Value="public bool AllowAutoRedirect { get; set; }" /> <MemberSignature Language="ILAsm" Value=".property instance bool AllowAutoRedirect" /> <MemberType>Property</MemberType> <AssemblyInfo> <AssemblyVersion>2.0.5.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>System.Boolean</ReturnType> </ReturnValue> <Docs> <summary preserve-mono="true">Determines whether the request handler should follow redirects sent by the server.</summary> <value></value> <remarks></remarks> </Docs> </Member> <Member MemberName="Dispose"> <MemberSignature Language="C#" Value="protected override void Dispose (bool disposing);" /> <MemberSignature Language="ILAsm" Value=".method familyhidebysig virtual instance void Dispose(bool disposing) cil managed" /> <MemberType>Method</MemberType> <AssemblyInfo> <AssemblyVersion>2.0.5.0</AssemblyVersion> </AssemblyInfo> <ReturnValue> <ReturnType>System.Void</ReturnType> </ReturnValue> <Parameters> <Parameter Name="disposing" Type="System.Boolean" /> </Parameters> <Docs> <param name="disposing" preserve-mono="true">True if this is being called from Dispose(), false if it is being invoked by the finalizer.</param> <summary>Disposes this CFNetworkHandler.</summary> <remarks></remarks> </Docs> </Member> <Member MemberName="SendAsync"> <MemberSignature Language="C#" Value="protected override System.Threading.Tasks.Task&lt;System.Net.Http.HttpResponseMessage&gt; SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken);" /> <MemberSignature Language="ILAsm" Value=".method familyorassemblyhidebysig virtual instance class System.Threading.Tasks.Task`1&lt;class System.Net.Http.HttpResponseMessage&gt; SendAsync(class System.Net.Http.HttpRequestMessage request, valuetype System.Threading.CancellationToken cancellationToken) cil managed" /> <MemberType>Method</MemberType> <AssemblyInfo> <AssemblyVersion>2.0.5.0</AssemblyVersion> </AssemblyInfo> <Attributes> <Attribute> <AttributeName>System.Diagnostics.DebuggerStepThrough</AttributeName> </Attribute> <Attribute> <AttributeName>System.Runtime.CompilerServices.AsyncStateMachine(typeof(System.Net.Http.CFNetworkHandler/&lt;SendAsync&gt;c__async0))</AttributeName> </Attribute> </Attributes> <ReturnValue> <ReturnType>System.Threading.Tasks.Task&lt;System.Net.Http.HttpResponseMessage&gt;</ReturnType> </ReturnValue> <Parameters> <Parameter Name="request" Type="System.Net.Http.HttpRequestMessage" /> <Parameter Name="cancellationToken" Type="System.Threading.CancellationToken" /> </Parameters> <Docs> <param name="request" preserve-mono="true">The request to send.</param> <param name="cancellationToken" preserve-mono="true">Cancelation token to cancel the operation.</param> <summary preserve-mono="true">Sends the Http message asynchronously.</summary> <returns>Task representing the asynchronous operation.</returns> <remarks preserve-mono="true"> This method is invoked by the HttpClient, it is non-blocking. </remarks> </Docs> </Member> </Members> </Type>
{ "content_hash": "315b50b1ce51e31c41df103a26cd40fd", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 322, "avg_line_length": 45.89147286821706, "alnum_prop": 0.7027027027027027, "repo_name": "tunnelvisionlabs/dotnet-httpclient35", "id": "f714dec1a543caea45b6057a265edfa0c79ff1c9", "size": "5920", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "System.Net.Http/Documentation/en/System.Net.Http/CFNetworkHandler.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "460759" }, { "name": "Makefile", "bytes": "263" }, { "name": "PowerShell", "bytes": "3005" } ], "symlink_target": "" }
package com.github.javalbert.sqlbuilder.dsl; public interface ExpressionNode { public static final int EXPRESSION_OPERAND = 1; public static final int EXPRESSION_OPERATOR = 2; public static final int EXPRESSION_EXPRESSION = 3; default int getExpressionType() { return EXPRESSION_OPERAND; } }
{ "content_hash": "628904c27cbf0fc956cbf6a9c6f8b56d", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 51, "avg_line_length": 25.25, "alnum_prop": 0.7755775577557755, "repo_name": "Javalbert/sql-builder-orm", "id": "38221843474649591b466e3d2b4e44a40f7c1224", "size": "1049", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/github/javalbert/sqlbuilder/dsl/ExpressionNode.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "188508" }, { "name": "Java", "bytes": "772282" } ], "symlink_target": "" }
/** * List compiled by mystix on the extjs.com forums. * Thank you Mystix! * Slovak Translation by Michal Thomka * 14 April 2007 */ Ext.onReady(function() { if(Ext.Updater) { Ext.Updater.defaults.indicatorText = '<div class="loading-indicator">Nahrávam...</div>'; } if(Ext.view.View){ Ext.view.View.prototype.emptyText = ""; } if(Ext.grid.Panel){ Ext.grid.Panel.prototype.ddText = "{0} označených riadkov"; } if(Ext.TabPanelItem){ Ext.TabPanelItem.prototype.closeText = "Zavrieť túto záložku"; } if(Ext.form.field.Base){ Ext.form.field.Base.prototype.invalidText = "Hodnota v tomto poli je nesprávna"; } if(Ext.LoadMask){ Ext.LoadMask.prototype.msg = "Nahrávam..."; } if(Ext.Date) { Ext.Date.monthNames = [ "Január", "Február", "Marec", "Apríl", "Máj", "Jún", "Júl", "August", "September", "Október", "November", "December" ]; Ext.Date.dayNames = [ "Nedeľa", "Pondelok", "Utorok", "Streda", "Štvrtok", "Piatok", "Sobota" ]; } if(Ext.MessageBox){ Ext.MessageBox.buttonText = { ok : "OK", cancel : "Zrušiť", yes : "Áno", no : "Nie" }; } if(Ext.util.Format){ Ext.apply(Ext.util.Format, { thousandSeparator: '.', decimalSeparator: ',', currencySign: '\u20ac', // Slovakian Euro dateFormat: 'd.m.Y' }); } if(Ext.picker.Date){ Ext.apply(Ext.picker.Date.prototype, { todayText : "Dnes", minText : "Tento dátum je menší ako minimálny možný dátum", maxText : "Tento dátum je väčší ako maximálny možný dátum", disabledDaysText : "", disabledDatesText : "", monthNames : Ext.Date.monthNames, dayNames : Ext.Date.dayNames, nextText : 'Ďalší Mesiac (Control+Doprava)', prevText : 'Predch. Mesiac (Control+Doľava)', monthYearText : 'Vyberte Mesiac (Control+Hore/Dole pre posun rokov)', todayTip : "{0} (Medzerník)", format : "d.m.Y" }); } if(Ext.toolbar.Paging){ Ext.apply(Ext.PagingToolbar.prototype, { beforePageText : "Strana", afterPageText : "z {0}", firstText : "Prvá Strana", prevText : "Predch. Strana", nextText : "Ďalšia Strana", lastText : "Posledná strana", refreshText : "Obnoviť", displayMsg : "Zobrazujem {0} - {1} z {2}", emptyMsg : 'Žiadne dáta' }); } if(Ext.form.field.Text){ Ext.apply(Ext.form.field.Text.prototype, { minLengthText : "Minimálna dĺžka pre toto pole je {0}", maxLengthText : "Maximálna dĺžka pre toto pole je {0}", blankText : "Toto pole je povinné", regexText : "", emptyText : null }); } if(Ext.form.field.Number){ Ext.apply(Ext.form.field.Number.prototype, { minText : "Minimálna hodnota pre toto pole je {0}", maxText : "Maximálna hodnota pre toto pole je {0}", nanText : "{0} je nesprávne číslo" }); } if(Ext.form.field.Date){ Ext.apply(Ext.form.field.Date.prototype, { disabledDaysText : "Zablokované", disabledDatesText : "Zablokované", minText : "Dátum v tomto poli musí byť až po {0}", maxText : "Dátum v tomto poli musí byť pred {0}", invalidText : "{0} nie je správny dátum - musí byť vo formáte {1}", format : "d.m.Y" }); } if(Ext.form.field.ComboBox){ Ext.apply(Ext.form.field.ComboBox.prototype, { valueNotFoundText : undefined }); Ext.apply(Ext.form.field.ComboBox.prototype.defaultListConfig, { loadingText : "Nahrávam..." }); } if(Ext.form.field.VTypes){ Ext.apply(Ext.form.field.VTypes, { emailText : 'Toto pole musí byť e-mailová adresa vo formáte "user@example.com"', urlText : 'Toto pole musí byť URL vo formáte "http:/'+'/www.example.com"', alphaText : 'Toto pole može obsahovať iba písmená a znak _', alphanumText : 'Toto pole može obsahovať iba písmená, čísla a znak _' }); } if(Ext.grid.header.Container){ Ext.apply(Ext.grid.header.Container.prototype, { sortAscText : "Zoradiť vzostupne", sortDescText : "Zoradiť zostupne", lockText : "Zamknúť stľpec", unlockText : "Odomknúť stľpec", columnsText : "Stľpce" }); } if(Ext.grid.PropertyColumnModel){ Ext.apply(Ext.grid.PropertyColumnModel.prototype, { nameText : "Názov", valueText : "Hodnota", dateFormat : "d.m.Y" }); } if(Ext.layout.BorderLayout && Ext.layout.BorderLayout.SplitRegion){ Ext.apply(Ext.layout.BorderLayout.SplitRegion.prototype, { splitTip : "Potiahnite pre zmenu rozmeru", collapsibleSplitTip : "Potiahnite pre zmenu rozmeru. Dvojklikom schováte." }); } });
{ "content_hash": "c05ff673b708db056bf314ccf412b3f6", "timestamp": "", "source": "github", "line_count": 182, "max_line_length": 96, "avg_line_length": 30.494505494505493, "alnum_prop": 0.5212612612612613, "repo_name": "Nanonid/tcsolrsvc", "id": "7de828178b56e4348a52ba85a33a317b50a1fdac", "size": "6168", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webapps/owf/js-lib/ext-4.0.7/locale/ext-lang-sk.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "4651346" }, { "name": "Groovy", "bytes": "475503" }, { "name": "JavaScript", "bytes": "25903345" }, { "name": "Processing", "bytes": "334" }, { "name": "Python", "bytes": "467" }, { "name": "Ruby", "bytes": "15346" }, { "name": "Shell", "bytes": "83526" }, { "name": "XSLT", "bytes": "30318" } ], "symlink_target": "" }
package com.facebook.buck.jvm.java; import static com.facebook.buck.event.TestEventConfigurator.configureTestEvent; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertThat; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.BuildTargetFactory; import org.hamcrest.Matchers; import org.junit.Test; public class AnnotationProcessingEventTest { @Test public void testEquals() { BuildTarget target = BuildTargetFactory.newInstance("//fake:rule"); BuildTarget targetTwo = BuildTargetFactory.newInstance("//fake:rule2"); String annotationProcessorName = "com.facebook.FakeProcessor"; String annotationProcessorName2 = "com.facebook.FakeProcessor2"; AnnotationProcessingEvent.Started initStartedEventOne = configureTestEvent( AnnotationProcessingEvent.started( target, annotationProcessorName, AnnotationProcessingEvent.Operation.INIT, 0, false)); AnnotationProcessingEvent.Started initStartedEventTwo = configureTestEvent( AnnotationProcessingEvent.started( target, annotationProcessorName, AnnotationProcessingEvent.Operation.INIT, 0, false)); AnnotationProcessingEvent targetTwoInitStartedEvent = configureTestEvent( AnnotationProcessingEvent.started( targetTwo, annotationProcessorName, AnnotationProcessingEvent.Operation.INIT, 0, false)); AnnotationProcessingEvent annotationProcessorTwoInitStartedEvent = configureTestEvent( AnnotationProcessingEvent.started( target, annotationProcessorName2, AnnotationProcessingEvent.Operation.INIT, 0, false)); AnnotationProcessingEvent getSupportedOptionsStartedEvent = configureTestEvent( AnnotationProcessingEvent.started( target, annotationProcessorName, AnnotationProcessingEvent.Operation.GET_SUPPORTED_OPTIONS, 0, false)); AnnotationProcessingEvent finishedInitEventOne = configureTestEvent(AnnotationProcessingEvent.finished(initStartedEventOne)); AnnotationProcessingEvent finishedInitEventTwo = configureTestEvent(AnnotationProcessingEvent.finished(initStartedEventTwo)); assertEquals(initStartedEventOne, initStartedEventOne); assertNotEquals(initStartedEventOne, initStartedEventTwo); assertNotEquals(initStartedEventOne, targetTwoInitStartedEvent); assertNotEquals(initStartedEventOne, annotationProcessorTwoInitStartedEvent); assertNotEquals(initStartedEventOne, getSupportedOptionsStartedEvent); assertNotEquals(finishedInitEventOne, finishedInitEventTwo); assertThat(initStartedEventOne.isRelatedTo(finishedInitEventOne), Matchers.is(true)); assertThat(initStartedEventOne.isRelatedTo(finishedInitEventTwo), Matchers.is(false)); } }
{ "content_hash": "58ca716efa975aeb100b221bb22eb57b", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 90, "avg_line_length": 41.48051948051948, "alnum_prop": 0.7078897933625548, "repo_name": "clonetwin26/buck", "id": "fab46408424c53d23e0c598b2847070c712f5c9b", "size": "3799", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/com/facebook/buck/jvm/java/AnnotationProcessingEventTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "793" }, { "name": "Batchfile", "bytes": "2215" }, { "name": "C", "bytes": "263152" }, { "name": "C#", "bytes": "237" }, { "name": "C++", "bytes": "14997" }, { "name": "CSS", "bytes": "54894" }, { "name": "D", "bytes": "1017" }, { "name": "Go", "bytes": "4646" }, { "name": "Groovy", "bytes": "3362" }, { "name": "HTML", "bytes": "7248" }, { "name": "Haskell", "bytes": "971" }, { "name": "IDL", "bytes": "385" }, { "name": "Java", "bytes": "25118787" }, { "name": "JavaScript", "bytes": "933531" }, { "name": "Kotlin", "bytes": "19145" }, { "name": "Lex", "bytes": "2867" }, { "name": "Makefile", "bytes": "1816" }, { "name": "Matlab", "bytes": "47" }, { "name": "OCaml", "bytes": "4935" }, { "name": "Objective-C", "bytes": "160741" }, { "name": "Objective-C++", "bytes": "34" }, { "name": "PowerShell", "bytes": "244" }, { "name": "Prolog", "bytes": "858" }, { "name": "Python", "bytes": "1848054" }, { "name": "Roff", "bytes": "1207" }, { "name": "Rust", "bytes": "5199" }, { "name": "Scala", "bytes": "5046" }, { "name": "Shell", "bytes": "57970" }, { "name": "Smalltalk", "bytes": "3794" }, { "name": "Swift", "bytes": "10663" }, { "name": "Thrift", "bytes": "42010" }, { "name": "Yacc", "bytes": "323" } ], "symlink_target": "" }
angular.module(PKG.name + '.commons') .directive('myLogViewer', function ($filter, $timeout, $state, $location) { var capitalize = $filter('caskCapitalizeFilter'), filterFilter = $filter('filter'); return { restrict: 'E', scope: { params: '=' }, templateUrl: 'log-viewer/log-viewer.html', controller: function ($scope, myLogsApi, MyCDAPDataSource) { var dataSrc = new MyCDAPDataSource($scope); $scope.model = []; $scope.filters = 'all,info,warn,error,debug,other'.split(',') .map(function (key) { var p; switch(key) { case 'all': p = function() { return true; }; break; case 'other': p = function(line) { return !(/- (INFO|WARN|ERROR|DEBUG)/).test(line.log); }; break; default: p = function(line) { return (new RegExp('- '+key.toUpperCase())).test(line.log); }; } return { key: key, label: capitalize(key), entries: [], predicate: p }; }); $scope.$watch('model', function (newVal) { angular.forEach($scope.filters, function (one) { one.entries = filterFilter(newVal, one.predicate); }); }); var params = {}; var pollPromise = null; function pollForLogs(params) { var path = '/namespaces/' + params.namespace + '/apps/' + params.appId + '/' + params.programType + '/' + params.programId + '/runs/' + params.runId + '/logs/prev?max=50'; pollPromise = dataSrc.poll({ _cdapPath: path, interval: 3000 }, function (res) { $scope.model = res; if (res.length >= 50) { dataSrc.stopPoll(pollPromise.__pollId__); pollPromise = null; } }); } function initialize() { params = {}; angular.copy($scope.params, params); params.max = 50; params.scope = $scope; $scope.model = []; if (!params.runId) { return; } if (pollPromise) { dataSrc.stopPoll(pollPromise.__pollId__); pollPromise = null; } $scope.loadingNext = true; myLogsApi.prevLogs(params) .$promise .then(function (res) { $scope.model = res; if (res.length < 50) { pollForLogs(params); } $scope.loadingNext = false; }); } initialize(); $scope.$watch('params.runId', initialize); $scope.loadNextLogs = function () { if ($scope.loadingNext || $scope.loadingPrev) { return; } if (pollPromise) { dataSrc.stopPoll(pollPromise.__pollId__); pollPromise = null; } $scope.loadingNext = true; if ($scope.model.length) { params.fromOffset = $scope.model[$scope.model.length-1].offset; } myLogsApi.nextLogs(params) .$promise .then(function (res) { $scope.model = _.uniq($scope.model.concat(res)); $scope.loadingNext = false; }); }; $scope.loadPrevLogs = function () { if ($scope.loadingPrev || $scope.loadingNext) { return; } $scope.loadingPrev = true; if ($scope.model.length) { params.fromOffset = $scope.model[0].offset; } myLogsApi.prevLogs(params) .$promise .then(function (res) { $scope.model = _.uniq(res.concat($scope.model)); $scope.loadingPrev = false; $timeout(function() { var container = angular.element(document.querySelector('[infinite-scroll]'))[0]; var logItem = angular.element(document.getElementById(params.fromOffset))[0]; container.scrollTop = logItem.offsetTop; }); }); }; }, link: function (scope, element) { var termEl = angular.element(element[0].querySelector('.terminal')), QPARAM = 'filter'; scope.setFilter = function (k) { var f = filterFilter(scope.filters, {key:k}); scope.activeFilter = f.length ? f[0] : scope.filters[0]; $timeout(function(){ termEl.prop('scrollTop', termEl.prop('scrollHeight')); if(false === $state.current.reloadOnSearch) { var params = {}; params[QPARAM] = scope.activeFilter.key; $location.search(params); } }); }; scope.setFilter($state.params[QPARAM]); } }; });
{ "content_hash": "3e1722c7a7bc72226874b7baafe59113", "timestamp": "", "source": "github", "line_count": 180, "max_line_length": 99, "avg_line_length": 27.683333333333334, "alnum_prop": 0.47782460365241824, "repo_name": "chtyim/cdap", "id": "a454c0220af589e11fa6e845d664d3621d70613d", "size": "5580", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "cdap-ui/app/directives/log-viewer/log-viewer.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "13173" }, { "name": "CSS", "bytes": "219754" }, { "name": "HTML", "bytes": "455678" }, { "name": "Java", "bytes": "15847298" }, { "name": "JavaScript", "bytes": "1180404" }, { "name": "Python", "bytes": "102235" }, { "name": "Ruby", "bytes": "3178" }, { "name": "Scala", "bytes": "30340" }, { "name": "Shell", "bytes": "195815" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Ku.Core.Communication.SMS { public interface ISmsSender { Task<(bool success, string response)> Send(SmsObject sms); } }
{ "content_hash": "bb1871884658035e5fe8fd535bc64d6c", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 66, "avg_line_length": 20.833333333333332, "alnum_prop": 0.724, "repo_name": "kulend/Vino.Core.CMS", "id": "1800be6bb4afbb02b4d43500d439139f5039a21d", "size": "252", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/Ku.Core.Communication/SMS/ISmsSender.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "1304887" }, { "name": "CSS", "bytes": "21321" }, { "name": "JavaScript", "bytes": "1531549" }, { "name": "Smalltalk", "bytes": "48" } ], "symlink_target": "" }
import { EventEmitter, ChangeDetectorRef, OnDestroy, ElementRef } from '@angular/core'; /** * Count up component * * Loosely inspired by: * - https://github.com/izupet/angular2-counto * - https://inorganik.github.io/countUp.js/ * * @export * @class CountUpDirective */ export declare class CountUpDirective implements OnDestroy { private cd; countDuration: number; countPrefix: string; countSuffix: string; valueFormatting: any; countDecimals: number; countTo: any; countFrom: any; countChange: EventEmitter<{}>; countFinish: EventEmitter<{}>; nativeElement: any; value: any; formattedValue: string; private animationReq; private _countDecimals; private _countTo; private _countFrom; constructor(cd: ChangeDetectorRef, element: ElementRef); ngOnDestroy(): void; start(): void; }
{ "content_hash": "393020898f9a676ad561b2b72068dfc0", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 87, "avg_line_length": 26.363636363636363, "alnum_prop": 0.6873563218390805, "repo_name": "Luukschoen/ngx-frozen", "id": "277d7decf10d968efab64fc904eba8aed5c9b2d5", "size": "870", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "release/common/count/count.directive.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10554" }, { "name": "JavaScript", "bytes": "15738" }, { "name": "TypeScript", "bytes": "435716" } ], "symlink_target": "" }
[![Build Status](https://travis-ci.org/Acornsgrow/hitnmiss.svg?branch=master)](https://travis-ci.org/Acornsgrow/hitnmiss) [![Code Climate](https://codeclimate.com/github/Acornsgrow/hitnmiss/badges/gpa.svg)](https://codeclimate.com/github/Acornsgrow/hitnmiss) [![Test Coverage](https://codeclimate.com/github/Acornsgrow/hitnmiss/badges/coverage.svg)](https://codeclimate.com/github/Acornsgrow/hitnmiss/coverage) [![Issue Count](https://codeclimate.com/github/Acornsgrow/hitnmiss/badges/issue_count.svg)](https://codeclimate.com/github/Acornsgrow/hitnmiss) # Hitnmiss Hitnmiss is a Ruby gem that provides support for using the Repository pattern for read-through, write-behind caching in a thread-safe way. It is built heavily around using POROs (Plain Old Ruby Objects). This means it is intended to be used with all kinds of Ruby applications from plain Ruby command line tools, to framework (Rails, Sinatra, Rack, Hanami, etc.) based web apps, etc. Having defined repositories for accessing your caches aids in a number of ways. First, it centralizes cache key generation. Secondly, it centralizes & standardizes access to the cache rather than having code spread across your app duplicating key generation and access. Third, it provides clean separation between the cache persistence layer and the business representation. ## Installation Add this line to your application's Gemfile: ```ruby gem 'hitnmiss' ``` And then execute: $ bundle Or install it yourself as: $ gem install hitnmiss ## Define/Mixin a Repository Before you can use Hitnmiss to manage cache you first need to define a cache repository. This is done by defining a class for your repository and mixing the appropriate repository module in using `include`. Below, are explanations of the **Standard Repository** and the **Background Refresh Repository** so that you can decide which one fits your needs as well as learn how to use them. ### Standard Repository The standard repository module, `Hitnmiss::Repository`, fits the most common caching use case, the "Expiration Model". The "Expiration Model" is a caching model where a value gets cached with an associated expiration and when that expiration is reached that value is no longer cached. This affects the app behavior by having it pay the caching cost when it tries to get a value and it has expired. The following is an example of creating a `MostRecentPrice` cache repository for the "Expiration Model". ```ruby class MostRecentPrice include Hitnmiss::Repository default_expiration 134 # expiration in seconds from when value cached end ``` More often than not your caching use case will have a static/known expiration that you want to use for all values that get cached. This is handled for you by setting the `default_expiration` as seen in the example above. **Note:** Hitnmiss also supports being able to have different expirations for each cached value. You can learn more about this in the "Set Cache Source based Expiration" section. ### Background Refresh Repository Sometimes you don't have an expiration value and don't want cached values to disappear. In these scenarios you want something to update the cache for you based on some defined interval. When you use the `Hitnmiss::BackgroundRefreshRepository` module and set the `refresh_interval` as seen below, it prepares your repository to handle this scenario. This changes the behavior where the app never experiences the caching cost as it is continually managed for the app in the background based on the `refresh_interval`. ```ruby class MostRecentPrice include Hitnmiss::BackgroundRefreshRepository refresh_interval 60*5 # refresh interval in seconds end ``` Once you have defined your Background Refresh Repository in order to get the background process to update your cache you have to kick it off using the `background_refresh(*args, swallow_exceptions: [])` method as seen in the example below. The optional keyword argument `swallow_exceptions` defaults to `[]`. If enabled it will prevent the specified exceptions, raised in the `fetch(*args)` or `stale?(*args)` methods you defined, from killing the background thread, and prevent the exceptions from making their way up to the application. This is useful in scenarios where you want it to absorb say timeout exceptions, etc. and continue trucking along. **Note:** Any other exceptions not covered by the exceptions listed in the `swallow_exceptions` array will still be raised up into the application. ```ruby repository = MostRecentPrice.new repository.background_refresh(store_id) ``` This model also has the added benefit that the priming of the cache in the background refresh process is non-blocking. This means if you use this model the consumer will not experience the priming of the cache like they would with the Standard Repository's Expiration Model. #### Staleness Checking The Background Refresh Repository model introduces a new concept, Staleness Checking. Staleness is checked during the background refresh process. The way it works is if the cache is identified to be stale, then it primes the cache in the background, if the cache is identified to NOT be stale, then it sleeps for another `refresh_interval`. The stale checker, `stale?(*args)`, defaults to an always stale value of `true`. This causes the background refresh process to prime the cache every `refresh_interval`. If you want your cache implementation to be smarter and say validate a fingerprint or last modified value against the source, you can do it simply by overwriting the `stale?(*args)` method with your own staleness checking logic. The following is an example of this. ```ruby class MostRecentPrice include Hitnmiss::BackgroundRefreshRepository refresh_interval 60*5 # refresh interval in seconds def initialize @client = HTTPClient.new end def stale?(*args) hit_or_miss = get_from_cache(*args) if hit_or_miss.is_a?(Hitnmiss::Driver::Miss) return true elsif hit_or_miss.is_a?(Hitnmiss::Driver::Hit) url = "https://someresource.example.com/#{args[0]}/#{args[1]}/digest.json" res = @client.head(url) fingerprint = res.header['ETag'].first return false if fingerprint == hit_or_miss.fingerprint return true else raise Hitnmiss::Repository::UnsupportedDriverResponse.new("Driver '#{self.class.driver.inspect}' did not return an object of the support types (Hitnmiss::Driver::Hit, Hitnmiss::Driver::Miss)") end end end ``` ### Set a Repositories Cache Driver Hitnmiss defaults to the provided `Hitnmiss::InMemoryDriver`, but if an alternate driver is needed a new driver can be registered as seen below. ```ruby # config/hitnmiss.rb Hitnmiss.register_driver(:my_driver, SomeAlternativeDriver.new) ``` Once you have registered the new driver you can tell `Hitnmiss` what driver to use for this particular repository. The following is an example of how one would accomplish setting the repository driver to the driver that was just registered. ```ruby class MostRecentPrice include Hitnmiss::Repository driver :my_driver end ``` This works exactly the same with the `Hitnmiss::BackgroundRefreshRepository`. ### Set a Logger Hitnmiss defaults to not logging. However, if you would like to get detailed logging from Hitnmiss you can do so by passing your application controlled logger instance to the Hitnmiss repository. An example of this can be seen below. ```ruby class MostRecentPrice include Hitnmiss::Repository logger Logger.new(STDOUT) end ``` **Note:** The above works exactly the same way for `Hitnmiss::Repository` and `Hitnmiss::BackgroundRefreshRepository`. ### Use the File Driver Hitnmiss ships with an alternate file based driver that can be used to write cache values to individual files in a folder. ```ruby class MostRecentPrice include Hitnmiss::Repository driver Hitnmiss::FileDriver.new("some_cache_folder") end ``` ### Define Fetcher Methods You may be asking yourself, "How does the cache value get set?" Well, the answer is one of two ways. * Fetching an individual cacheable entity * Fetching all of the repository's cacheable entities Both of these scenarios are supported by defining the `fetch(*args)` method or the `fetch_all(keyspace)` method respectively in your cache repository class. See the following example. ```ruby class MostRecentPrice include Hitnmiss::Repository default_expiration 134 private def fetch(*args) # - do whatever to get the value you want to cache # - construct a Hitnmiss::Entity with the value Hitnmiss::Entity.new('some value') end def fetch_all(keyspace) # - do whatever to get the values you want to cache # - construct a collection of arguments and Hitnmiss entities [ { args: ['a', 'b'], entity: Hitnmiss::Entity.new('some value') }, { args: ['x', 'y'], entity: Hitnmiss::Entity.new('other value') } ] end end ``` The `fetch(*args)` method is responsible for obtaining the value that you want to cache by whatever means necessary and returning a `Hitnmiss::Entity` containing the value, and optionally an `expiration`, `fingerprint`, and `last_modified`. **Note:** The `*args` passed into the `fetch(*args)` method originate as the arguments that are passed into `prime` and `get` methods when they are called. For more context on `prime` and `get` please so [Priming an Entity](#priming-an-entity) and [Getting a Value](#getting-a-value) respectively. Defining the `fetch(*args)` method is **required** if you want to be able to cache values or get cached values using the `prime` or `get` methods. If you wish to support [priming the cache for an entire repository](#priming-the-entire-repository) using the `prime_all` method, you **must** define the `fetch_all(keyspace)` method on the repository class. This method **must** return a collection of hashes describing the `args` that would be used to get an entity and the corresponding `Hitnmiss::Entity`. See example above. #### Set Cache Source based Expiration In some cases you might need to set the expiration to be a different value for each cached value. This is generally needed when you get information back from a remote entity in the `fetch(*args)` method and you use it to compute the expiration. This for example could be via the `Expiration` header in an HTTP response. Once you have the expiration for that value you can set it by passing the expiration into the `Hitnmiss::Entity` constructor as seen below. **Note:** The expiration in the `Hitnmiss::Entity` will take precedence over the `default_expiration`. ```ruby class MostRecentPrice include Hitnmiss::Repository default_expiration 134 private def fetch(*args) # - do whatever to get the value you want to cache # - construct a Hitnmiss::Entity with the value and optionally a # result based expiration. If no result based expiration is # provided it will use the default_expiration. Hitnmiss::Entity.new('some value', expiration: 235) end end ``` #### Set Cache Source based Fingerprint In some cases you might want to set the fingerprint for the cached value. Doing so provides more flexibility to `Hitnmiss` in terms of determining staleness of cache. A very common example of this would be if you are fetching something over HTTP from the remote and the remote includes the `ETag` header. If you take the value of the `ETag` header (a fingerprint) and you set it in the `Hitnmiss::Entity` it can be used later on by `Hitnmiss` to aid in identifying staleness. Once you have obtained the fingerprint by whatever means you can set it by passing the fingerprint into the `Hitnmiss::Entity` constructor as seen below. ```ruby class MostRecentPrice include Hitnmiss::Repository default_expiration 134 private def fetch(*args) # - do whatever to get the value you want to cache # - do whatever to get the fingerprint of the value you want to cache # - construct a Hitnmiss::Entity with the value and optionally a # fingerprint. Hitnmiss::Entity.new('some value', fingerprint: "63478adce0dd0fbc82ef4bb1f1d64193") end end ``` #### Set Cache Source based Last Modified In some cases you might want to set the `last_modified` value for a cached value. Doing this provides more felxibility to `Hitnmiss` when trying to determine staleness of a cached item. A common example of this would be if you are fetching somthing over HTTP from a remote server and it includes the `Last-Modified` entity header in the response. If you took the value of the `Last-Modified` header and you set it in the `Hitnmiss::Entity` it can be used later on by `Hitnmiss` to aid in identifying staleness. Once you have obtained the `Last-Modified` value by whatever means you can set it by passing the `last_modified` option into the `Hitnmiss::Entity` constructor as seen below. ```ruby class MostRecentPrice include Hitnmiss::Repository default_expiration 134 private def fetch(*args) # - do whatever to get the value you want to cache # - do whatever to get the last modified of the value you want to cache # - construct a Hitnmiss::Entity with the value and optionally a # last_modified value. Hitnmiss::Entity.new('some value', last_modified: "2016-04-15T13:00:00Z") end end ``` ## Usage The following is a light breakdown of the various pieces of Hitnmiss and how to get going with them after defining your cache repository. ### Priming an entity Once you have defined the `fetch(*args)` method you can construct an instance of your cache repository and use it. One way you might want to use it is to force the repository to cache a value. This can be done using the `prime` method as seen below. ```ruby repository = MostRecentPrice.new repository.prime(current_user.id) # => cached_value ``` ### Priming the entire repository You can use the `prime_all` method to prime the entire repository. **Note:** The repository class must define the `fetch_all(keyspace)` method for this to work. See the "Define Fetcher Methods" section above for details. ```ruby repository = MostRecentPrice.new repository.prime_all # => [cached values, ...] ``` ### Getting a value You can also use your cache repository to get a particular cached value by doing the following. ```ruby repository = MostRecentPrice.new repository.get(current_user.id) # => cached_value ``` ### Deleting a cached value You can delete a cached value by calling the `delete` method with the same arguments used to get it. ```ruby repository = MostRecentPrice.new # cache some values ex: repository.prime(current_user.id) repository.delete(current_user.id) ``` ### Clearing a repository You can clear the entire repository of cached values by calling the `clear` method. ```ruby repository = MostRecentPrice.new # cache some values ex: repository.prime(current_user.id) repository.clear ``` ## Contributing If you are interested in contributing to Hitnmiss. There is a guide (both code and general help) over in [CONTRIBUTING](https://github.com/Acornsgrow/hitnmiss/blob/master/CONTRIBUTING.md). ## License The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
{ "content_hash": "c651ce6dc524c0bbe3eb71cc64183abb", "timestamp": "", "source": "github", "line_count": 428, "max_line_length": 198, "avg_line_length": 35.7196261682243, "alnum_prop": 0.761119832548404, "repo_name": "Acornsgrow/hitnmiss", "id": "2422259a6d4f6f126a27000d3c7d9f33fe5eb8de", "size": "15288", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "81997" }, { "name": "Shell", "bytes": "131" } ], "symlink_target": "" }
//Matt Schoen //5-29-2013 // // This software is the copyrighted material of its author, Matt Schoen, and his company Defective Studios. // It is available for sale on the Unity Asset store and is subject to their restrictions and limitations, as well as // the following: You shall not reproduce or re-distribute this software without the express written (e-mail is fine) // permission of the author. If permission is granted, the code (this file and related files) must bear this license // in its entirety. Anyone who purchases the script is welcome to modify and re-use the code at their personal risk // and under the condition that it not be included in any distribution builds. The software is provided as-is without // warranty and the author bears no responsibility for damages or losses caused by the software. // This Agreement becomes effective from the day you have installed, copied, accessed, downloaded and/or otherwise used // the software. #if UNITY_EDITOR #define DEV //Comment this out to not auto-populate scene merge using UnityEditor; using UnityEngine; using System.Collections.Generic; using System.IO; public class SceneMerge : EditorWindow { const string messagePath = "Assets/merges.txt"; public static Object mine, theirs; private static bool merged; //If these names end up conflicting with names within your scene, change them here public const string mineContainerName = "mine", theirsContainerName = "theirs"; public static GameObject mineContainer, theirsContainer; public static float colWidth; static SceneData mySceneData, theirSceneData; Vector2 scroll; [MenuItem("Window/UniMerge/Scene Merge %&m")] static void Init() { GetWindow(typeof(SceneMerge)); } #if DEV //If these names end up conflicting with names within your project, change them here public const string mineSceneName = "Mine", theirsSceneName = "Theirs"; void OnEnable() { //Get path #if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 //Unity 3 path stuff? #else string scriptPath = AssetDatabase.GetAssetPath(MonoScript.FromScriptableObject(this)); UniMergeConfig.DEFAULT_PATH = scriptPath.Substring(0, scriptPath.IndexOf("Editor") - 1); #endif if(Directory.Exists(UniMergeConfig.DEFAULT_PATH + "/Demo/Scene Merge")){ string[] assets = Directory.GetFiles(UniMergeConfig.DEFAULT_PATH + "/Demo/Scene Merge"); foreach(var asset in assets) { if(asset.EndsWith(".unity")) { if(asset.Contains(mineSceneName)) { mine = AssetDatabase.LoadAssetAtPath(asset.Replace('\\', '/'), typeof(Object)); } if(asset.Contains(theirsSceneName)) { theirs = AssetDatabase.LoadAssetAtPath(asset.Replace('\\', '/'), typeof(Object)); } } } } } #endif void OnGUI(){ #if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 //Layout fix for older versions? #else EditorGUIUtility.labelWidth = 100; #endif //Ctrl + w to close if(Event.current.Equals(Event.KeyboardEvent("^w"))) { Close(); GUIUtility.ExitGUI(); } /* * SETUP */ #if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 EditorGUIUtility.LookLikeControls(); #endif ObjectMerge.alt = false; //Adjust colWidth as the window resizes colWidth = (position.width - UniMergeConfig.midWidth*2 - UniMergeConfig.margin)/2; if(mine == null || theirs == null || mine.GetType() != typeof(Object) || mine.GetType() != typeof(Object) ) //|| !AssetDatabase.GetAssetPath(mine).Contains(".unity") || !AssetDatabase.GetAssetPath(theirs).Contains(".unity")) merged = GUI.enabled = false; if(GUILayout.Button("Merge")) { Merge(mine, theirs); GUIUtility.ExitGUI(); } GUI.enabled = merged; GUILayout.BeginHorizontal(); { GUI.enabled = mineContainer; if (!GUI.enabled) merged = false; if(GUILayout.Button("Unpack Mine")) { DestroyImmediate(theirsContainer); List<Transform> tmp = new List<Transform>(); foreach(Transform t in mineContainer.transform) tmp.Add(t); foreach(Transform t in tmp) t.parent = null; DestroyImmediate(mineContainer); mySceneData.ApplySettings(); } GUI.enabled = theirsContainer; if (!GUI.enabled) merged = false; if(GUILayout.Button("Unpack Theirs")) { DestroyImmediate(mineContainer); List<Transform> tmp = new List<Transform>(); foreach(Transform t in theirsContainer.transform) tmp.Add(t); foreach(Transform t in tmp) t.parent = null; DestroyImmediate(theirsContainer); theirSceneData.ApplySettings(); } } GUILayout.EndHorizontal(); GUI.enabled = true; ObjectMerge.DrawRowHeight(); GUILayout.BeginHorizontal(); { GUILayout.BeginVertical(GUILayout.Width(colWidth)); { #if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 mine = EditorGUILayout.ObjectField("Mine", mine, typeof(Object)); #else mine = EditorGUILayout.ObjectField("Mine", mine, typeof(Object), true); #endif } GUILayout.EndVertical(); GUILayout.Space(UniMergeConfig.midWidth*2); GUILayout.BeginVertical(GUILayout.Width(colWidth)); { #if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 theirs = EditorGUILayout.ObjectField("Theirs", theirs, typeof(Object)); #else theirs = EditorGUILayout.ObjectField("Theirs", theirs, typeof(Object), true); #endif } GUILayout.EndVertical(); } GUILayout.EndHorizontal(); if(mine == null || theirs == null) merged = false; if(merged) { scroll = GUILayout.BeginScrollView(scroll); //Fog ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments { indent = 0, colWidth = colWidth, compare = delegate { bool same = GenericCompare(); if(same) same = mySceneData.fog == theirSceneData.fog; return same; }, left = delegate { if(mine) mySceneData.fog = EditorGUILayout.Toggle("Fog", mySceneData.fog); }, leftButton = delegate { mySceneData.fog = theirSceneData.fog; }, rightButton = delegate { theirSceneData.fog = mySceneData.fog; }, right = delegate { if(theirs) theirSceneData.fog = EditorGUILayout.Toggle("Fog", theirSceneData.fog); }, drawButtons = mine && theirs }); //Fog Color ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments { indent = 0, colWidth = colWidth, compare = delegate { bool same = GenericCompare(); if(same) same = mySceneData.fogColor == theirSceneData.fogColor; return same; }, left = delegate { if(mine) mySceneData.fogColor = EditorGUILayout.ColorField("Fog Color", mySceneData.fogColor); }, leftButton = delegate { mySceneData.fogColor = theirSceneData.fogColor; }, rightButton = delegate { theirSceneData.fogColor = mySceneData.fogColor; }, right = delegate { if(theirs) theirSceneData.fogColor = EditorGUILayout.ColorField("Fog Color", theirSceneData.fogColor); }, drawButtons = mine && theirs }); //Fog Mode ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments { indent = 0, colWidth = colWidth, compare = delegate { bool same = GenericCompare(); if(same) same = mySceneData.fogMode == theirSceneData.fogMode; return same; }, left = delegate { if(mine) mySceneData.fogMode = (FogMode)EditorGUILayout.EnumPopup("Fog Mode", mySceneData.fogMode); }, leftButton = delegate { mySceneData.fogMode = theirSceneData.fogMode; }, rightButton = delegate { theirSceneData.fogMode = mySceneData.fogMode; }, right = delegate { if(theirs) theirSceneData.fogMode = (FogMode)EditorGUILayout.EnumPopup("Fog Mode", theirSceneData.fogMode); }, drawButtons = mine && theirs }); //Fog Density ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments { indent = 0, colWidth = colWidth, compare = delegate { bool same = GenericCompare(); if(same) same = mySceneData.fogDensity == theirSceneData.fogDensity; return same; }, left = delegate { if(mine) mySceneData.fogDensity = EditorGUILayout.FloatField("Linear Density", mySceneData.fogDensity); }, leftButton = delegate { mySceneData.fogDensity = theirSceneData.fogDensity; }, rightButton = delegate { theirSceneData.fogDensity = mySceneData.fogDensity; }, right = delegate { if(theirs) theirSceneData.fogDensity = EditorGUILayout.FloatField("Linear Density", theirSceneData.fogDensity); }, drawButtons = mine && theirs }); //Linear Fog Start ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments { indent = 0, colWidth = colWidth, compare = delegate { bool same = GenericCompare(); if(same) same = mySceneData.fogStartDistance == theirSceneData.fogStartDistance; return same; }, left = delegate { if(mine) mySceneData.fogStartDistance = EditorGUILayout.FloatField("Linear Fog Start", mySceneData.fogStartDistance); }, leftButton = delegate { mySceneData.fogStartDistance = theirSceneData.fogStartDistance; }, rightButton = delegate { theirSceneData.fogStartDistance = mySceneData.fogStartDistance; }, right = delegate { if(theirs) theirSceneData.fogStartDistance = EditorGUILayout.FloatField("Linear Fog Start", theirSceneData.fogStartDistance); }, drawButtons = mine && theirs }); //Linear Fog End ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments { indent = 0, colWidth = colWidth, compare = delegate { bool same = GenericCompare(); if(same) same = mySceneData.fogEndDistance == theirSceneData.fogEndDistance; return same; }, left = delegate { if(mine) mySceneData.fogEndDistance = EditorGUILayout.FloatField("Linear Fog End", mySceneData.fogEndDistance); }, leftButton = delegate { mySceneData.fogEndDistance = theirSceneData.fogEndDistance; }, rightButton = delegate { theirSceneData.fogEndDistance = mySceneData.fogEndDistance; }, right = delegate { if(theirs) theirSceneData.fogEndDistance = EditorGUILayout.FloatField("Linear Fog End", theirSceneData.fogEndDistance); }, drawButtons = mine && theirs }); //Ambient Light ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments { indent = 0, colWidth = colWidth, compare = delegate { bool same = GenericCompare(); if(same) same = mySceneData.ambientLight == theirSceneData.ambientLight; return same; }, left = delegate { if(mine) mySceneData.ambientLight = EditorGUILayout.ColorField("Ambient Light", mySceneData.ambientLight); }, leftButton = delegate { mySceneData.ambientLight = theirSceneData.ambientLight; }, rightButton = delegate { theirSceneData.ambientLight = mySceneData.ambientLight; }, right = delegate { if(theirs) theirSceneData.ambientLight = EditorGUILayout.ColorField("Ambient Light", theirSceneData.ambientLight); }, drawButtons = mine && theirs }); //Skybox ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments { indent = 0, colWidth = colWidth, compare = delegate { bool same = GenericCompare(); if(same) same = mySceneData.skybox == theirSceneData.skybox; return same; }, left = delegate { if(mine) #if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 mySceneData.skybox = (Material)EditorGUILayout.ObjectField("Skybox Material", mySceneData.skybox, typeof(Material)); #else mySceneData.skybox = (Material)EditorGUILayout.ObjectField("Skybox Material", mySceneData.skybox, typeof(Material), false); #endif }, leftButton = delegate { mySceneData.skybox = theirSceneData.skybox; }, rightButton = delegate { theirSceneData.skybox = mySceneData.skybox; }, right = delegate { if(theirs) #if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 theirSceneData.skybox = (Material)EditorGUILayout.ObjectField("Skybox Material", theirSceneData.skybox, typeof(Material)); #else theirSceneData.skybox = (Material)EditorGUILayout.ObjectField("Skybox Material", theirSceneData.skybox, typeof(Material), false); #endif }, drawButtons = mine && theirs }); //Halo Strength ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments { indent = 0, colWidth = colWidth, compare = delegate { bool same = GenericCompare(); if(same) same = mySceneData.haloStrength == theirSceneData.haloStrength; return same; }, left = delegate { if(mine) mySceneData.haloStrength = EditorGUILayout.FloatField("Halo Strength", mySceneData.haloStrength); }, leftButton = delegate { mySceneData.haloStrength = theirSceneData.haloStrength; }, rightButton = delegate { theirSceneData.haloStrength = mySceneData.haloStrength; }, right = delegate { if(theirs) theirSceneData.haloStrength = EditorGUILayout.FloatField("Halo Strength", theirSceneData.haloStrength); }, drawButtons = mine && theirs }); //Flare Strength ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments { indent = 0, colWidth = colWidth, compare = delegate { bool same = GenericCompare(); if(same) same = mySceneData.flareStrength == theirSceneData.flareStrength; return same; }, left = delegate { if(mine) mySceneData.flareStrength = EditorGUILayout.FloatField("Flare Strength", mySceneData.flareStrength); }, leftButton = delegate { mySceneData.flareStrength = theirSceneData.flareStrength; }, rightButton = delegate { theirSceneData.flareStrength = mySceneData.flareStrength; }, right = delegate { if(theirs) theirSceneData.flareStrength = EditorGUILayout.FloatField("Flare Strength", theirSceneData.flareStrength); }, drawButtons = mine && theirs }); //Flare Fade Speed ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments { indent = 0, colWidth = colWidth, compare = delegate { bool same = GenericCompare(); if(same) same = mySceneData.flareFadeSpeed == theirSceneData.flareFadeSpeed; return same; }, left = delegate { if(mine) mySceneData.flareFadeSpeed = EditorGUILayout.FloatField("Flare Fade Speed", mySceneData.flareFadeSpeed); }, leftButton = delegate { mySceneData.flareFadeSpeed = theirSceneData.flareFadeSpeed; }, rightButton = delegate { theirSceneData.flareFadeSpeed = mySceneData.flareFadeSpeed; }, right = delegate { if(theirs) theirSceneData.flareFadeSpeed = EditorGUILayout.FloatField("Flare Fade Speed", theirSceneData.flareFadeSpeed); }, drawButtons = mine && theirs }); GUILayout.EndScrollView(); } } static bool GenericCompare() { bool same = mine; if(same) same = theirs; return same; } public static void CLIIn() { string[] args = System.Environment.GetCommandLineArgs(); foreach(string arg in args) Debug.Log(arg); Merge(args[args.Length - 2], args[args.Length - 1]); } void Update() { TextAsset mergeFile = (TextAsset)AssetDatabase.LoadAssetAtPath(messagePath, typeof(TextAsset)); if(mergeFile) { string[] files = mergeFile.text.Split('\n'); AssetDatabase.DeleteAsset(messagePath); foreach(string file in files) Debug.Log(file); //TODO: Add prefab case DoMerge(files); } } public static void DoMerge(string[] paths) { if(paths.Length > 2) { Merge(paths[0], paths[1]); } else Debug.LogError("need at least 2 paths, " + paths.Length + " given"); } public static void Merge(Object myScene, Object theirScene) { if(myScene == null || theirScene == null) return; Merge(AssetDatabase.GetAssetPath(myScene), AssetDatabase.GetAssetPath(theirScene)); } public static void Merge(string myPath, string theirPath) { if(string.IsNullOrEmpty(myPath) || string.IsNullOrEmpty(theirPath)) return; if(AssetDatabase.LoadAssetAtPath(myPath, typeof(Object)) && AssetDatabase.LoadAssetAtPath(theirPath, typeof(Object))) { if(EditorApplication.SaveCurrentSceneIfUserWantsTo()) { //Load "theirs" to get RenderSettings, etc. EditorApplication.OpenScene(theirPath); theirSceneData.ambientLight = RenderSettings.ambientLight; #if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 #else theirSceneData.flareFadeSpeed = RenderSettings.flareFadeSpeed; #endif theirSceneData.flareStrength = RenderSettings.flareStrength; theirSceneData.fog = RenderSettings.fog; theirSceneData.fogColor = RenderSettings.fogColor; theirSceneData.fogDensity = RenderSettings.fogDensity; theirSceneData.fogEndDistance = RenderSettings.fogEndDistance; theirSceneData.fogMode = RenderSettings.fogMode; theirSceneData.fogStartDistance = RenderSettings.fogStartDistance; theirSceneData.haloStrength = RenderSettings.haloStrength; theirSceneData.skybox = RenderSettings.skybox; //Load "mine" to start the merge EditorApplication.OpenScene(myPath); mySceneData.ambientLight = RenderSettings.ambientLight; #if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 #else mySceneData.flareFadeSpeed = RenderSettings.flareFadeSpeed; #endif mySceneData.flareStrength = RenderSettings.flareStrength; mySceneData.fog = RenderSettings.fog; mySceneData.fogColor = RenderSettings.fogColor; mySceneData.fogDensity = RenderSettings.fogDensity; mySceneData.fogEndDistance = RenderSettings.fogEndDistance; mySceneData.fogMode = RenderSettings.fogMode; mySceneData.fogStartDistance = RenderSettings.fogStartDistance; mySceneData.haloStrength = RenderSettings.haloStrength; mySceneData.skybox = RenderSettings.skybox; mineContainer = new GameObject {name = mineContainerName}; GameObject[] allObjects = (GameObject[])Resources.FindObjectsOfTypeAll(typeof(GameObject)); #if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 foreach(GameObject obj in allObjects) { if(obj.transform.parent == null && EditorUtility.GetPrefabType(obj) != PrefabType.Prefab && EditorUtility.GetPrefabType(obj) != PrefabType.ModelPrefab && obj.hideFlags == 0) //Want a better way to filter out "internal" objects obj.transform.parent = mineContainer.transform; } #else foreach(GameObject obj in allObjects) { if(obj.transform.parent == null && PrefabUtility.GetPrefabType(obj) != PrefabType.Prefab && PrefabUtility.GetPrefabType(obj) != PrefabType.ModelPrefab && obj.hideFlags == 0) //Want a better way to filter out "internal" objects obj.transform.parent = mineContainer.transform; } #endif EditorApplication.OpenSceneAdditive(theirPath); theirsContainer = new GameObject {name = theirsContainerName}; allObjects = (GameObject[])Resources.FindObjectsOfTypeAll(typeof(GameObject)); #if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 foreach(GameObject obj in allObjects) { if(obj.transform.parent == null && obj.name != mineContainerName && EditorUtility.GetPrefabType(obj) != PrefabType.Prefab && EditorUtility.GetPrefabType(obj) != PrefabType.ModelPrefab && obj.hideFlags == 0) //Want a better way to filter out "internal" objects obj.transform.parent = theirsContainer.transform; } #else foreach(GameObject obj in allObjects) { if(obj.transform.parent == null && obj.name != mineContainerName && PrefabUtility.GetPrefabType(obj) != PrefabType.Prefab && PrefabUtility.GetPrefabType(obj) != PrefabType.ModelPrefab && obj.hideFlags == 0) //Want a better way to filter out "internal" objects obj.transform.parent = theirsContainer.transform; } #endif GetWindow(typeof(ObjectMerge)); ObjectMerge.mine = mineContainer; ObjectMerge.theirs = theirsContainer; merged = true; } } } } public struct SceneData { public Color ambientLight, fogColor; public float flareFadeSpeed, flareStrength, fogDensity, fogEndDistance, fogStartDistance, haloStrength; public bool fog; public FogMode fogMode; public Material skybox; //Hmm... can't get at haloTexture or spotCookie //public Texture haloTexture, spotCookie; public void ApplySettings() { RenderSettings.ambientLight = ambientLight; RenderSettings.fogColor = fogColor; #if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 #else RenderSettings.flareFadeSpeed = flareFadeSpeed; #endif RenderSettings.flareStrength = flareStrength; RenderSettings.fogDensity = fogDensity; RenderSettings.fogEndDistance = fogEndDistance; RenderSettings.fogStartDistance = fogStartDistance; RenderSettings.haloStrength = haloStrength; RenderSettings.fog = fog; RenderSettings.fogMode = fogMode; RenderSettings.skybox = skybox; } } #endif
{ "content_hash": "9955e5bcf6ba94d6ca2d3feed08a3643", "timestamp": "", "source": "github", "line_count": 609, "max_line_length": 144, "avg_line_length": 35.32348111658457, "alnum_prop": 0.6930550390479733, "repo_name": "Zeropointstudios/Hybrid_Skies", "id": "f73adc79b14170fa6f6fdeb6b87af5af4705864f", "size": "21512", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Plugins/UniMerge/Editor/SceneMerge.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "488924" }, { "name": "JavaScript", "bytes": "2436" }, { "name": "Python", "bytes": "2357" } ], "symlink_target": "" }
import List from './List'; import Loader from './Loader'; import ThirdLoader from './ThirdLoader' export default { components: { listA: { creator: List, args: [document.getElementById('a'), {$ref: 'loader'}] }, listB: { creator: List, args: [document.getElementById('b'), {$ref: 'thirdLoader'}] }, loader: { creator: Loader, args: ['list.json'] }, thirdLoader: { creator: ThirdLoader } } };
{ "content_hash": "8c4a58f9423b7ca0680548873c2da1ad", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 71, "avg_line_length": 23.782608695652176, "alnum_prop": 0.4826325411334552, "repo_name": "ecomfe/uioc", "id": "3a8b14a1184fbe2c3ee5fe5d0ed8a22bf8d9b785", "size": "547", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "examples/simple-es6-module/src/config.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "3150" }, { "name": "JavaScript", "bytes": "154204" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>equations: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.13.2 / equations - 1.2~beta+8.8</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> equations <small> 1.2~beta+8.8 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-03-31 07:41:49 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-31 07:41:49 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.13.2 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.08.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.08.1 Official release 4.08.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; authors: [ &quot;Matthieu Sozeau &lt;matthieu.sozeau@inria.fr&gt;&quot; &quot;Cyprien Mangin &lt;cyprien.mangin@m4x.org&gt;&quot; ] dev-repo: &quot;git+https://github.com/mattam82/Coq-Equations.git&quot; maintainer: &quot;matthieu.sozeau@inria.fr&quot; homepage: &quot;https://mattam82.github.io/Coq-Equations&quot; bug-reports: &quot;https://github.com/mattam82/Coq-Equations/issues&quot; license: &quot;LGPL 2.1&quot; build: [ [&quot;coq_makefile&quot; &quot;-f&quot; &quot;_CoqProject&quot; &quot;-o&quot; &quot;Makefile&quot;] [make &quot;-j%{jobs}%&quot;] ] install: [ [make &quot;install&quot;] ] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Equations&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8.1&quot; &amp; &lt; &quot;8.9&quot;} ] synopsis: &quot;A function definition package for Coq&quot; description: &quot;&quot;&quot; Equations is a function definition plugin for Coq, that allows the definition of functions by dependent pattern-matching and well-founded, mutual or nested structural recursion and compiles them into core terms. It automatically derives the clauses equations, the graph of the function and its associated elimination principle.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/mattam82/Coq-Equations/archive/v1.2-beta-8.8.tar.gz&quot; checksum: &quot;md5=1cc8f9edbc55ac189dfd1471a77c3863&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-equations.1.2~beta+8.8 coq.8.13.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.13.2). The following dependencies couldn&#39;t be met: - coq-equations -&gt; coq &lt; 8.9 -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-equations.1.2~beta+8.8</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "a72ed96c58f405e927b3f21869198fe3", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 159, "avg_line_length": 42.02298850574713, "alnum_prop": 0.5545678336980306, "repo_name": "coq-bench/coq-bench.github.io", "id": "6a08cdc003d26a3afae96662e67d5cdd29e11f73", "size": "7337", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.08.1-2.0.5/released/8.13.2/equations/1.2~beta+8.8.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<footer class="container"> <div class="site-footer"> <div class="copyright pull-left"> <!-- 请不要更改这一行 方便其他人知道模板的来源 谢谢 --> <!-- Please keep this line to let others know where this theme comes from. Thank you :D --> Power by <a href="https://github.com/DONGChuan/Yummy-Jekyll">Yummy Jekyll</a> </div> <a href="https://github.com/vincentfeng" target="_blank" aria-label="view source code"> <span class="mega-octicon octicon-mark-github" title="GitHub"></span> </a> <div class="pull-right"> <a href="javascript:window.scrollTo(0,0)" >TOP</a> </div> </div> <!-- Third-Party JS --> <script type="text/javascript" src="/bower_components/geopattern/js/geopattern.min.js"></script> <!-- My JS --> <script type="text/javascript" src="/assets/js/script.js"></script> {% for javascript in page.javascript %} <script src="/assets/js/{{javascript}}"></script> {% endfor %} {% if site.analytics.google.tracking_id %} <!-- Google Analytics --> <div style="display:none"> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '{{ site.analytics.google.tracking_id }}', 'auto'); ga('send', 'pageview'); </script> </div> {% endif %} </footer>
{ "content_hash": "12a101452c7de6c3c43c95a8c0bd5efe", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 103, "avg_line_length": 35.91489361702128, "alnum_prop": 0.5633886255924171, "repo_name": "vincentfeng/vincentfeng.github.io", "id": "22e1c8784004f0512fe40e122fab36c394e6e199", "size": "1732", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_includes/footer.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11393" }, { "name": "HTML", "bytes": "22691" }, { "name": "JavaScript", "bytes": "408" }, { "name": "Ruby", "bytes": "4095" } ], "symlink_target": "" }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.envirocar.aggregation; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URISyntaxException; import java.net.URL; import java.nio.channels.Channels; import java.nio.file.CopyOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Properties; import java.util.UUID; import java.util.function.Consumer; import java.util.logging.Level; import javax.servlet.ServletInputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author matthes */ public class Util { private static final Logger logger = LoggerFactory.getLogger(Util.class); public static Collection<Properties> getAlgorithmConfigurations() throws IOException { URL res = Util.class.getResource("/algorithm_instances/README.md"); final List<Properties> props = new ArrayList<>(); if (res != null) { try { Path instanceReadme = Paths.get(res.toURI()); if (Files.exists(instanceReadme)) { Files.newDirectoryStream(instanceReadme.getParent(), "*.{properties}").forEach(new Consumer<Path>() { @Override public void accept(Path t) { Properties p = new Properties(); try { p.load(Files.newBufferedReader(t)); props.add(p); } catch (IOException ex) { logger.warn("Could not load algorithm instnace: "+p, ex); } } }); } } catch (URISyntaxException ex) { throw new IOException(ex); } } return props; } static Path writeToTempFile(InputStream inputStream) throws IOException { Path target = Files.createTempFile(UUID.randomUUID().toString(), ".json"); Files.copy(inputStream, target, StandardCopyOption.REPLACE_EXISTING); return target; } }
{ "content_hash": "7423f20b16345ef0b168798105ae766d", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 121, "avg_line_length": 33.25333333333333, "alnum_prop": 0.603448275862069, "repo_name": "enviroCar/enviroCar-aggregation", "id": "fdf91eb3d8a25412ded0bc69f896a77047502826", "size": "3141", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webapp/src/main/java/org/envirocar/aggregation/Util.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "120722" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright 2014-2016 CyberVision, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/sliding_panel" android:layout_width="match_parent" android:layout_height="match_parent"> <FrameLayout android:id="@+id/contentLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentTop="true" android:layout_above="@+id/music_track_view" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:orientation="vertical"> <org.kaaproject.kaa.demo.iotworld.smarthome.widget.AutoSpanRecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone" android:scrollbars="vertical"/> <TextView android:id="@+id/noDataText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="22sp" android:textColor="?android:attr/textColorSecondary" android:layout_gravity="center" android:visibility="visible" /> </FrameLayout> <org.kaaproject.kaa.demo.iotworld.smarthome.widget.MusicTrackWidget android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:id="@id/music_track_view" /> </RelativeLayout>
{ "content_hash": "5e6c27543b8673d23712e345fb736275", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 83, "avg_line_length": 42.353846153846156, "alnum_prop": 0.6240464947330185, "repo_name": "maxml/sample-apps", "id": "0118a3731176a38b2d3372f3c0f9c718f8b949cd", "size": "2753", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "iotworld/source/smarthome/android/res/layout/fragment_music_albums_device.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "23868" }, { "name": "C", "bytes": "5016986" }, { "name": "C++", "bytes": "420951" }, { "name": "CMake", "bytes": "52788" }, { "name": "HTML", "bytes": "1482" }, { "name": "Java", "bytes": "2114878" }, { "name": "JavaScript", "bytes": "4701" }, { "name": "Makefile", "bytes": "9995" }, { "name": "Objective-C", "bytes": "382359" }, { "name": "Shell", "bytes": "73744" } ], "symlink_target": "" }
package ui; import javafx.event.Event; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; /** * Creates sidebar that contains menu */ public class Sidebar extends VBox implements EventHandler { private Hyperlink tasksLink = new Hyperlink("Tasks"); private Hyperlink employeesLink = new Hyperlink("Employees"); private Hyperlink skillsLink = new Hyperlink("Skills"); private Hyperlink projectsLink = new Hyperlink("Projects"); private Hyperlink visitedPageLink = tasksLink; private Sidebar() { this.setPadding(new Insets(0)); this.setSpacing(0); this.getStyleClass().add("sidebar"); this.setMinWidth(110); this.setWidth(110); this.setMaxWidth(110); Label title = new Label("Menu"); title.getStyleClass().add("menu-title"); title.setAlignment(Pos.TOP_LEFT); title.prefWidthProperty().bind(this.widthProperty()); this.getChildren().add(title); tasksLink.setOnAction(this); employeesLink.setOnAction(this); skillsLink.setOnAction(this); projectsLink.setOnAction(this); Hyperlink pageHyperlinks[] = new Hyperlink[] { tasksLink, employeesLink, skillsLink, projectsLink }; for (int i=0; i<pageHyperlinks.length; i++) { this.getChildren().add(pageHyperlinks[i]); pageHyperlinks[i].getStyleClass().add("sidebar-item"); pageHyperlinks[i].setPadding(new Insets(0, 0, 0, 8)); if (pageHyperlinks[i].equals(tasksLink)) { pageHyperlinks[i].getStyleClass().add("menu-item-clicked"); } else { pageHyperlinks[i].getStyleClass().add("menu-item-non-clicked"); } pageHyperlinks[i].prefWidthProperty().bind(this.widthProperty()); } } public static Sidebar getInstance() { return new Sidebar(); } @Override public void handle(Event event) { visitedPageLink.getStyleClass().remove("menu-item-clicked"); ((Hyperlink) event.getSource()).getStyleClass().remove("menu-item-non-clicked"); ((Hyperlink) event.getSource()).getStyleClass().add("menu-item-clicked"); if (event.getSource()==tasksLink) { MainUI.borderPane.setCenter(TasksPage.getInstance()); MainUI.borderPane.setRight(TasksPage.getInstance().addCard()); TasksPage.getInstance().table.refresh(); } else if (event.getSource() == employeesLink) { MainUI.borderPane.setCenter(EmployeesPage.getInstance()); MainUI.borderPane.setRight(EmployeesPage.getInstance().addCard()); EmployeesPage.getInstance().table.refresh(); } else if (event.getSource() == projectsLink) { MainUI.borderPane.setCenter(ProjectsPage.getInstance()); MainUI.borderPane.setRight(ProjectsPage.getInstance().addCard()); ProjectsPage.getInstance().table.refresh(); } else if (event.getSource() == skillsLink) { MainUI.borderPane.setCenter(SkillsPage.getInstance()); MainUI.borderPane.setRight(SkillsPage.getInstance().addCard()); SkillsPage.getInstance().table.refresh(); } visitedPageLink = (Hyperlink)event.getSource(); } }
{ "content_hash": "9247e4dbc4599c13be10502416118c02", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 88, "avg_line_length": 38.30107526881721, "alnum_prop": 0.6406513194834362, "repo_name": "AinurMakhmet/allsys-standalone", "id": "37c8d41c3bad30efba18b4f8145f825fdee8261c", "size": "3562", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/ui/Sidebar.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3379" }, { "name": "HTML", "bytes": "188" }, { "name": "Java", "bytes": "219975" } ], "symlink_target": "" }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var schema = []; var create = function create(context) { var globalScope = void 0; // do nearly the same thing that eslint does for config globals // https://github.com/eslint/eslint/blob/v2.0.0/lib/eslint.js#L118-L194 var makeDefined = function makeDefined(ident) { var ii = void 0; // start from the right since we're going to remove items from the array for (ii = globalScope.through.length - 1; ii >= 0; ii--) { var ref = globalScope.through[ii]; if (ref.identifier.name === ident.name) { // use "__defineGeneric" since we don't have a reference to "escope.Variable" // eslint-disable-next-line no-underscore-dangle globalScope.__defineGeneric(ident.name, globalScope.set, globalScope.variables); var variable = globalScope.set.get(ident.name); variable.writeable = false; // "through" contains all references whose definition cannot be found // so we need to update references and remove the ones that were added globalScope.through.splice(ii, 1); ref.resolved = variable; variable.references.push(ref); } } }; return { ClassImplements(node) { makeDefined(node.id); }, DeclareInterface(node) { makeDefined(node.id); }, DeclareTypeAlias(node) { makeDefined(node.id); }, GenericTypeAnnotation(node) { if (node.id.type === 'Identifier') { makeDefined(node.id); } else if (node.id.type === 'QualifiedTypeIdentifier') { var qid = void 0; qid = node.id; do { qid = qid.qualification; } while (qid.qualification); makeDefined(qid); } }, // Can be removed once https://github.com/babel/babel-eslint/pull/696 is published OpaqueType(node) { if (node.id.type === 'Identifier') { makeDefined(node.id); } }, Program() { globalScope = context.getScope(); }, TypeParameterDeclaration(node) { node.params.forEach(function (param) { makeDefined(param); }); } }; }; exports.default = { create, schema }; module.exports = exports.default;
{ "content_hash": "bbe4cf931500cecba19c0d39049907af", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 88, "avg_line_length": 27.08433734939759, "alnum_prop": 0.6152135231316725, "repo_name": "BigBoss424/portfolio", "id": "fe343fe4c2a7314d8e5698236cc9b103123aa8a5", "size": "2248", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "v7/development/node_modules/eslint-plugin-flowtype/dist/rules/defineFlowType.js", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<Workflow xmlns="urn:wexflow-schema" id="4" name="Workflow_FilesMover" description="Workflow_FilesMover"> <Settings> <Setting name="launchType" value="trigger" /> <Setting name="enabled" value="true" /> </Settings> <Tasks> <Task id="1" name="FilesLoader" description="Loading files" enabled="true"> <Setting name="file" value="/opt/wexflow/WexflowTesting/file10.txt" /> </Task> <Task id="2" name="FilesMover" description="Moving files to FilesMover folder" enabled="true"> <Setting name="selectFiles" value="1" /> <Setting name="destFolder" value="/opt/wexflow/WexflowTesting/FilesMover/" /> <Setting name="overwrite" value="true" /> </Task> </Tasks> </Workflow>
{ "content_hash": "058ff735053a686cf5984ffbb2dfc869", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 105, "avg_line_length": 43.1875, "alnum_prop": 0.6989869753979739, "repo_name": "aelassas/Wexflow", "id": "7f0ead0bf810dda0f48b2da5af21e61b777fa43b", "size": "691", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "samples/netcore/linux/Wexflow/Workflows/Workflow_FilesMover.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "23783" }, { "name": "C#", "bytes": "2722280" }, { "name": "CSS", "bytes": "24134" }, { "name": "Dockerfile", "bytes": "794" }, { "name": "HTML", "bytes": "45720" }, { "name": "Inno Setup", "bytes": "120128" }, { "name": "Java", "bytes": "42544" }, { "name": "JavaScript", "bytes": "302348" }, { "name": "Objective-C", "bytes": "142" }, { "name": "Swift", "bytes": "31730" } ], "symlink_target": "" }
package mireka.smtp.address.parser.base; import java.text.MessageFormat; import java.text.ParseException; import java.util.List; public abstract class Token { public int position; public Token(int position) { this.position = position; } public abstract List<CharToken> getSpellingTokens(); public ParseException syntaxException(Object expected) { return new ParseException("Syntax error. Expected: " + expected + ", received: " + toString() + " at character position " + position + ".", position); } public ParseException otherSyntaxException(String sentence) { String formattedMessage = MessageFormat.format(sentence, this); return new ParseException("Syntax error. " + formattedMessage + " Character position: " + position + ".", position); } /** * Returns the token in a readable format which can be used in error * messages. */ @Override public abstract String toString(); }
{ "content_hash": "5556588c890ef065da506ca2e36cfb54", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 73, "avg_line_length": 29.314285714285713, "alnum_prop": 0.6539961013645225, "repo_name": "hontvari/mireka", "id": "edf93c4b1c60a2845918b1ab140b6e8ffc69dc60", "size": "1026", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/mireka/smtp/address/parser/base/Token.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "184" }, { "name": "HTML", "bytes": "57358" }, { "name": "Java", "bytes": "733844" }, { "name": "JavaScript", "bytes": "21941" }, { "name": "Shell", "bytes": "7251" } ], "symlink_target": "" }
<link rel="import" href="../bower_components/polymer/polymer.html"> <link rel="import" href="../bower_components/iron-ajax/iron-ajax.html"> <link rel="import" href="../bower_components/iron-input/iron-input.html"> <link rel="import" href="../bower_components/iron-label/iron-label.html"> <link rel="import" href="../bower_components/iron-list/iron-list.html"> <link rel="import" href="../bower_components/poly-filter/poly-filter.html"> <link rel="import" href="../bower_components/paper-material/paper-material.html"> <link rel="import" href="../bower_components/paper-card/paper-card.html"> <link rel="import" href="../bower_components/iron-localstorage/iron-localstorage.html"> <!-- jukebox elements --> <link rel="import" href="jukebox-control-element.html"> <link rel="import" href="jukebox-login.html"> <dom-module id="jukebox-element"> <template> <style> .item { @apply(--layout-horizontal); cursor: pointer; padding: 10px 15px; border-bottom: 1px solid #DDD; font-size: 0.875em; } .item:focus, .item.selected:focus { outline: 0; background-color: #ddd; } .item.selected { background-color: var(--google-grey-300); border-bottom: 1px solid #ccc; } .iron-selected { background: #eee; } iron-list { height: 400px; } </style> <jukebox-login token="{{token}}" hidden$="{{token}}"></jukebox-login> <iron-localstorage name="token" value="{{token}}"></iron-localstorage> <div style="display: flex; height: 100%;"> <div style="width: 50%;"> <audio src="" id="player" on-ended="handleEnded" on-abort="handledEnded" on-error="handleEnded"></audio> <iron-ajax id="ajax" url="/playlist" last-response="{{playlist}}" handle-as="json" headers$='{"Authorization" :"Bearer {{token}}"}' auto="{{token}}"> </iron-ajax> <poly-filter array-to-filter="[[playlist]]" filter="[[filterString]]" filtered-array="{{filteredPlaylist}}"> </poly-filter> <jukebox-control-element id="control" on-next-tap="handleNext" on-prev-tap="handlePrev" on-stop-tap="handleStop" on-play-tap="handlePlay" on-pause-tap="handlePause"> </jukebox-control-element> <paper-material elevation="1"> <div class="item"> <iron-label>Search <input is="iron-input" type="string" value="{{filterString::input}}" autofocus></iron-label> </div> <iron-list items="[[filteredPlaylist]]" as="song" id="playlist" selection-enabled> <template> <div index$="[[index]]" selected$="[[selected]]" artist="[[song.artist]]" title="[[song.title]]" url="[[song.url]]" class$="[[_computedClass(selected)]]" on-tap="_itemSelected">[[song.artist]] - [[song.title]] </div> </template> </iron-list> </paper-material> </div> <div style="width: 50%;"> <paper-card heading="Up next"></paper-card> <paper-material elevation="1"> <iron-list items="[[playNext]]" as="song" id="playlistNext"> <template> <div index$="[[index]]" artist="[[song.artist]]" title="[[song.title]]" url="[[song.url]]?auth={{token}}" class="item">[[song.artist]] - [[song.title]] </div> </template> </iron-list> </paper-material> </div> </div> </template> <script> (function(win, doc, undefined){ Polymer({ is: 'jukebox-element', properties: { token: { type: String, notify: true, value: '' }, playNext: { type: Array, value: [] } }, listeners: { 'logout': '_logout' }, _logout: function() { this.token = ''; }, handlePlay: function(e) { this.$.player.load(); this.$.player.play(); }, handleEnded: function(e) { this.handleNext(e); }, handleNext: function (e) { if (this.playNext[0] !== undefined) { this.splice('playNext',0,1); } if (this.playNext[0] !== undefined) { console.log('Play deck not empty'); this.$.player.src = this.playNext[0].url + '?auth='+this.token; this.$.control.song = this.playNext[0]; this.$.player.load(); this.$.player.play(); } else { console.log('Play deck empty'); if (this.$.playlist.items != null) { var track = Math.floor(Math.random() * this.$.playlist.items.length); this.$.player.src = this.$.playlist.items[track].url +'?auth='+this.token; this.$.control.song = this.$.playlist.items[track]; this.$.playlist.selectItem(track); this.$.playlist.scrollToIndex(track); this.$.player.load(); this.$.player.play(); this.push('playNext',this.$.playlist.items[track]); } else { console.log('playlist empty'); } } }, handlePause: function (e) { if (this.$.player.paused == true) { this.$.player.play(); } else { this.$.player.pause(); } }, _itemSelected: function(e) { this.push('playNext',e.model.song); }, _computedClass: function(isSelected) { var classes = 'item'; if (isSelected) { classes += ' selected'; } return classes; }, }) })(window, document); </script> </dom-module>
{ "content_hash": "97b66c2d705cd01a4446608692091d31", "timestamp": "", "source": "github", "line_count": 186, "max_line_length": 135, "avg_line_length": 40.38709677419355, "alnum_prop": 0.40947816826411076, "repo_name": "marksteele/emusak", "id": "8c7b62cc03f31096e673de3ea9c367080424d76e", "size": "7512", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/app/elements/jukebox-element.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "622" }, { "name": "Erlang", "bytes": "15937" }, { "name": "HTML", "bytes": "20857" }, { "name": "JavaScript", "bytes": "3185" }, { "name": "Makefile", "bytes": "120" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "87231caaf06ed77033a42cc85bf80e80", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "8764ce521082035fdf2326a851d4f1b5887f0085", "size": "196", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Rhynchospora/Rhynchospora inundata/ Syn. Rhynchospora macrostachya inundata/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import { SET_SETTING } from '../constants'; export default function setting(state = {}, action) { switch (action.type) { case SET_SETTING: return { ...state, ['ssr']: action.payload.value, }; default: return state; } }
{ "content_hash": "a2be89c563f9899d40a03b6b757d77ed", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 53, "avg_line_length": 20.46153846153846, "alnum_prop": 0.556390977443609, "repo_name": "luanlv/comhoavang", "id": "e2499b176b6db997fce500e6da068ae4d6438c00", "size": "266", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/reducers/setting.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "695835" }, { "name": "Dockerfile", "bytes": "278" }, { "name": "HTML", "bytes": "623615" }, { "name": "JavaScript", "bytes": "5924440" }, { "name": "PHP", "bytes": "4314" } ], "symlink_target": "" }
namespace device { namespace { template <typename Set> bool SetsEqual(const Set& lhs, const Set& rhs) { // Since sets order elements via an operator, std::equal doesn't work. It // would require elements to be equal-comparable. Check if symmetric // difference is empty instead. std::vector<typename Set::value_type> symmetric_difference; std::set_symmetric_difference(lhs.begin(), lhs.end(), rhs.begin(), rhs.end(), std::back_inserter(symmetric_difference), typename Set::value_compare()); return symmetric_difference.empty(); } } // namespace FakePositionCache::FakePositionCache() = default; FakePositionCache::~FakePositionCache() = default; void FakePositionCache::CachePosition(const WifiData& wifi_data, const mojom::Geoposition& position) { data.push_back(std::make_pair(wifi_data, position)); } const mojom::Geoposition* FakePositionCache::FindPosition( const WifiData& wifi_data) const { auto it = std::find_if( data.begin(), data.end(), [&wifi_data](const auto& candidate_pair) { return SetsEqual(wifi_data.access_point_data, candidate_pair.first.access_point_data); }); return it == data.end() ? nullptr : &(it->second); } size_t FakePositionCache::GetPositionCacheSize() const { return data.size(); } const mojom::Geoposition& FakePositionCache::GetLastUsedNetworkPosition() const { return last_used_position; } void FakePositionCache::SetLastUsedNetworkPosition( const mojom::Geoposition& position) { last_used_position = position; } } // namespace device
{ "content_hash": "1fd661f173856d86de6c9e0a597b0b92", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 79, "avg_line_length": 33.28, "alnum_prop": 0.6724759615384616, "repo_name": "endlessm/chromium-browser", "id": "6d2d35d477ac37f96616dd772264eff8c5d7cbb4", "size": "2030", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "services/device/geolocation/fake_position_cache.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
require 'util/postgres_admin' module MiqServer::LogManagement extend ActiveSupport::Concern included do belongs_to :log_file_depot, :class_name => "FileDepot" has_many :log_files, :dependent => :destroy, :as => :resource end def format_log_time(time) time.respond_to?(:strftime) ? time.strftime("%Y%m%d_%H%M%S") : "unknown" end def post_historical_logs(taskid, log_depot) task = MiqTask.find(taskid) resource = who_am_i # Post all compressed logs for a specific date + configs, creating a new row per day VMDB::Util.compressed_log_patterns.each do |pattern| evm = VMDB::Util.get_evm_log_for_date(pattern) next if evm.nil? log_start, log_end = VMDB::Util.get_log_start_end_times(evm) date = File.basename(pattern).gsub!(/\*|\.gz/, "") date_string = "#{format_log_time(log_start)} #{format_log_time(log_end)}" unless log_start.nil? && log_end.nil? date_string ||= date name = "Archived #{self.name} logs #{date_string} " desc = "Logs for Zone #{zone.name rescue nil} Server #{self.name} #{date_string}" cond = {:historical => true, :name => name, :state => 'available'} cond[:logging_started_on] = log_start unless log_start.nil? cond[:logging_ended_on] = log_end unless log_end.nil? logfile = log_files.find_by(cond) if logfile && logfile.log_uri.nil? _log.info("Historical logfile already exists with id: [#{logfile.id}] for [#{resource}] dated: [#{date}] with contents from: [#{log_start}] to: [#{log_end}]") next else logfile = LogFile.historical_logfile end msg = "Creating historical Logfile for [#{resource}] dated: [#{date}] from: [#{log_start}] to [#{log_end}]" task.update_status("Active", "Ok", msg) _log.info(msg) begin log_files << logfile save msg = "Zipping and posting historical logs and configs on #{resource}" task.update_status("Active", "Ok", msg) _log.info(msg) patterns = [pattern] cfg_pattern = ::Settings.log.collection.archive.pattern patterns += cfg_pattern if cfg_pattern.kind_of?(Array) local_file = VMDB::Util.zip_logs("evm_server_daily.zip", patterns, "admin") logfile.update_attributes( :file_depot => log_depot, :local_file => local_file, :logging_started_on => log_start, :logging_ended_on => log_end, :name => name, :description => desc, :miq_task_id => task.id ) logfile.upload rescue StandardError, Timeout::Error => err logfile.update_attributes(:state => "error") _log.error("Posting of historical logs failed for #{resource} due to error: [#{err.class.name}] [#{err}]") raise end msg = "Historical log files from #{resource} for #{date} are posted" task.update_status("Active", "Ok", msg) _log.info(msg) # TODO: If the gz has been posted and the gz is more than X days old, delete it end end def _post_my_logs(options) # Make the request to the MiqServer whose logs are needed MiqQueue.put_or_update( :class_name => self.class.name, :instance_id => id, :method_name => "post_logs", :server_guid => guid, :zone => my_zone, ) do |msg, item| _log.info("Previous adhoc log collection is still running, skipping...Resource: [#{self.class.name}], id: [#{id}]") unless msg.nil? item.merge( :miq_callback => options.delete(:callback), :msg_timeout => options.delete(:timeout), :priority => MiqQueue::HIGH_PRIORITY, :args => [options]) end end def synchronize_logs(*args) options = args.extract_options! args << self unless args.last.kind_of?(self.class) LogFile.logs_from_server(*args, options) end def last_log_sync_on log_files.maximum(:updated_on) end def last_log_sync_message last_log = log_files.order(:updated_on => :desc).first last_log.try(:miq_task).try!(:message) end def post_logs(options) taskid = options[:taskid] task = MiqTask.find(taskid) context_log_depot = log_depot(options[:context]) # the current queue item and task must be errored out on exceptions so re-raise any caught errors raise _("Log depot settings not configured") unless context_log_depot context_log_depot.update_attributes(:support_case => options[:support_case].presence) post_historical_logs(taskid, context_log_depot) unless options[:only_current] post_current_logs(taskid, context_log_depot) task.update_status("Finished", "Ok", "Log files were successfully collected") end def current_log_patterns # use an array union to add pg log path patterns if not already there ::Settings.log.collection.current.pattern | pg_log_patterns end def pg_data_dir PostgresAdmin.data_directory end def pg_log_patterns pg_data = pg_data_dir return [] unless pg_data pg_data = Pathname.new(pg_data) [pg_data.join("*.conf"), pg_data.join("pg_log/*")] end def post_current_logs(taskid, log_depot) resource = who_am_i task = MiqTask.find(taskid) delete_old_requested_logs logfile = LogFile.current_logfile logfile.update_attributes(:miq_task_id => taskid) begin log_files << logfile save log_prefix = "Task: [#{task.id}]" msg = "Posting logs for: #{resource}" _log.info("#{log_prefix} #{msg}") task.update_status("Active", "Ok", msg) msg = "Zipping and posting current logs and configs on #{resource}" _log.info("#{log_prefix} #{msg}") task.update_status("Active", "Ok", msg) local_file = VMDB::Util.zip_logs("evm.zip", current_log_patterns, "system") evm = VMDB::Util.get_evm_log_for_date("log/*.log") log_start, log_end = VMDB::Util.get_log_start_end_times(evm) date_string = "#{format_log_time(log_start)} #{format_log_time(log_end)}" unless log_start.nil? && log_end.nil? name = "Requested #{self.name} logs #{date_string} " desc = "Logs for Zone #{zone.name rescue nil} Server #{self.name} #{date_string}" logfile.update_attributes( :file_depot => log_depot, :local_file => local_file, :logging_started_on => log_start, :logging_ended_on => log_end, :name => name, :description => desc, ) logfile.upload rescue StandardError, Timeout::Error => err _log.error("#{log_prefix} Posting of current logs failed for #{resource} due to error: [#{err.class.name}] [#{err}]") logfile.update_attributes(:state => "error") raise end msg = "Current log files from #{resource} are posted" _log.info("#{log_prefix} #{msg}") task.update_status("Active", "Ok", msg) end def delete_old_requested_logs log_files.where(:historical => false).destroy_all end def delete_active_log_collections_queue MiqQueue.put_or_update( :class_name => self.class.name, :instance_id => id, :method_name => "delete_active_log_collections", :server_guid => guid ) do |msg, item| _log.info("Previous cleanup is still running, skipping...") unless msg.nil? item.merge(:priority => MiqQueue::HIGH_PRIORITY) end end def delete_active_log_collections log_files.each do |lf| if lf.state == 'collecting' _log.info("Deleting #{lf.description}") lf.miq_task.update_attributes(:state => 'Finished', :status => 'Error', :message => 'Log Collection Incomplete during Server Startup') unless lf.miq_task.nil? lf.destroy end end # Since a task is created before a logfile, there's a chance we have a task without a logfile MiqTask.where(:miq_server_id => id).where("name like ?", "Zipped log retrieval for %").where("state != ?", "Finished").each do |task| task.update_attributes(:state => 'Finished', :status => 'Error', :message => 'Log Collection Incomplete during Server Startup') end end def log_collection_active_recently?(since = nil) since ||= 15.minutes.ago.utc return true if log_files.exists?(["created_on > ? AND state = ?", since, "collecting"]) MiqTask.exists?(["miq_server_id = ? and name like ? and state != ? and created_on > ?", id, "Zipped log retrieval for %", "Finished", since]) end def log_collection_active? return true if log_files.exists?(:state => "collecting") MiqTask.exists?(["miq_server_id = ? and name like ? and state != ?", id, "Zipped log retrieval for %", "Finished"]) end def log_depot(context) context == "Zone" ? zone.log_file_depot : log_file_depot end def base_zip_log_name t = Time.now.utc.strftime('%FT%H_%M_%SZ'.freeze) # Name the file based on GUID and time. GUID and Date/time of the request are as close to unique filename as we're going to get "App-#{guid}-#{t}" end end
{ "content_hash": "d48481c90c444786215de392a2ca55b1", "timestamp": "", "source": "github", "line_count": 249, "max_line_length": 166, "avg_line_length": 36.321285140562246, "alnum_prop": 0.6219593100398054, "repo_name": "fbladilo/manageiq", "id": "d723ea0c975200e0be21c65878403dcd8b05a926", "size": "9044", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "app/models/miq_server/log_management.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "2167" }, { "name": "JavaScript", "bytes": "183" }, { "name": "PowerShell", "bytes": "2644" }, { "name": "Ruby", "bytes": "10494037" }, { "name": "Shell", "bytes": "2696" } ], "symlink_target": "" }
require 'rubygems' gem 'templater', '>= 0.5.0' require 'templater' module SousChef VERSION = '0.0.1' autoload :ApplicationTask, File.join(File.dirname(__FILE__), 'sous-chef', 'application_task') autoload :NodeTask, File.join(File.dirname(__FILE__), 'sous-chef', 'node_task') end path = File.join(File.dirname(__FILE__)) require File.join(path, 'sous-chef', 'generator') require File.join(path, 'generators', 'application') require File.join(path, 'generators', 'cookbook') require File.join(path, 'generators', 'node') require File.join(path, 'generators', 'file') require File.join(path, 'generators', 'template')
{ "content_hash": "09cb6d6a23fb177ae78741c2438768d8", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 96, "avg_line_length": 33.31578947368421, "alnum_prop": 0.6951026856240127, "repo_name": "benburkert/sous-chef", "id": "7d49183ca72e346236265a9d71d93abaa48348d0", "size": "633", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/sous-chef.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "10711" } ], "symlink_target": "" }
package com.google.tsunami.plugins.detectors.rce.java; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableList.toImmutableList; import com.google.common.collect.ImmutableList; import com.google.common.flogger.GoogleLogger; import com.google.protobuf.util.Timestamps; import com.google.tsunami.common.data.NetworkEndpointUtils; import com.google.tsunami.common.data.NetworkServiceUtils; import com.google.tsunami.common.time.UtcClock; import com.google.tsunami.plugin.PluginType; import com.google.tsunami.plugin.VulnDetector; import com.google.tsunami.plugin.annotations.PluginInfo; import com.google.tsunami.proto.DetectionReport; import com.google.tsunami.proto.DetectionReportList; import com.google.tsunami.proto.DetectionStatus; import com.google.tsunami.proto.NetworkService; import com.google.tsunami.proto.Severity; import com.google.tsunami.proto.TargetInfo; import com.google.tsunami.proto.Vulnerability; import com.google.tsunami.proto.VulnerabilityId; import java.net.MalformedURLException; import java.time.Clock; import java.time.Instant; import java.util.UUID; import javax.inject.Inject; import javax.management.MBeanServerConnection; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; /** A {@link VulnDetector} that detects unprotected Java JMX servers. */ @PluginInfo( type = PluginType.VULN_DETECTION, name = "JavaJmxRceDetector", version = "0.1", description = "This detector checks for unprotected Java JMX servers with RMI endpoint.", author = "Tsunami Team (tsunami-dev@google.com)", bootstrapModule = JavaJmxRceDetectorBootstrapModule.class) public final class JavaJmxRceDetector implements VulnDetector { private static final GoogleLogger logger = GoogleLogger.forEnclosingClass(); private final Clock utcClock; @Inject JavaJmxRceDetector(@UtcClock Clock utcClock) { this.utcClock = checkNotNull(utcClock); } @Override public DetectionReportList detect( TargetInfo targetInfo, ImmutableList<NetworkService> matchedServices) { logger.atInfo().log("JavaJmxRceDetector starts detecting."); return DetectionReportList.newBuilder() .addAllDetectionReports( matchedServices.stream() .filter(JavaJmxRceDetector::isRmiOrUnknownService) .filter(JavaJmxRceDetector::isServiceVulnerable) .map(networkService -> buildDetectionReport(targetInfo, networkService)) .collect(toImmutableList())) .build(); } private static boolean isServiceVulnerable(NetworkService networkService) { // First create an URL for the JMX service according to // https://docs.oracle.com/javase/8/docs/technotes/guides/management/agent.html#gdfci JMXServiceURL serviceURL; String urlString = "service:jmx:rmi:///jndi/rmi://" + NetworkEndpointUtils.toUriAuthority(networkService.getNetworkEndpoint()) + "/jmxrmi"; try { serviceURL = new JMXServiceURL(urlString); } catch (MalformedURLException ex) { logger.atSevere().log("Invalid URL string for Java JMX service: %s", urlString); return false; } // Second try connecting to the service without any auth config. This can only succeed if the // service is a JMX server and unprotected. try (JMXConnector connector = JMXConnectorFactory.connect(serviceURL)) { connector.connect(); MBeanServerConnection serverConnection = connector.getMBeanServerConnection(); // Finally try creating an MBean with class javax.management.loading.MLet, which would allow // us instantiating arbitrary MBeans from a remote URL. See // https://www.optiv.com/explore-optiv-insights/blog/exploiting-jmx-rmi. ObjectName objectName = new ObjectName("MLet#" + UUID.randomUUID(), "id", "1"); serverConnection.createMBean("javax.management.loading.MLet", objectName); logger.atInfo().log("Successfully created a MLet MBean on JMX service %s", urlString); // Delete the created MBean. serverConnection.unregisterMBean(objectName); return true; } catch (Exception ex) { logger.atFine().log("Failed to run JavaJmxRceDetector for service: %s", urlString); } return false; } private DetectionReport buildDetectionReport( TargetInfo targetInfo, NetworkService vulnerableNetworkService) { return DetectionReport.newBuilder() .setTargetInfo(targetInfo) .setNetworkService(vulnerableNetworkService) .setDetectionTimestamp(Timestamps.fromMillis(Instant.now(utcClock).toEpochMilli())) .setDetectionStatus(DetectionStatus.VULNERABILITY_VERIFIED) .setVulnerability( Vulnerability.newBuilder() .setMainId( VulnerabilityId.newBuilder() .setPublisher("GOOGLE") .setValue("JAVA_UNPROTECTED_JMX_RMI_SERVER")) .setSeverity(Severity.CRITICAL) .setTitle("Unprotected Java JMX RMI Server") .setDescription( "Java Management Extension (JMX) allows remote monitoring and diagnostics for" + " Java applications. Running JMX with unprotected RMI endpoint allows" + " any remote users to create a javax.management.loading.MLet MBean and" + " use it to create new MBeans from arbitrary URLs.") .setRecommendation( "Enable authentication and upgrade to the latest JDK environment.")) .build(); } /** * Checks whether the network service is a Java RMI service or unknown. * * <p>Tsunami currently runs the port scanner nmap with version detection intensity set to 5, * which isn't high enough to detect Java RMI services. Therefore we run this detector for * "java-rmi" services as well as network service whose service name is empty. */ private static boolean isRmiOrUnknownService(NetworkService networkService) { return networkService.getServiceName().isEmpty() || NetworkServiceUtils.getServiceName(networkService).equals("java-rmi"); } }
{ "content_hash": "f9fc68fd20c167214ccbecd9bf473361", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 98, "avg_line_length": 44.851063829787236, "alnum_prop": 0.7224857685009488, "repo_name": "google/tsunami-security-scanner-plugins", "id": "416d0ca520196c7273581159bfc48542aa34a29c", "size": "6913", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "google/detectors/rce/java_jmx/src/main/java/com/google/tsunami/plugins/detectors/rce/java/JavaJmxRceDetector.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1753015" }, { "name": "Python", "bytes": "7400" }, { "name": "Shell", "bytes": "10263" } ], "symlink_target": "" }
<?php namespace NSONE; use NSONE\Rest\Records; class RecordException extends \Exception { } class Record extends DataObject { public $domain = NULL; public $type = NULL; protected $rest = NULL; protected $parentZone = NULL; public function __construct($config, $parentZone, $domain, $type) { parent::__construct(); $this->rest = new Records($config); $this->parentZone = $parentZone; if (strstr($domain, $parentZone->zone) === false) $domain .= '.'.$parentZone->zone; $this->domain = $domain; $this->type = $type; } public function reload() { return $this->load(true); } public function load($reload=false) { if (!$reload && !empty($this->data)) throw new RecordException('record already loaded'); $this->data = $this->rest->retrieve($this->parentZone->zone, $this->domain, $this->type); return $this; } public function delete() { if (empty($this->data)) throw new RecordException('record not loaded'); $this->rest->delete($this->parentZone->zone, $this->domain, $this->type); $this->data = array(); } public function update($options) { if (empty($this->data)) throw new RecordException('record not loaded'); $this->data = $this->rest->update($this->parentZone->zone, $this->domain, $this->type, $options); return $this; } public function create($options) { if (!empty($this->data)) throw new RecordException('record already loaded'); $this->data = $this->rest->create($this->parentZone->zone, $this->domain, $this->type, $options); return $this; } // qps // usage // addAnswers }
{ "content_hash": "466529d63ce951d5711573f486a61ae8", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 105, "avg_line_length": 25.92753623188406, "alnum_prop": 0.5762996087199553, "repo_name": "ns1/nsone-php", "id": "67ad2f2965db97a340b083ecd88c3ca3d1b6df47", "size": "1901", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Record.php", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "27" }, { "name": "PHP", "bytes": "28578" } ], "symlink_target": "" }
CLASS({ package: 'foam.memento', name: 'MemorableTrait', properties: [ { name: 'memento', hidden: true } ], methods: { init: function(args) { this.SUPER(args); var properties = this.model_.getRuntimeProperties(); for ( var i = 0, prop ; prop = properties[i] ; i++ ) { if ( ! prop.memorable ) continue; this.addPropertyListener(prop.name, this.updateMemento); if ( this[prop.name] != null && this[prop.name].model_ && typeof this[prop.name].memento !== 'undefined' ) { this[prop.name].addPropertyListener('memento', this.updateMemento); } } this.addPropertyListener('memento', this.updateFromMemento); if ( this.hasOwnProperty('memento') ) { this.updateFromMemento(null, null, null, this.memento); } else { this.updateMemento(); } }, toMemento_: function() { var memento = { __proto__: MementoProto }; var properties = this.model_.getRuntimeProperties(); for ( var i = 0, prop ; prop = properties[i] ; i ++ ) { if ( ! prop.memorable ) continue; if ( this[prop.name] != null ) { var key = typeof prop.memorable === 'string' ? prop.memorable : prop.name; var value = this[prop.name]; if (prop.toMemento) { memento[key] = prop.toMemento(value); } else { memento[key] = typeof value.memento !== 'undefined' ? value.memento : (value.toMemento ? value.toMemento() : value.toString()); } } } return memento; } }, listeners: [ { name: 'updateFromMemento', code: function(src, topic, old, memento) { if ( this.mementoFeedback_ || !memento ) { return; } var properties = this.model_.getRuntimeProperties(); for ( var i = 0, prop ; prop = properties[i] ; i++ ) { if (prop.memorable) { var key = typeof prop.memorable === 'string' ? prop.memorable : prop.name; var value = prop.fromMemento ? prop.fromMemento(memento[key]) : memento[key]; if (this[prop.name].memento$) { this[prop.name].memento = value; } else { this[prop.name] = value; } } } } }, { name: 'updateMemento', code: function(src, topic, old, nu) { // If the new property value is a memorable modelled object // then we need to subscribe for changes to that object. if ( src === this && old && old.model_ && old.memento ) { old.removePropertyListener('memento', this.updateMemento); } if ( src === this && nu && nu.model_ && nu.memento ) { nu.addPropertyListener('memento', this.updateMemento); } this.mementoFeedback_ = true; this.memento = this.toMemento_(); this.mementoFeedback_ = false; } } ] });
{ "content_hash": "d70897f37f79827c9c60d140746f3e31", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 89, "avg_line_length": 30.383838383838384, "alnum_prop": 0.5325797872340425, "repo_name": "jlhughes/foam", "id": "c56e05e77356078d20d61c4a30e35fb6f84422a2", "size": "3636", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "js/foam/memento/MemorableTrait.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1826" }, { "name": "CSS", "bytes": "64734" }, { "name": "HTML", "bytes": "324383" }, { "name": "Java", "bytes": "167220" }, { "name": "JavaScript", "bytes": "5905830" }, { "name": "Objective-J", "bytes": "834" }, { "name": "Shell", "bytes": "24747" } ], "symlink_target": "" }
/** * Check if arguments are nor null and neither undefined. */ export function isPresent() { var args = Array.prototype.slice.call(arguments); for (var i = 0; i < args.length; i++) { var it = args[i]; if (it === null || it === undefined) { return false; } } return true; } /** * Check if arguments are functions. * @returns {boolean} */ export function isFunction() { var args = Array.prototype.slice.call(arguments); for (var i = 0; i < args.length; i++) { var it = args[i]; var getType = {}; if (it === undefined || getType.toString.call(it) !== '[object Function]') { return false; } } return true; } /** * Slugify a strign. * @param str * @returns {void|XML|string|*} */ export function slugify(str) { return str.replace(/\s+/g, '-'); }
{ "content_hash": "3d13a17c1d22a759456bc1f3e1f47b2e", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 80, "avg_line_length": 20.82051282051282, "alnum_prop": 0.5849753694581281, "repo_name": "Laucsen/node-migrate-lite", "id": "1facaffd21778fd43c465d50ace7c2ef3216d0d5", "size": "812", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/util.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "32706" } ], "symlink_target": "" }
package spookfishperfviz; import static spookfishperfviz.Utils.forEach; import static spookfishperfviz.Utils.reverse; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.NavigableSet; import java.util.Objects; import java.util.Set; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import spookfishperfviz.Density.IndexedDataPoint; /** * @see http://www.brendangregg.com/HeatMaps/latency.html * * @author Rahul Bakale * @since Nov, 2014 */ final class TimeSeriesLatencyDensity { private static final int DEFAULT_HEAT_MAP_SINGLE_AREA_HEIGHT = 10; /** * TODO - take this as input parameter */ private static final int MAX_HEAT_MAP_HEIGHT = 400; private static final int DEFAULT_MAX_INTERBAL_POINTS_FOR_LATENCY_DENSITY = MAX_HEAT_MAP_HEIGHT / DEFAULT_HEAT_MAP_SINGLE_AREA_HEIGHT; private static final double X_AXIS_LABEL_FONT_SIZE = 10; // TODO - add to SVGConstants. private static final String X_AXIS_LABEL_FONT_FAMILY = SVGConstants.MONOSPACE_FONT_FAMILY; private static final UnaryOperator<Long> LONG_INC_OPERATOR = new UnaryOperator<Long>() { @Override public Long apply(final Long l) { return l == null ? Long.valueOf(0) : Long.valueOf(l.longValue() + 1); } }; private static final Function<IndexedDataPoint<Double>, String> Y_AXIS_LABEL_MAKER = new Function<Density.IndexedDataPoint<Double>, String>() { @Override public String apply(final IndexedDataPoint<Double> i) { return i.toString(new StripTrailingZeroesAfterDecimalFunction(true)); } }; private static final class TimestampLabelMaker implements Function<Long, String> { private static final String NL = System.lineSeparator(); private final SimpleDateFormat dayMonthFormat; private final SimpleDateFormat yearFormat; private final SimpleDateFormat timeFormat; TimestampLabelMaker(final TimeZone timeZone) { final SimpleDateFormat dayMonth = new SimpleDateFormat("dd/MM"); dayMonth.setTimeZone(timeZone); final SimpleDateFormat year = new SimpleDateFormat("yyyy"); year.setTimeZone(timeZone); final SimpleDateFormat time = new SimpleDateFormat("HH:mm"); time.setTimeZone(timeZone); this.dayMonthFormat = dayMonth; this.yearFormat = year; this.timeFormat = time; } @Override public String apply(final Long time) { final Date d = new Date(time.longValue()); return this.timeFormat.format(d) + NL + this.dayMonthFormat.format(d) + NL + this.yearFormat.format(d); } } private static final class TimestampTooltipMaker implements Function<Long, String> { private final SimpleDateFormat format; TimestampTooltipMaker(final TimeZone timeZone) { final SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy HH:mm"); f.setTimeZone(timeZone); this.format = f; } @Override public String apply(final Long time) { return this.format.format(time); } } static TimeSeriesLatencyDensity create( final double[] latencies, final long[] timestamps, final TimeZone outputTimeZone, final Integer maxIntervalPointsForLatencyDensity) { final double[] minMax = Utils.minMax(latencies); final double minIntervalPoint = minMax[0]; final double maxIntervalPoint = minMax[1]; return create0(latencies, timestamps, outputTimeZone, minIntervalPoint, maxIntervalPoint, maxIntervalPointsForLatencyDensity); } static TimeSeriesLatencyDensity create( final double[] latencies, final long[] timestamps, final TimeZone outputTimeZone, final double minIntervalPointForLatencyDensity, final double maxIntervalPointForLatencyDensity, final Integer maxIntervalPointsForLatencyDensity) { if (minIntervalPointForLatencyDensity > maxIntervalPointForLatencyDensity) { throw new IllegalArgumentException("min = <" + minIntervalPointForLatencyDensity + ">, max = <" + maxIntervalPointForLatencyDensity + ">"); } final double[] minMax = Utils.minMax(latencies); final double minLatency = minMax[0]; final double maxLatency = minMax[1]; final double minIntervalPoint; final double maxIntervalPoint; if ((maxIntervalPointForLatencyDensity < minLatency) || (minIntervalPointForLatencyDensity > maxLatency)) { minIntervalPoint = minIntervalPointForLatencyDensity; maxIntervalPoint = maxIntervalPointForLatencyDensity; } else { minIntervalPoint = Math.max(minLatency, minIntervalPointForLatencyDensity); maxIntervalPoint = Math.min(maxLatency, maxIntervalPointForLatencyDensity); } return create0(latencies, timestamps, outputTimeZone, minIntervalPoint, maxIntervalPoint, maxIntervalPointsForLatencyDensity); } private static TimeSeriesLatencyDensity create0(final double[] latencies, final long[] timestamps, final TimeZone outputTimeZone, final double adjustedMinIntervalPointForLatencyDensity, final double adjustedMaxIntervalPointForLatencyDensity, final Integer maxIntervalPointsForLatencyDensity) { final int maxIntervalPoints = maxIntervalPointsForLatencyDensity == null ? DEFAULT_MAX_INTERBAL_POINTS_FOR_LATENCY_DENSITY : maxIntervalPointsForLatencyDensity.intValue(); final double[] intervalPointsForLatencyDensity = createIntervalPoints(adjustedMinIntervalPointForLatencyDensity, adjustedMaxIntervalPointForLatencyDensity, maxIntervalPoints); return new TimeSeriesLatencyDensity(latencies, timestamps, outputTimeZone, intervalPointsForLatencyDensity); } private static double[] createIntervalPoints(final double minIntervalPoint, final double maxIntervalPoint, final int maxIntervalPoints) { final double adjustedMin = Math.floor(minIntervalPoint); final double adjustedMax = Math.ceil(maxIntervalPoint); if (adjustedMin > adjustedMax) { throw new IllegalArgumentException("min = <" + adjustedMin + ">, max = <" + adjustedMax + ">"); } //adjustedMin will be equal to adjustedMax in cases like minIntervalPoint=3.0 and maxIntervalPoint=3.0. //In such cases nIntervalPoints can be taken as 1. final int nIntervalPoints = adjustedMin == adjustedMax ? 1 : Math.min(maxIntervalPoints, (int) Math.ceil(adjustedMax - adjustedMin)); return Utils.createIntervalPoints(adjustedMin, adjustedMax, nIntervalPoints); } private final Density<Double, Long, Long> density; private final int defaultTimeLabelSkipCount; private final TimestampLabelMaker timestampLabelMaker; private final TimestampTooltipMaker timestampTooltipMaker; private TimeSeriesLatencyDensity(final double[] latencies, final long[] timestamps, final TimeZone outputTimeZone, final double[] responseTimeIntervalPoints) { this(latencies, timestamps, outputTimeZone, null, Utils.toHashSet(responseTimeIntervalPoints)); } private TimeSeriesLatencyDensity(final double[] latencies, final long[] timestamps, final TimeZone outputTimeZone, final Set<Long> inputTimestampIntervalPoints, final Set<Double> responseTimeIntervalPoints) { Objects.requireNonNull(latencies); Objects.requireNonNull(timestamps); Objects.requireNonNull(outputTimeZone); this.timestampLabelMaker = new TimestampLabelMaker(outputTimeZone); this.timestampTooltipMaker = new TimestampTooltipMaker(outputTimeZone); if (latencies.length != timestamps.length) { throw new IllegalArgumentException("Number of latencies must be same as number of timestamps"); } final long[] sortedTimestamps = Utils.sort(timestamps); final long minTime = sortedTimestamps[0]; final long maxTime = sortedTimestamps[sortedTimestamps.length - 1]; final long duration = maxTime - minTime; final long threshold = TimeUnit.HOURS.toMillis(5); final int defaultTimeLabelSkipCount = (duration > threshold) ? 1 : 2; final Set<Long> timestampIntervalPoints; if (inputTimestampIntervalPoints == null) { final long timeIntervalInMillis = (duration > threshold) ? TimeUnit.MINUTES.toMillis(30) : TimeUnit.MINUTES.toMillis(5); timestampIntervalPoints = Utils.getTimestampIntervalPoints(timestamps, outputTimeZone, timeIntervalInMillis); } else { timestampIntervalPoints = inputTimestampIntervalPoints; } final Density<Double, Long, Long> d = Density.create(responseTimeIntervalPoints, timestampIntervalPoints, Long.valueOf(0), Long.class); for (int i = 0; i < latencies.length; i++) { final Double row = Double.valueOf(latencies[i]); final Long column = Long.valueOf(timestamps[i]); d.apply(row, column, LONG_INC_OPERATOR); } this.density = d; this.defaultTimeLabelSkipCount = defaultTimeLabelSkipCount; } HeatMapSVG getHeatMapSVG(final TimeUnit latencyUnit, final double heatMapSingleAreaWidth, final ColorRampScheme colorScheme) { return getHeatMapSVG(latencyUnit, this.defaultTimeLabelSkipCount, heatMapSingleAreaWidth, colorScheme); } HeatMapSVG getHeatMapSVG(final TimeUnit latencyUnit, final int timeLabelSkipCount, final double heatMapSingleAreaWidth, final ColorRampScheme colorScheme) { return getHeatMapSVG(this.density, colorScheme, timeLabelSkipCount, latencyUnit, this.timestampLabelMaker, this.timestampTooltipMaker, heatMapSingleAreaWidth); } /** * TODO - re-factor common code from this and BarChart. */ private static HeatMapSVG getHeatMapSVG(final Density<Double, Long, Long> density, final ColorRampScheme colorScheme, final int timeLabelSkipCount, final TimeUnit latencyUnit, final TimestampLabelMaker timestampLabelMaker, final TimestampTooltipMaker timestampTooltipMaker, final double heatMapSingleAreaWidth) { final Long[][] matrix = density.getMatrix(); final String[][] heatMap = getColoredHeatMap(matrix, colorScheme); final int rowCount = heatMap.length; final int columnCount = heatMap[0].length; final String NL = System.lineSeparator(); final int START_X = SVGConstants.LEFT_RIGHT_MARGIN; final int START_Y = SVGConstants.TOP_DOWN_MARGIN; final int TICK_LENGTH = 10; final int SPACE_BETWEEN_LABEL_AND_TICK = 10; final int SPACE_BETWEEN_TITLE_AND_LABEL = 10; final String latencyUnitShortForm = Utils.toShortForm(latencyUnit); final String yAxisTitle = "Latency" + " (" + latencyUnitShortForm + ")"; final double Y_AXIS_TITLE_FONT_SIZE = SVGConstants.MONOSPACE_FONT_SIZE; final String Y_AXIS_TITLE_FONT_FAMILY = SVGConstants.MONOSPACE_FONT_FAMILY; final double Y_AXIS_TITLE_START_X = START_X; final double Y_AXIS_TITLE_END_X = Y_AXIS_TITLE_START_X + SVGConstants.MONOSPACE_FONT_SIZE; final double Y_AXIS_LABEL_FONT_SIZE = SVGConstants.MONOSPACE_FONT_SIZE; final String Y_AXIS_LABEL_FONT_FAMILY = SVGConstants.MONOSPACE_FONT_FAMILY; final double Y_AXIS_LABEL_START_X = Y_AXIS_TITLE_END_X + SPACE_BETWEEN_TITLE_AND_LABEL; final String X_AXIS_TITLE = "Time"; final double X_AXIS_TITLE_FONT_SIZE = SVGConstants.MONOSPACE_FONT_SIZE; final String X_AXIS_TITLE_FONT_FAMILY = SVGConstants.MONOSPACE_FONT_FAMILY; final double BOX_START_Y = START_Y; final ArrayList<String> yAxisLabels = forEach(reverse(density.getRowIntervalPoints(), new ArrayListSupplier<IndexedDataPoint<Double>>()), Y_AXIS_LABEL_MAKER, new ArrayListSupplier<String>()); final int yAxisMaxLabelLength = Collections.max(forEach(yAxisLabels, CharSeqLengthFunction.INSTANCE, new ArrayListSupplier<Integer>())).intValue(); final ArrayList<String> yAxisPaddedLabels = Utils.getPaddedLabels(yAxisLabels, yAxisMaxLabelLength, new ArrayListSupplier<String>(), true); final double yAxisMaxLabelWidth = yAxisMaxLabelLength * SVGConstants.MONOSPACE_FONT_WIDTH; final double yAxisMajorTickStartX = Y_AXIS_LABEL_START_X + yAxisMaxLabelWidth + SPACE_BETWEEN_LABEL_AND_TICK; final double yAxisTickEndX = yAxisMajorTickStartX + TICK_LENGTH; final double heatMapSingleAreaHeight = Math.min(MAX_HEAT_MAP_HEIGHT / rowCount, DEFAULT_HEAT_MAP_SINGLE_AREA_HEIGHT); final double heatMapHeight = rowCount * heatMapSingleAreaHeight; final double heatMapWidth = columnCount * heatMapSingleAreaWidth; final double heatMapBoxStartX = yAxisTickEndX; final double heatMapStartX = heatMapBoxStartX + heatMapSingleAreaWidth; final double heatMapStartY = BOX_START_Y + /* gutter */DEFAULT_HEAT_MAP_SINGLE_AREA_HEIGHT; final double heatMapBoxEndX = heatMapStartX + heatMapWidth + heatMapSingleAreaWidth; final double heatMapBoxEndY = heatMapStartY + heatMapHeight + /* gutter */DEFAULT_HEAT_MAP_SINGLE_AREA_HEIGHT; final double heatMapBoxHeight = heatMapBoxEndY - BOX_START_Y; final double heatMapBoxWidth = heatMapBoxEndX - heatMapBoxStartX; final double yAxisTitleStartY = BOX_START_Y + ((heatMapBoxHeight / 2.0) - (Y_AXIS_TITLE_FONT_SIZE / 2.0)); final double xAxisTickStartY = heatMapBoxEndY; final double xAxisMajorTickEndY = xAxisTickStartY + TICK_LENGTH; final double xAxisMinorTickEndY = xAxisTickStartY + (TICK_LENGTH / 2.0); // TODO - check if cast to int is OK final int yAxisLabelSkipCount = (int) (DEFAULT_HEAT_MAP_SINGLE_AREA_HEIGHT / heatMapSingleAreaHeight); final double xAxisLabelStartY = xAxisMajorTickEndY + SPACE_BETWEEN_LABEL_AND_TICK; final StringBuilder yAxisTitleSVG; { yAxisTitleSVG = new StringBuilder(); yAxisTitleSVG.append("<text "); yAxisTitleSVG.append("style=\""); yAxisTitleSVG.append("font-family:").append(Y_AXIS_TITLE_FONT_FAMILY).append(";"); yAxisTitleSVG.append("font-size:").append(Y_AXIS_TITLE_FONT_SIZE).append("px;"); yAxisTitleSVG.append("text-anchor: middle;"); // related to rotation of the title yAxisTitleSVG.append("dominant-baseline: middle;"); // related to rotation of the title yAxisTitleSVG.append("\""); yAxisTitleSVG.append(" x=\"").append(Y_AXIS_TITLE_START_X).append("\""); yAxisTitleSVG.append(" y=\"").append(yAxisTitleStartY).append("\""); yAxisTitleSVG.append(" transform=\"rotate(-90,").append(Y_AXIS_TITLE_START_X).append(",").append(yAxisTitleStartY).append(")\""); yAxisTitleSVG.append(">"); yAxisTitleSVG.append(yAxisTitle); yAxisTitleSVG.append("</text>"); } final StringBuilder yAxisLabelsSVG; final StringBuilder yAxisTicksSVG; { yAxisLabelsSVG = new StringBuilder(); yAxisTicksSVG = new StringBuilder(); yAxisLabelsSVG.append("<g style=\"font-family:").append(Y_AXIS_LABEL_FONT_FAMILY).append(";font-size:").append(Y_AXIS_LABEL_FONT_SIZE) .append("px;\">").append(NL); yAxisTicksSVG.append("<g style=\"stroke:black; stroke-width:1\">").append(NL); double yAxisLabelStartY = heatMapStartY; for (int i = 0; i <= rowCount; i++) { final boolean skipLabel = Utils.skipLabel(i, rowCount, yAxisLabelSkipCount); if (skipLabel == false) { yAxisLabelsSVG.append("<text style=\"dominant-baseline: central;\" x=\"").append(Y_AXIS_LABEL_START_X).append("\" y=\"") .append(yAxisLabelStartY).append("\">").append(yAxisPaddedLabels.get(i)).append("</text>").append(NL); yAxisTicksSVG .append("<line x1=\"").append(yAxisMajorTickStartX) .append("\" y1=\"").append(yAxisLabelStartY) .append("\" x2=\"").append(yAxisTickEndX) .append("\" y2=\"").append(yAxisLabelStartY) .append("\"/>").append(NL); } yAxisLabelStartY += heatMapSingleAreaHeight; } yAxisLabelsSVG.append("</g>"); yAxisTicksSVG.append("</g>"); } final ArrayList<IndexedDataPoint<Long>> timestampPoints = new ArrayList<>(density.getColumnIntervalPoints()); final double xAxisLabelEndY; final StringBuilder xAxisTicksSVG; final StringBuilder xAxisLabelsSVG; { xAxisTicksSVG = new StringBuilder(); xAxisLabelsSVG = new StringBuilder(); xAxisTicksSVG.append("<g style=\"stroke:black; stroke-width:1\">").append(NL); xAxisLabelsSVG.append("<g style=\"font-family:").append(X_AXIS_LABEL_FONT_FAMILY).append(";font-size:").append(X_AXIS_LABEL_FONT_SIZE).append("px;\">").append(NL); double x = heatMapStartX; // boxStartX; int maxXAxisLabelPartCount = Integer.MIN_VALUE; final double fontSize = X_AXIS_LABEL_FONT_SIZE; for (int i = 0; i <= columnCount; i++) { final boolean skipLabel = Utils.skipLabel(i, columnCount, timeLabelSkipCount); final double xAxisTickEndY = skipLabel ? xAxisMinorTickEndY : xAxisMajorTickEndY; xAxisTicksSVG.append("<line x1=\"").append(x).append("\" y1=\"").append(xAxisTickStartY).append("\" x2=\"").append(x) .append("\" y2=\"").append(xAxisTickEndY).append("\"/>").append(NL); if (skipLabel == false) { final String multiLineLabel = timestampPoints.get(i).toString(timestampLabelMaker); final MultiSpanSVGText label = Utils.createMultiSpanSVGText(multiLineLabel, x, xAxisLabelStartY, fontSize, null); xAxisLabelsSVG.append(label.getSvg()); maxXAxisLabelPartCount = Math.max(label.getSpanCount(), maxXAxisLabelPartCount); } x += heatMapSingleAreaWidth; } xAxisLabelEndY = xAxisLabelStartY + (maxXAxisLabelPartCount * fontSize); xAxisTicksSVG.append("</g>"); xAxisLabelsSVG.append("</g>"); } final double xAxisTitleEndY; final StringBuilder xAxisTitleSVG; { final double xAxisTitleStartY = xAxisLabelEndY + SPACE_BETWEEN_TITLE_AND_LABEL; xAxisTitleEndY = xAxisTitleStartY + X_AXIS_TITLE_FONT_SIZE; xAxisTitleSVG = new StringBuilder(); xAxisTitleSVG.append("<text "); xAxisTitleSVG.append("style=\""); xAxisTitleSVG.append("font-family:").append(X_AXIS_TITLE_FONT_FAMILY).append(";"); xAxisTitleSVG.append("font-size:").append(X_AXIS_TITLE_FONT_SIZE).append("px;"); xAxisTitleSVG.append("text-anchor: middle;"); xAxisTitleSVG.append("\""); xAxisTitleSVG.append(" x=\"").append(heatMapBoxStartX + (heatMapBoxWidth / 2.0)).append("\""); xAxisTitleSVG.append(" y=\"").append(xAxisTitleStartY).append("\""); xAxisTitleSVG.append(">"); xAxisTitleSVG.append(X_AXIS_TITLE); xAxisTitleSVG.append("</text>"); } final String colorForZeroVal = colorScheme.getBackgroundColor(); final StringBuilder boxSVG; { boxSVG = new StringBuilder(); boxSVG.append("<rect x=\"").append(heatMapBoxStartX).append("\" y=\"").append(BOX_START_Y).append("\" width=\"").append(heatMapBoxWidth) .append("\" height=\"").append(heatMapBoxHeight).append("\" style=\"fill:").append(colorForZeroVal) .append(";stroke:black;stroke-width:1\"/>").append(NL); } final StringBuilder colorMapSVG; { colorMapSVG = new StringBuilder(); double y = heatMapStartY; for (int rowNum = rowCount - 1, r = 0; rowNum >= 0; rowNum--, r++) { final String[] row = heatMap[rowNum]; final String yTooltip1 = yAxisLabels.get(r + 1); final String yTooltip2 = yAxisLabels.get(r); double x = heatMapStartX; for (int colNum = 0; colNum < columnCount; colNum++) { final String color = row[colNum]; if (!Objects.equals(color, colorForZeroVal)) { colorMapSVG.append("<rect"); colorMapSVG.append(" x=\"").append(x).append("\""); colorMapSVG.append(" y=\"").append(y).append("\""); colorMapSVG.append(" fill=\"").append(color).append("\""); colorMapSVG.append(" width=\"").append(heatMapSingleAreaWidth).append("\""); colorMapSVG.append(" height=\"").append(heatMapSingleAreaHeight).append("\""); colorMapSVG.append(">"); {//TOOLTIP //TODO - escape HTML special characters in tooltip text. For e.g. spaces. colorMapSVG.append("<title>"); colorMapSVG.append("Count = ").append(matrix[rowNum][colNum]).append(", Color = ").append(color).append(NL); final String xTooltip1 = timestampPoints.get(colNum).toString(timestampTooltipMaker); final String xTooltip2 = timestampPoints.get(colNum + 1).toString(timestampTooltipMaker); colorMapSVG.append("Period: (").append(xTooltip1).append(" - ").append(xTooltip2).append(')').append(NL); colorMapSVG.append("Latency range: (").append(yTooltip1).append(" - ").append(yTooltip2).append(") ").append(latencyUnitShortForm).append(NL); colorMapSVG.append("</title>"); } colorMapSVG.append("</rect>"); colorMapSVG.append(NL); } x += heatMapSingleAreaWidth; } y += heatMapSingleAreaHeight; } } final StringBuilder svg = new StringBuilder(); // Need to set the width & height of the SVG to prevent clipping of large SVGs. final double svgEndX = heatMapBoxEndX + SVGConstants.LEFT_RIGHT_MARGIN; final double svgEndY = xAxisTitleEndY + SVGConstants.TOP_DOWN_MARGIN; svg.append("<svg width=\"").append(svgEndX).append("\" height=\"").append(svgEndY).append("\">").append(NL); svg.append(xAxisTitleSVG).append(NL); svg.append(xAxisTicksSVG).append(NL); svg.append(xAxisLabelsSVG).append(NL); svg.append(yAxisTitleSVG).append(NL); svg.append(yAxisLabelsSVG).append(NL); svg.append(yAxisTicksSVG).append(NL); svg.append(boxSVG).append(NL); svg.append(colorMapSVG).append(NL); svg.append("</svg>"); return new HeatMapSVG(svg.toString(), timeLabelSkipCount, heatMapBoxStartX, heatMapSingleAreaWidth); } /** * TODO - check if some code can be moved to {@linkplain Density} */ private static String[][] getColoredHeatMap(final Long[][] matrix, final ColorRampScheme colorScheme) { final String[] colorMapArray = ColorRampCalculator.getColorMap(Utils.toOneDimArray(matrix), colorScheme); final int rowCount = matrix.length; final int columnCount = matrix[0].length; final String[][] colorMapMatrix = new String[rowCount][columnCount]; Utils.fillMatrix(colorMapArray, colorMapMatrix); return colorMapMatrix; } String getTrxCountBarChartSVG(final int labelSkipCount, final double boxStartX, final double barWidth, final ColorRampScheme colorRampScheme) { return getTrxCountBarChartSVG(this.density, labelSkipCount, this.timestampLabelMaker, boxStartX, barWidth, colorRampScheme); } private static String getTrxCountBarChartSVG(final Density<Double, Long, Long> density, final int labelSkipCount, final TimestampLabelMaker timestampLabelMaker, final double boxStartX, final double barWidth, final ColorRampScheme colorRampScheme) { final int MAX_BAR_LENGTH = 100; final Long[][] matrix = density.getMatrix(); final NavigableSet<IndexedDataPoint<Long>> columnIntervalPoints = density.getColumnIntervalPoints(); final int rowCount = matrix.length; final int columnCount = matrix[0].length; final long[] columnTotals = new long[columnCount]; for (int column = 0; column < columnCount; column++) { long sum = 0; for (int row = 0; row < rowCount; row++) { sum += matrix[row][column].longValue(); } columnTotals[column] = sum; } final List<String> labels = new ArrayList<>(); for (final IndexedDataPoint<Long> columnIntervalPoint : columnIntervalPoints) { labels.add(columnIntervalPoint.toString(timestampLabelMaker)); } final VerticalBarChart barChart = VerticalBarChart.create(columnTotals, labels.toArray(new String[labels.size()])); return barChart.toSVG(MAX_BAR_LENGTH, barWidth, boxStartX, X_AXIS_LABEL_FONT_FAMILY, X_AXIS_LABEL_FONT_SIZE, labelSkipCount, colorRampScheme); } @Override public String toString() { return this.density.toString(); } }
{ "content_hash": "3edfaafeec7166614e1a0fa09f33f103", "timestamp": "", "source": "github", "line_count": 591, "max_line_length": 185, "avg_line_length": 40.585448392554994, "alnum_prop": 0.7107896272825815, "repo_name": "rahulbakale/Spookfish-Perf-Viz", "id": "412743158348608c8c7683ea3edcfd248db0e17f", "size": "24603", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/spookfishperfviz/TimeSeriesLatencyDensity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "158269" } ], "symlink_target": "" }
/** * Vidom * @author Filatov Dmitry <dfilatov@inbox.ru> * @version 0.8.6 */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.vidom = global.vidom || {}))); }(this, (function (exports) { 'use strict'; var AMP_RE = /&/g; var QUOT_RE = /"/g; function escapeAttr(str) { str = str + ''; var i = str.length, escapes = 0; // 1 — escape '&', 2 — escape '"' while (i--) { switch (str[i]) { case '&': escapes |= 1; break; case '"': escapes |= 2; break; } } if (escapes & 1) { str = str.replace(AMP_RE, '&amp;'); } if (escapes & 2) { str = str.replace(QUOT_RE, '&quot;'); } return str; } function isInArray(arr, item) { var len = arr.length; var i = 0; while (i < len) { if (arr[i++] == item) { return true; } } return false; } var DASHERIZE_RE = /([^A-Z]+)([A-Z])/g; function dasherize(str) { return str.replace(DASHERIZE_RE, '$1-$2').toLowerCase(); } /** @const */ var IS_DEBUG = !'development' || 'development' === 'development'; function setAttr(node, name, val) { if (name === 'type' && node.tagName === 'INPUT') { var value = node.value; // value will be lost in IE if type is changed node.setAttribute(name, '' + val); node.value = value; } else { node.setAttribute(ATTR_NAMES[name] || name, '' + val); } } function setBooleanAttr(node, name, val) { if (val) { setAttr(node, name, val); } else { removeAttr$1(node, name); } } function setProp(node, name, val) { node[name] = val; } function setObjProp(node, name, val) { if (IS_DEBUG) { var typeOfVal = typeof val; if (typeOfVal !== 'object') { throw TypeError('vidom: "' + name + '" attribute value must be an object, not a ' + typeOfVal); } } var prop = node[name]; for (var i in val) { prop[i] = val[i] == null ? '' : val[i]; } } function setPropWithCheck(node, name, val) { if (name === 'value' && node.tagName === 'SELECT') { setSelectValue(node, val); } else { node[name] !== val && (node[name] = val); } } function removeAttr$1(node, name) { node.removeAttribute(ATTR_NAMES[name] || name); } function removeProp(node, name) { if (name === 'style') { node[name].cssText = ''; } else if (name === 'value' && node.tagName === 'SELECT') { removeSelectValue(node); } else { node[name] = getDefaultPropVal(node.tagName, name); } } function setSelectValue(node, value) { var isMultiple = Array.isArray(value); if (isMultiple) { var options = node.options, len = options.length; var i = 0, optionNode = void 0; while (i < len) { optionNode = options[i++]; optionNode.selected = value != null && isInArray(value, optionNode.value); } } else { node.value = value; } } function removeSelectValue(node) { var options = node.options, len = options.length; var i = 0; while (i < len) { options[i++].selected = false; } } function attrToString(name, value) { return value === false ? '' : (ATTR_NAMES[name] || name) + (value === true ? '' : '="' + escapeAttr(value) + '"'); } function booleanAttrToString(name, value) { return value ? name : ''; } function stylePropToString(name, value) { var styles = '', i = void 0; for (i in value) { if (value[i] != null) { styles += dasherize(i) + ':' + value[i] + ';'; } } return styles ? name + '="' + styles + '"' : styles; } var defaultPropVals = {}; function getDefaultPropVal(tag, attrName) { var tagAttrs = defaultPropVals[tag] || (defaultPropVals[tag] = {}); return attrName in tagAttrs ? tagAttrs[attrName] : tagAttrs[attrName] = document.createElement(tag)[attrName]; } var ATTR_NAMES = { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv', autoCapitalize: 'autocapitalize', autoComplete: 'autocomplete', autoCorrect: 'autocorrect', autoFocus: 'autofocus', autoPlay: 'autoplay', encType: 'encoding', hrefLang: 'hreflang', radioGroup: 'radiogroup', spellCheck: 'spellcheck', srcDoc: 'srcdoc', srcSet: 'srcset', tabIndex: 'tabindex' }; var DEFAULT_ATTR_CFG = { set: setAttr, remove: removeAttr$1, toString: attrToString }; var BOOLEAN_ATTR_CFG = { set: setBooleanAttr, remove: removeAttr$1, toString: booleanAttrToString }; var DEFAULT_PROP_CFG = { set: setProp, remove: removeProp, toString: attrToString }; var BOOLEAN_PROP_CFG = { set: setProp, remove: removeProp, toString: booleanAttrToString }; var attrsCfg = { checked: BOOLEAN_PROP_CFG, controls: DEFAULT_PROP_CFG, disabled: BOOLEAN_ATTR_CFG, id: DEFAULT_PROP_CFG, ismap: BOOLEAN_ATTR_CFG, loop: DEFAULT_PROP_CFG, multiple: BOOLEAN_PROP_CFG, muted: DEFAULT_PROP_CFG, open: BOOLEAN_ATTR_CFG, readOnly: BOOLEAN_PROP_CFG, selected: BOOLEAN_PROP_CFG, srcDoc: DEFAULT_PROP_CFG, style: { set: setObjProp, remove: removeProp, toString: stylePropToString }, value: { set: setPropWithCheck, remove: removeProp, toString: attrToString } }; var domAttrs = function (attrName) { return attrsCfg[attrName] || DEFAULT_ATTR_CFG; }; function append(parent, child) { if (Array.isArray(parent)) { insertBefore(child, parent[1]); } else if (Array.isArray(child)) { var currentChild = child[0], nextChild = void 0; var lastChild = child[1]; while (currentChild !== lastChild) { nextChild = currentChild.nextSibling; parent.appendChild(currentChild); currentChild = nextChild; } parent.appendChild(lastChild); } else { parent.appendChild(child); } } function remove(child) { if (Array.isArray(child)) { var currentChild = child[0], nextChild = void 0; var lastChild = child[1], parent = lastChild.parentNode; while (currentChild !== lastChild) { nextChild = currentChild.nextSibling; parent.removeChild(currentChild); currentChild = nextChild; } parent.removeChild(lastChild); } else { child.parentNode.removeChild(child); } } function insertBefore(child, beforeChild) { Array.isArray(beforeChild) && (beforeChild = beforeChild[0]); if (Array.isArray(child)) { var currentChild = child[0], nextChild = void 0; var lastChild = child[1], parent = lastChild.parentNode; while (currentChild !== lastChild) { nextChild = currentChild.nextSibling; parent.insertBefore(currentChild, beforeChild); currentChild = nextChild; } parent.insertBefore(lastChild, beforeChild); } else { beforeChild.parentNode.insertBefore(child, beforeChild); } } function move(child, toChild, after) { if (after) { Array.isArray(toChild) && (toChild = toChild[1]); var nextSibling = toChild.nextSibling; nextSibling ? insertBefore(child, nextSibling) : append(toChild.parentNode, child); } else { insertBefore(child, toChild); } } function replace$1(old, replacement) { if (Array.isArray(old)) { insertBefore(replacement, old); remove(old); } else { old.parentNode.replaceChild(replacement, old); } } function removeChildren$1(from) { if (Array.isArray(from)) { var currentChild = from[0].nextSibling, nextChild = void 0; var lastChild = from[1], parent = lastChild.parentNode; while (currentChild !== lastChild) { nextChild = currentChild.nextSibling; parent.removeChild(currentChild); currentChild = nextChild; } } else { from.textContent = ''; } } function updateText$1(node, text, escape) { if (Array.isArray(node)) { var beforeChild = node[1], previousChild = beforeChild.previousSibling; if (previousChild === node[0]) { beforeChild.parentNode.insertBefore(document.createTextNode(text), beforeChild); } else { previousChild.nodeValue = text; } } else if (escape) { var firstChild = node.firstChild; firstChild ? firstChild.nodeValue = text : node.textContent = text; } else { node.innerHTML = text; } } function removeText$1(from) { if (Array.isArray(from)) { var child = from[0].nextSibling; child.parentNode.removeChild(child); } else { from.textContent = ''; } } var domOps = { append: append, remove: remove, insertBefore: insertBefore, move: move, replace: replace$1, removeChildren: removeChildren$1, updateText: updateText$1, removeText: removeText$1 }; function isEventSupported(type) { var eventProp = 'on' + type; if (eventProp in document) { return true; } var domNode = document.createElement('div'); domNode.setAttribute(eventProp, 'return;'); if (typeof domNode[eventProp] === 'function') { return true; } return type === 'wheel' && document.implementation && document.implementation.hasFeature && document.implementation.hasFeature('', '') !== true && document.implementation.hasFeature('Events.wheel', '3.0'); } function SyntheticEvent(type, nativeEvent) { this.type = type; this.target = nativeEvent.target; this.nativeEvent = nativeEvent; this._isPropagationStopped = false; this._isDefaultPrevented = false; this._isPersisted = false; } SyntheticEvent.prototype = { stopPropagation: function () { this._isPropagationStopped = true; var nativeEvent = this.nativeEvent; nativeEvent.stopPropagation ? nativeEvent.stopPropagation() : nativeEvent.cancelBubble = true; }, isPropagationStopped: function () { return this._isPropagationStopped; }, preventDefault: function () { this._isDefaultPrevented = true; var nativeEvent = this.nativeEvent; nativeEvent.preventDefault ? nativeEvent.preventDefault() : nativeEvent.returnValue = false; }, isDefaultPrevented: function () { return this._isDefaultPrevented; }, persist: function () { this._isPersisted = true; } }; var eventsPool = {}; function createSyntheticEvent(type, nativeEvent) { var pooledEvent = eventsPool[type]; if (pooledEvent && !pooledEvent._isPersisted) { pooledEvent.target = nativeEvent.target; pooledEvent.nativeEvent = nativeEvent; pooledEvent._isPropagationStopped = false; pooledEvent._isDefaultPrevented = false; return pooledEvent; } return eventsPool[type] = new SyntheticEvent(type, nativeEvent); } var ID_PROP = '__vidom__id__'; var counter = 1; function getDomNodeId(node, onlyGet) { return node[ID_PROP] || (onlyGet ? null : node[ID_PROP] = counter++); } var SimpleMap = void 0; if (typeof Map === 'undefined') { SimpleMap = function () { this._storage = {}; }; SimpleMap.prototype = { has: function (key) { return key in this._storage; }, get: function (key) { return this._storage[key]; }, set: function (key, value) { this._storage[key] = value; return this; }, delete: function (key) { return delete this._storage[key]; }, forEach: function (callback, thisArg) { var storage = this._storage; for (var key in storage) { callback.call(thisArg, storage[key], key, this); } } }; } else { SimpleMap = Map; } var SimpleMap$1 = SimpleMap; var ua = typeof navigator === 'undefined' ? '' : navigator.userAgent; var isTrident = ua.indexOf('Trident') > -1; var isEdge = ua.indexOf('Edge') > -1; var isIos = /iPad|iPhone|iPod/.test(ua) && typeof MSStream === 'undefined'; var MOUSE_NATIVE_EVENTS = ['click', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup']; var BUBBLEABLE_NATIVE_EVENTS = ['blur', 'change', 'contextmenu', 'copy', 'cut', 'dblclick', 'drag', 'dragend', 'dragenter', 'dragleave', 'dragover', 'dragstart', 'drop', 'focus', 'input', 'keydown', 'keypress', 'keyup', 'paste', 'submit', 'touchcancel', 'touchend', 'touchmove', 'touchstart', 'wheel']; var NON_BUBBLEABLE_NATIVE_EVENTS = ['canplay', 'canplaythrough', 'complete', 'durationchange', 'emptied', 'ended', 'error', 'load', 'loadeddata', 'loadedmetadata', 'loadstart', 'mouseenter', 'mouseleave', 'pause', 'play', 'playing', 'progress', 'ratechange', 'scroll', 'seeked', 'seeking', 'select', 'stalled', 'suspend', 'timeupdate', 'volumechange', 'waiting']; if (isIos) { NON_BUBBLEABLE_NATIVE_EVENTS = [].concat(NON_BUBBLEABLE_NATIVE_EVENTS, MOUSE_NATIVE_EVENTS); } else { BUBBLEABLE_NATIVE_EVENTS = [].concat(BUBBLEABLE_NATIVE_EVENTS, MOUSE_NATIVE_EVENTS); } var listenersStorage = new SimpleMap$1(); var eventsCfg = {}; var areListenersEnabled = true; function globalEventListener(e) { var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : e.type; if (!areListenersEnabled) { return; } var target = e.target, listenersCount = eventsCfg[type].listenersCount, listeners = void 0, listener = void 0, domNodeId = void 0, syntheticEvent = void 0; while (listenersCount && target && target !== document) { // need to check target for detached dom if (domNodeId = getDomNodeId(target, true)) { listeners = listenersStorage.get(domNodeId); if (listeners && (listener = listeners[type])) { listener(syntheticEvent || (syntheticEvent = createSyntheticEvent(type, e))); if (! --listenersCount || syntheticEvent.isPropagationStopped()) { return; } } } target = target.parentNode; } } function eventListener(e) { if (areListenersEnabled) { listenersStorage.get(getDomNodeId(e.currentTarget))[e.type](createSyntheticEvent(e.type, e)); } } if (typeof document !== 'undefined') { (function () { var focusEvents = { focus: 'focusin', blur: 'focusout' }; var i = 0, type = void 0; while (i < BUBBLEABLE_NATIVE_EVENTS.length) { type = BUBBLEABLE_NATIVE_EVENTS[i++]; eventsCfg[type] = { type: type, bubbles: true, listenersCount: 0, set: false, setup: focusEvents[type] ? isEventSupported(focusEvents[type]) ? function () { var type = this.type; document.addEventListener(focusEvents[type], function (e) { globalEventListener(e, type); }); } : function () { document.addEventListener(this.type, globalEventListener, true); } : null }; } i = 0; while (i < NON_BUBBLEABLE_NATIVE_EVENTS.length) { eventsCfg[NON_BUBBLEABLE_NATIVE_EVENTS[i++]] = { type: type, bubbles: false, set: false }; } })(); } function addListener(domNode, type, listener) { var cfg = eventsCfg[type]; if (cfg) { if (!cfg.set) { cfg.setup ? cfg.setup() : cfg.bubbles && document.addEventListener(type, globalEventListener, false); cfg.set = true; } var domNodeId = getDomNodeId(domNode); var listeners = listenersStorage.get(domNodeId); if (!listeners) { listenersStorage.set(domNodeId, listeners = {}); } if (!listeners[type]) { cfg.bubbles ? ++cfg.listenersCount : domNode.addEventListener(type, eventListener, false); } listeners[type] = listener; } } function doRemoveListener(domNode, type) { var cfg = eventsCfg[type]; if (cfg) { if (cfg.bubbles) { --cfg.listenersCount; } else { domNode.removeEventListener(type, eventListener); } } } function removeListener(domNode, type) { var domNodeId = getDomNodeId(domNode, true); if (domNodeId) { var listeners = listenersStorage.get(domNodeId); if (listeners && listeners[type]) { listeners[type] = null; doRemoveListener(domNode, type); } } } function removeListeners(domNode) { var domNodeId = getDomNodeId(domNode, true); if (domNodeId) { var listeners = listenersStorage.get(domNodeId); if (listeners) { for (var type in listeners) { if (listeners[type]) { doRemoveListener(domNode, type); } } listenersStorage.delete(domNodeId); } } } function disableListeners() { areListenersEnabled = false; } function enableListeners() { areListenersEnabled = true; } var DEFAULT_NS_URI = 'http://www.w3.org/1999/xhtml'; function getNs(domNode) { return Array.isArray(domNode) ? getParentNs(domNode) : domNode.namespaceURI === DEFAULT_NS_URI ? null : domNode.namespaceURI; } function getParentNs(domNode) { return getNs((Array.isArray(domNode) ? domNode[domNode.length - 1] : domNode).parentNode); } var ATTRS_TO_EVENTS = { onBlur: 'blur', onCanPlay: 'canplay', onCanPlayThrough: 'canplaythrough', onChange: 'change', onClick: 'click', onComplete: 'complete', onContextMenu: 'contextmenu', onCopy: 'copy', onCut: 'cut', onDblClick: 'dblclick', onDrag: 'drag', onDragEnd: 'dragend', onDragEnter: 'dragenter', onDragLeave: 'dragleave', onDragOver: 'dragover', onDragStart: 'dragstart', onDrop: 'drop', onDurationChange: 'durationchange', onEmptied: 'emptied', onEnded: 'ended', onError: 'error', onFocus: 'focus', onInput: 'input', onKeyDown: 'keydown', onKeyPress: 'keypress', onKeyUp: 'keyup', onLoad: 'load', onLoadedData: 'loadeddata', onLoadedMetadata: 'loadedmetadata', onLoadStart: 'loadstart', onMouseDown: 'mousedown', onMouseEnter: 'mouseenter', onMouseLeave: 'mouseleave', onMouseMove: 'mousemove', onMouseOut: 'mouseout', onMouseOver: 'mouseover', onMouseUp: 'mouseup', onPaste: 'paste', onPause: 'pause', onPlay: 'play', onPlaying: 'playing', onProgress: 'progress', onRateChange: 'ratechange', onScroll: 'scroll', onSeeked: 'seeked', onSeeking: 'seeking', onSelect: 'select', onStalled: 'stalled', onSubmit: 'submit', onSuspend: 'suspend', onTimeUpdate: 'timeupdate', onTouchCancel: 'touchcancel', onTouchEnd: 'touchend', onTouchMove: 'touchmove', onTouchStart: 'touchstart', onVolumeChange: 'volumechange', onWaiting: 'waiting', onWheel: 'wheel' }; function appendChild(parentNode, childNode) { var parentDomNode = parentNode.getDomNode(); domOps.append(parentDomNode, childNode.renderToDom(getNs(parentDomNode))); childNode.mount(); } function insertChild(childNode, beforeChildNode) { var beforeChildDomNode = beforeChildNode.getDomNode(); domOps.insertBefore(childNode.renderToDom(getParentNs(beforeChildDomNode)), beforeChildDomNode); childNode.mount(); } function removeChild(childNode) { var childDomNode = childNode.getDomNode(); childNode.unmount(); domOps.remove(childDomNode); } function moveChild(childNode, toChildNode, after) { var activeDomNode = document.activeElement; disableListeners(); domOps.move(childNode.getDomNode(), toChildNode.getDomNode(), after); if (document.activeElement !== activeDomNode) { activeDomNode.focus(); } enableListeners(); } function removeChildren(parentNode) { var parentDomNode = parentNode.getDomNode(), childNodes = parentNode.children, len = childNodes.length; var j = 0; while (j < len) { childNodes[j++].unmount(); } domOps.removeChildren(parentDomNode); } function replace(oldNode, newNode) { var oldDomNode = oldNode.getDomNode(); oldNode.unmount(); domOps.replace(oldDomNode, newNode.renderToDom(getParentNs(oldDomNode))); newNode.mount(); } function updateAttr(node, attrName, attrVal) { var domNode = node.getDomNode(); ATTRS_TO_EVENTS[attrName] ? addListener(domNode, ATTRS_TO_EVENTS[attrName], attrVal) : domAttrs(attrName).set(domNode, attrName, attrVal); } function removeAttr(node, attrName) { var domNode = node.getDomNode(); ATTRS_TO_EVENTS[attrName] ? removeListener(domNode, ATTRS_TO_EVENTS[attrName]) : domAttrs(attrName).remove(domNode, attrName); } function updateText(node, text, escape) { domOps.updateText(node.getDomNode(), text, escape); } function removeText(node) { domOps.removeText(node.getDomNode()); } var patchOps = { appendChild: appendChild, insertChild: insertChild, removeChild: removeChild, moveChild: moveChild, removeChildren: removeChildren, replace: replace, updateAttr: updateAttr, removeAttr: removeAttr, updateText: updateText, removeText: removeText }; function checkReuse(node, name) { if (node.getDomNode()) { throw Error("vidom: Detected unexpected attempt to reuse the same node \"" + name + "\"."); } } var elementProtos = {}; function createElement(tag, ns) { var baseElement = void 0; if (ns) { var key = ns + ':' + tag; baseElement = elementProtos[key] || (elementProtos[key] = document.createElementNS(ns, tag)); } else { baseElement = elementProtos[tag] || (elementProtos[tag] = tag === '!' ? document.createComment('') : document.createElement(tag)); } return baseElement.cloneNode(); } function patchChildren(nodeA, nodeB) { var childrenA = nodeA.children, childrenB = nodeB.children, childrenALen = childrenA.length, childrenBLen = childrenB.length; if (childrenALen === 1 && childrenBLen === 1) { childrenA[0].patch(childrenB[0]); return; } var leftIdxA = 0, rightIdxA = childrenALen - 1, leftChildA = childrenA[leftIdxA], leftChildAKey = leftChildA.key, rightChildA = childrenA[rightIdxA], rightChildAKey = rightChildA.key, leftIdxB = 0, rightIdxB = childrenBLen - 1, leftChildB = childrenB[leftIdxB], leftChildBKey = leftChildB.key, rightChildB = childrenB[rightIdxB], rightChildBKey = rightChildB.key, updateLeftIdxA = false, updateRightIdxA = false, updateLeftIdxB = false, updateRightIdxB = false, childrenAKeys = void 0, foundAChildIdx = void 0, foundAChild = void 0; var childrenAIndicesToSkip = {}; while (leftIdxA <= rightIdxA && leftIdxB <= rightIdxB) { if (childrenAIndicesToSkip[leftIdxA]) { updateLeftIdxA = true; } else if (childrenAIndicesToSkip[rightIdxA]) { updateRightIdxA = true; } else if (leftChildAKey === leftChildBKey) { leftChildA.patch(leftChildB); updateLeftIdxA = true; updateLeftIdxB = true; } else if (rightChildAKey === rightChildBKey) { rightChildA.patch(rightChildB); updateRightIdxA = true; updateRightIdxB = true; } else if (leftChildAKey != null && leftChildAKey === rightChildBKey) { patchOps.moveChild(leftChildA, rightChildA, true); leftChildA.patch(rightChildB); updateLeftIdxA = true; updateRightIdxB = true; } else if (rightChildAKey != null && rightChildAKey === leftChildBKey) { patchOps.moveChild(rightChildA, leftChildA, false); rightChildA.patch(leftChildB); updateRightIdxA = true; updateLeftIdxB = true; } else if (leftChildAKey != null && leftChildBKey == null) { patchOps.insertChild(leftChildB, leftChildA); updateLeftIdxB = true; } else if (leftChildAKey == null && leftChildBKey != null) { patchOps.removeChild(leftChildA); updateLeftIdxA = true; } else { childrenAKeys || (childrenAKeys = buildKeys(childrenA, leftIdxA, rightIdxA)); if ((foundAChildIdx = childrenAKeys[leftChildBKey]) == null) { patchOps.insertChild(leftChildB, leftChildA); } else { foundAChild = childrenA[foundAChildIdx]; childrenAIndicesToSkip[foundAChildIdx] = true; patchOps.moveChild(foundAChild, leftChildA, false); foundAChild.patch(leftChildB); } updateLeftIdxB = true; } if (updateLeftIdxA) { updateLeftIdxA = false; if (++leftIdxA <= rightIdxA) { leftChildA = childrenA[leftIdxA]; leftChildAKey = leftChildA.key; } } if (updateRightIdxA) { updateRightIdxA = false; if (--rightIdxA >= leftIdxA) { rightChildA = childrenA[rightIdxA]; rightChildAKey = rightChildA.key; } } if (updateLeftIdxB) { updateLeftIdxB = false; if (++leftIdxB <= rightIdxB) { leftChildB = childrenB[leftIdxB]; leftChildBKey = leftChildB.key; } } if (updateRightIdxB) { updateRightIdxB = false; if (--rightIdxB >= leftIdxB) { rightChildB = childrenB[rightIdxB]; rightChildBKey = rightChildB.key; } } } while (leftIdxA <= rightIdxA) { if (!childrenAIndicesToSkip[leftIdxA]) { patchOps.removeChild(childrenA[leftIdxA]); } ++leftIdxA; } while (leftIdxB <= rightIdxB) { rightIdxB < childrenBLen - 1 ? patchOps.insertChild(childrenB[leftIdxB], childrenB[rightIdxB + 1]) : patchOps.appendChild(nodeB, childrenB[leftIdxB]); ++leftIdxB; } } function buildKeys(children, idxFrom, idxTo) { var res = {}; var child = void 0; while (idxFrom < idxTo) { child = children[idxFrom]; child.key != null && (res[child.key] = idxFrom); ++idxFrom; } return res; } var obj = {}; if (IS_DEBUG) { Object.freeze(obj); } function noOp() {} var globalConsole = typeof console == 'undefined' ? null : console; var consoleWrapper = {}; var PREFIXES = { log: '', info: '', warn: 'Warning!', error: 'Error!' }; ['log', 'info', 'warn', 'error'].forEach(function (name) { consoleWrapper[name] = globalConsole ? globalConsole[name] ? function (arg1, arg2, arg3, arg4, arg5) { // IE9: console methods aren't functions var arg0 = PREFIXES[name]; switch (arguments.length) { case 1: globalConsole[name](arg0, arg1); break; case 2: globalConsole[name](arg0, arg1, arg2); break; case 3: globalConsole[name](arg0, arg1, arg2, arg3); break; case 4: globalConsole[name](arg0, arg1, arg2, arg3, arg4); break; case 5: globalConsole[name](arg0, arg1, arg2, arg3, arg4, arg5); break; } } : function () { globalConsole.log.apply(globalConsole, arguments); } : noOp; }); function restrictObjProp(obj, prop) { var hiddenProp = "__" + prop + "__"; Object.defineProperty(obj, prop, { get: function () { return obj[hiddenProp]; }, set: function (value) { if (obj.__isFrozen) { throw TypeError("vidom: " + prop + " is readonly"); } obj[hiddenProp] = value; } }); } var NODE_TYPE_TOP = 1; var NODE_TYPE_TAG = 2; var NODE_TYPE_TEXT = 3; var NODE_TYPE_FRAGMENT = 4; var NODE_TYPE_COMPONENT = 5; var NODE_TYPE_FUNCTION_COMPONENT = 6; var KEY_SET = 1; var REF_SET = 2; function setKey(key) { if (IS_DEBUG) { if (this._sets & KEY_SET) { console.warn('Key is already set and shouldn\'t be set again'); } this.__isFrozen = false; } this.key = key; if (IS_DEBUG) { this._sets |= KEY_SET; this.__isFrozen = true; } return this; } function setRef(ref) { if (IS_DEBUG) { if (this._sets & REF_SET) { console.warn('Ref is already set and shouldn\'t be set again.'); } } this._ref = ref; if (IS_DEBUG) { this._sets |= REF_SET; } return this; } var CHILDREN_SET$1 = 8; function FragmentNode() { if (IS_DEBUG) { restrictObjProp(this, 'type'); restrictObjProp(this, 'key'); restrictObjProp(this, 'children'); this.__isFrozen = false; } this.type = NODE_TYPE_FRAGMENT; this.key = null; this.children = null; if (IS_DEBUG) { this.__isFrozen = true; this._sets = 0; } this._domNode = null; this._ctx = obj; } FragmentNode.prototype = { getDomNode: function () { return this._domNode; }, setKey: setKey, setChildren: function (children) { if (IS_DEBUG) { if (this._sets & CHILDREN_SET$1) { consoleWrapper.warn('Children are already set and shouldn\'t be set again.'); } this.__isFrozen = false; } this.children = processChildren$1(children); if (IS_DEBUG) { if (Array.isArray(this.children)) { Object.freeze(this.children); } this._sets |= CHILDREN_SET$1; this.__isFrozen = true; } return this; }, setCtx: function (ctx) { if (ctx !== obj) { this._ctx = ctx; var children = this.children; if (children) { var len = children.length; var i = 0; while (i < len) { children[i++].setCtx(ctx); } } } return this; }, renderToDom: function (parentNs) { if (IS_DEBUG) { checkReuse(this, 'fragment'); } var children = this.children, domNode = [createElement('!'), createElement('!')], domFragment = document.createDocumentFragment(); domFragment.appendChild(domNode[0]); if (children) { var len = children.length; var i = 0; while (i < len) { domFragment.appendChild(children[i++].renderToDom(parentNs)); } } domFragment.appendChild(domNode[1]); this._domNode = domNode; return domFragment; }, renderToString: function () { var children = this.children; var res = '<!---->'; if (children) { var i = children.length - 1; while (i >= 0) { res = children[i--].renderToString() + res; } } return '<!---->' + res; }, adoptDom: function (domNodes, domIdx) { if (IS_DEBUG) { checkReuse(this, 'fragment'); } var domNode = [domNodes[domIdx++]], children = this.children; if (children) { var len = children.length; var i = 0; while (i < len) { domIdx = children[i++].adoptDom(domNodes, domIdx); } } domNode.push(domNodes[domIdx]); this._domNode = domNode; return domIdx + 1; }, mount: function () { var children = this.children; if (children) { var i = 0; var len = children.length; while (i < len) { children[i++].mount(); } } }, unmount: function () { var children = this.children; if (children) { var len = children.length; var i = 0; while (i < len) { children[i++].unmount(); } } }, clone: function () { var res = new FragmentNode(); if (IS_DEBUG) { res.__isFrozen = false; } res.key = this.key; res.children = this.children; if (IS_DEBUG) { res.__isFrozen = true; } res._ctx = this._ctx; return res; }, patch: function (node) { if (this === node) { this._patchChildren(node); } else if (this.type === node.type) { node._domNode = this._domNode; this._patchChildren(node); } else { patchOps.replace(this, node); } }, _patchChildren: function (node) { var childrenA = this.children, childrenB = node.children; if (!childrenA && !childrenB) { return; } if (!childrenB || !childrenB.length) { if (childrenA && childrenA.length) { patchOps.removeChildren(this); } return; } if (!childrenA || !childrenA.length) { var childrenBLen = childrenB.length; var iB = 0; while (iB < childrenBLen) { patchOps.appendChild(node, childrenB[iB++]); } return; } patchChildren(this, node); } }; if (IS_DEBUG) { FragmentNode.prototype.setRef = function () { throw Error('vidom: Fragment nodes don\'t support refs.'); }; } function processChildren$1(children) { if (children == null) { return null; } var res = Array.isArray(children) ? children : [children]; if (IS_DEBUG) { checkChildren(res); } return res; } function merge(source1, source2) { var res = {}; for (var key in source1) { res[key] = source1[key]; } for (var _key in source2) { res[_key] = source2[_key]; } return res; } var ATTRS_SET$1 = 4; var CHILDREN_SET$2 = 8; function FunctionComponentNode(component) { if (IS_DEBUG) { restrictObjProp(this, 'type'); restrictObjProp(this, 'key'); restrictObjProp(this, 'attrs'); restrictObjProp(this, 'children'); this.__isFrozen = false; } this.type = NODE_TYPE_FUNCTION_COMPONENT; this.key = null; this.attrs = obj; this.children = null; if (IS_DEBUG) { this.__isFrozen = true; this._sets = 0; } this._component = component; this._rootNode = null; this._ctx = obj; } FunctionComponentNode.prototype = { getDomNode: function () { return this._rootNode && this._rootNode.getDomNode(); }, setKey: setKey, setAttrs: function (attrs) { if (IS_DEBUG) { if (this._sets & ATTRS_SET$1) { consoleWrapper.warn('Attrs are already set and shouldn\'t be set again.'); } this.__isFrozen = false; } this.attrs = this.attrs === obj ? attrs : merge(this.attrs, attrs); if (IS_DEBUG) { Object.freeze(this.attrs); this._sets |= ATTRS_SET$1; this.__isFrozen = true; } return this; }, setChildren: function (children) { if (IS_DEBUG) { if (this._sets & CHILDREN_SET$2) { consoleWrapper.warn('Children are already set and shouldn\'t be set again.'); } this.__isFrozen = false; } this.children = children; if (IS_DEBUG) { this._sets |= CHILDREN_SET$2; this.__isFrozen = true; } return this; }, setCtx: function (ctx) { this._ctx = ctx; return this; }, renderToDom: function (parentNs) { if (IS_DEBUG) { checkReuse(this, this._component.name || 'Anonymous'); } return this._getRootNode().renderToDom(parentNs); }, renderToString: function () { return this._getRootNode().renderToString(); }, adoptDom: function (domNode, domIdx) { if (IS_DEBUG) { checkReuse(this, this._component.name || 'Anonymous'); } return this._getRootNode().adoptDom(domNode, domIdx); }, mount: function () { this._getRootNode().mount(); }, unmount: function () { if (this._rootNode) { this._rootNode.unmount(); this._rootNode = null; } }, clone: function () { var res = new FunctionComponentNode(this._component); if (IS_DEBUG) { res.__isFrozen = false; } res.key = this.key; res.attrs = this.attrs; res.children = this.children; if (IS_DEBUG) { res.__isFrozen = true; } res._ctx = this._ctx; return res; }, patch: function (node) { if (this === node) { var prevRootNode = this._getRootNode(); this._rootNode = null; prevRootNode.patch(this._getRootNode()); } else if (this.type === node.type && this._component === node._component) { this._getRootNode().patch(node._getRootNode()); this._rootNode = null; } else { patchOps.replace(this, node); this._rootNode = null; } }, _getRootNode: function () { if (this._rootNode) { return this._rootNode; } var rootNode = this._component(this.attrs, this.children, this._ctx) || createNode('!'); if (IS_DEBUG) { if (typeof rootNode !== 'object' || Array.isArray(rootNode)) { throw Error('vidom: Function component must return a single node on the top level.'); } } rootNode.setCtx(this._ctx); return this._rootNode = rootNode; } }; if (IS_DEBUG) { FunctionComponentNode.prototype.setRef = function () { throw Error('vidom: Function component nodes don\'t support refs.'); }; } var CHILDREN_SET$3 = 8; function TextNode() { if (IS_DEBUG) { restrictObjProp(this, 'type'); restrictObjProp(this, 'key'); restrictObjProp(this, 'children'); this.__isFrozen = false; } this.type = NODE_TYPE_TEXT; this.key = null; this.children = null; if (IS_DEBUG) { this.__isFrozen = true; } this._domNode = null; } TextNode.prototype = { getDomNode: function () { return this._domNode; }, setKey: setKey, setChildren: function (children) { if (IS_DEBUG) { if (this._sets & CHILDREN_SET$3) { console.warn('Children are already set and shouldn\'t be set again.'); } this.__isFrozen = false; } this.children = processChildren$2(children); if (IS_DEBUG) { this._sets |= CHILDREN_SET$3; this.__isFrozen = true; } return this; }, setCtx: function () { return this; }, renderToDom: function () { if (IS_DEBUG) { checkReuse(this, 'text'); } var domFragment = document.createDocumentFragment(), domNode = [createElement('!'), createElement('!')], children = this.children; domFragment.appendChild(domNode[0]); if (children) { domFragment.appendChild(document.createTextNode(children)); } domFragment.appendChild(domNode[1]); this._domNode = domNode; return domFragment; }, renderToString: function () { return '<!---->' + (this.children || '') + '<!---->'; }, adoptDom: function (domNodes, domIdx) { if (IS_DEBUG) { checkReuse(this, 'text'); } var domNode = [domNodes[domIdx++]]; if (this.children) { domIdx++; } domNode.push(domNodes[domIdx++]); this._domNode = domNode; return domIdx; }, mount: noOp, unmount: noOp, clone: function () { var res = new TextNode(); if (IS_DEBUG) { res.__isFrozen = false; } res.key = this.key; res.children = this.children; if (IS_DEBUG) { res.__isFrozen = true; } return res; }, patch: function (node) { if (this !== node) { if (this.type === node.type) { node._domNode = this._domNode; this._patchChildren(node); } else { patchOps.replace(this, node); } } }, _patchChildren: function (node) { var childrenA = this.children, childrenB = node.children; if (childrenA !== childrenB) { if (childrenB) { patchOps.updateText(this, childrenB, false); } else if (childrenA) { patchOps.removeText(this); } } } }; if (IS_DEBUG) { TextNode.prototype.setRef = function () { throw Error('vidom: Text nodes don\'t support refs.'); }; } function processChildren$2(children) { return children == null || typeof children === 'string' ? children : children.toString(); } var raf = typeof window !== 'undefined' && (window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame) || function (callback) { setTimeout(callback, 1000 / 60); }; var batch = []; function applyBatch() { var i = 0; while (i < batch.length) { batch[i++](); } batch = []; } function rafBatch(fn) { batch.push(fn) === 1 && raf(applyBatch); } function Emitter() { this._listeners = {}; } Emitter.prototype = { on: function (event, fn) { var fnCtx = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; (this._listeners[event] || (this._listeners[event] = [])).push({ fn: fn, fnCtx: fnCtx }); return this; }, off: function (event, fn) { var fnCtx = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var eventListeners = this._listeners[event]; if (eventListeners) { var i = 0, eventListener = void 0; while (i < eventListeners.length) { eventListener = eventListeners[i]; if (eventListener.fn === fn && eventListener.fnCtx === fnCtx) { eventListeners.splice(i, 1); break; } i++; } } return this; }, emit: function (event) { var eventListeners = this._listeners[event]; if (eventListeners) { var i = 0; for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } while (i < eventListeners.length) { var _eventListeners = eventListeners[i++], fn = _eventListeners.fn, fnCtx = _eventListeners.fnCtx; fn.call.apply(fn, [fnCtx].concat(args)); } } return this; } }; function TopNode(childNode) { this.type = NODE_TYPE_TOP; this._childNode = childNode; this._ns = null; } TopNode.prototype = { getDomNode: function () { return this._childNode.getDomNode(); }, setNs: function (ns) { if (ns) { this._ns = ns; } return this; }, setCtx: function (ctx) { if (ctx) { this._childNode.setCtx(ctx); } return this; }, renderToDom: function () { return this._childNode.renderToDom(this._ns); }, adoptDom: function (domNode) { this._childNode.adoptDom(domNode, 0); }, patch: function (node) { this._childNode.patch(node._childNode); }, mount: function () { this._childNode.mount(); }, unmount: function () { this._childNode.unmount(); } }; var mountedNodes = new SimpleMap$1(); var counter$1 = 0; function mountToDomNode(domNode, node, ctx, cb, syncMode) { if (IS_DEBUG) { if (!isNode(node)) { throw TypeError('vidom: Unexpected type of node is passed to mount.'); } } var domNodeId = getDomNodeId(domNode); var mounted = mountedNodes.get(domNodeId), mountId = void 0; if (mounted && mounted.tree) { mountId = ++mounted.id; var patchFn = function () { mounted = mountedNodes.get(domNodeId); if (mounted && mounted.id === mountId) { var prevTree = mounted.tree, newTree = new TopNode(node); newTree.setNs(prevTree._ns).setCtx(ctx); prevTree.patch(newTree); mounted.tree = newTree; callCb(cb); if (IS_DEBUG) { hook.emit('replace', prevTree, newTree); } } }; syncMode ? patchFn() : rafBatch(patchFn); } else { mountedNodes.set(domNodeId, mounted = { tree: null, id: mountId = ++counter$1 }); if (domNode.childNodes.length) { var topDomChildNodes = collectTopDomChildNodes(domNode); if (topDomChildNodes) { var tree = mounted.tree = new TopNode(node); tree.setNs(getNs(domNode)).setCtx(ctx); tree.adoptDom(topDomChildNodes); tree.mount(); callCb(cb); if (IS_DEBUG) { hook.emit('mount', tree); } return; } else { domNode.textContent = ''; } } var renderFn = function () { var mounted = mountedNodes.get(domNodeId); if (mounted && mounted.id === mountId) { var _tree = mounted.tree = new TopNode(node); _tree.setNs(getNs(domNode)).setCtx(ctx); domOps.append(domNode, _tree.renderToDom()); _tree.mount(); callCb(cb); if (IS_DEBUG) { hook.emit('mount', _tree); } } }; syncMode ? renderFn() : rafBatch(renderFn); } } function unmountFromDomNode(domNode, cb, syncMode) { var domNodeId = getDomNodeId(domNode); var mounted = mountedNodes.get(domNodeId); if (mounted) { (function () { var mountId = ++mounted.id, unmountFn = function () { mounted = mountedNodes.get(domNodeId); if (mounted && mounted.id === mountId) { mountedNodes.delete(domNodeId); var tree = mounted.tree; if (tree) { var treeDomNode = tree.getDomNode(); tree.unmount(); domOps.remove(treeDomNode); } callCb(cb); if (IS_DEBUG) { tree && hook.emit('unmount', tree); } } }; mounted.tree ? syncMode ? unmountFn() : rafBatch(unmountFn) : syncMode || callCb(cb); })(); } else if (!syncMode) { callCb(cb); } } function callCb(cb) { cb && cb(); } function collectTopDomChildNodes(node) { var childNodes = node.childNodes, len = childNodes.length; var i = 0, res = void 0, childNode = void 0; while (i < len) { childNode = childNodes[i++]; if (res) { res.push(childNode); } else if (childNode.nodeType === Node.COMMENT_NODE && childNode.textContent === 'vidom') { res = []; } } return res; } function mount(domNode, tree, ctx, cb) { if (typeof ctx === 'function') { cb = ctx; ctx = this; } mountToDomNode(domNode, tree, ctx, cb, false); } function mountSync(domNode, tree, ctx) { mountToDomNode(domNode, tree, ctx, null, true); } function unmount(domNode, cb) { unmountFromDomNode(domNode, cb, false); } function unmountSync(domNode) { unmountFromDomNode(domNode, null, true); } function getMountedRootNodes() { var res = []; mountedNodes.forEach(function (_ref) { var tree = _ref.tree; if (tree) { res.push(tree); } }); return res; } var hook = new Emitter(); hook.getRootNodes = getMountedRootNodes; if (IS_DEBUG) { if (typeof window !== 'undefined') { window['__vidom__hook__'] = hook; } } function mountComponent() { this.__isMounted = true; this.onMount(); } function unmountComponent() { this.__isMounted = false; this.onUnmount(); } function patchComponent(nextAttrs, nextChildren, nextContext) { if (!this.isMounted()) { return; } nextAttrs = this.__buildAttrs(nextAttrs); var prevAttrs = this.attrs, prevChildren = this.children, prevContext = this.context; if (prevAttrs !== nextAttrs || prevChildren !== nextChildren || prevContext !== nextContext) { var isUpdating = this.__isUpdating; this.__isUpdating = true; if (prevAttrs !== nextAttrs) { if (IS_DEBUG) { this.__isFrozen = false; } this.attrs = nextAttrs; if (IS_DEBUG) { this.__isFrozen = true; } this.onAttrsChange(prevAttrs); } if (prevChildren !== nextChildren) { if (IS_DEBUG) { this.__isFrozen = false; } this.children = nextChildren; if (IS_DEBUG) { this.__isFrozen = true; } this.onChildrenChange(prevChildren); } if (prevContext !== nextContext) { if (IS_DEBUG) { this.__isFrozen = false; } this.context = nextContext; if (IS_DEBUG) { Object.freeze(this.context); this.__isFrozen = true; } this.onContextChange(prevContext); } this.__isUpdating = isUpdating; } if (this.__isUpdating) { return; } var shouldUpdate = this.shouldUpdate(prevAttrs, prevChildren, this.__prevState, prevContext); if (IS_DEBUG) { var shouldUpdateResType = typeof shouldUpdate; if (shouldUpdateResType !== 'boolean') { consoleWrapper.warn('Component#shouldUpdate() should return boolean instead of ' + shouldUpdateResType); } } if (shouldUpdate) { var prevRootNode = this.__rootNode; this.__rootNode = this.render(); prevRootNode.patch(this.__rootNode); this.onUpdate(prevAttrs, prevChildren, this.__prevState, prevContext); } } function shouldComponentUpdate() { return true; } function renderComponentToDom(parentNs) { return this.__rootNode.renderToDom(parentNs); } function renderComponentToString() { return this.__rootNode.renderToString(); } function adoptComponentDom(domNode, domIdx) { return this.__rootNode.adoptDom(domNode, domIdx); } function getComponentDomNode() { return this.__rootNode.getDomNode(); } function requestChildContext() { return obj; } function setComponentState(state) { var nextState = void 0; if (this.__rootNode) { // was inited this.update(this.state === this.__prevState ? updateComponentPrevState : null); nextState = merge(this.state, state); } else { nextState = state === obj ? state : merge(this.state, state); } if (IS_DEBUG) { this.__isFrozen = false; } this.state = nextState; if (IS_DEBUG) { Object.freeze(this.state); this.__isFrozen = true; } } function updateComponentPrevState() { this.__prevState = this.state; } function renderComponent() { var rootNode = this.onRender() || createNode('!'); if (IS_DEBUG) { if (typeof rootNode !== 'object' || Array.isArray(rootNode)) { throw TypeError('vidom: Component#onRender must return a single node on the top level.'); } } var childCtx = this.onChildContextRequest(), rootNodeCtx = childCtx === obj ? this.context : this.context === obj ? childCtx : merge(this.context, childCtx); if (IS_DEBUG) { Object.freeze(rootNodeCtx); } rootNode.setCtx(rootNodeCtx); return rootNode; } function updateComponent(cb) { var _this = this; if (this.__isUpdating) { cb && rafBatch(function () { return cb.call(_this); }); } else { this.__isUpdating = true; rafBatch(function () { if (_this.isMounted()) { _this.__isUpdating = false; var prevRootNode = _this.__rootNode; _this.patch(_this.attrs, _this.children, _this.context); cb && cb.call(_this); if (IS_DEBUG) { hook.emit('replace', prevRootNode, _this.__rootNode); } } }); } } function getComponentRootNode() { return this.__rootNode; } function isComponentMounted() { return this.__isMounted; } function onComponentRefRequest() { return this; } function buildComponentAttrs(attrs) { if (attrs === this.attrs) { return attrs; } var defaultAttrs = this.constructor.defaultAttrs, resAttrs = attrs === obj ? defaultAttrs || attrs : defaultAttrs ? merge(defaultAttrs, attrs) : attrs; if (IS_DEBUG) { Object.freeze(resAttrs); } return resAttrs; } function createComponent(props, staticProps) { var res = function (attrs, children, ctx) { if (IS_DEBUG) { restrictObjProp(this, 'attrs'); restrictObjProp(this, 'children'); restrictObjProp(this, 'state'); restrictObjProp(this, 'context'); this.__isFrozen = false; } this.attrs = this.__buildAttrs(attrs); this.children = children; this.state = obj; this.context = ctx; if (IS_DEBUG) { this.__isFrozen = true; } this.__isMounted = false; this.__isUpdating = false; this.onInit(); this.__prevState = this.state; this.__rootNode = this.render(); }, ptp = { constructor: res, onInit: noOp, mount: mountComponent, unmount: unmountComponent, onMount: noOp, onUnmount: noOp, onAttrsChange: noOp, onChildrenChange: noOp, onContextChange: noOp, shouldUpdate: shouldComponentUpdate, onUpdate: noOp, isMounted: isComponentMounted, setState: setComponentState, renderToDom: renderComponentToDom, renderToString: renderComponentToString, adoptDom: adoptComponentDom, getDomNode: getComponentDomNode, getRootNode: getComponentRootNode, render: renderComponent, onRender: noOp, update: updateComponent, patch: patchComponent, onChildContextRequest: requestChildContext, onRefRequest: onComponentRefRequest, __buildAttrs: buildComponentAttrs }; for (var i in props) { ptp[i] = props[i]; } res.prototype = ptp; for (var _i in staticProps) { res[_i] = staticProps[_i]; } res['__vidom__component__'] = true; return res; } var Input = createComponent({ onInit: function () { var _this = this; this._addAttrs = { onChange: null, onInput: function (e) { _this.onInput(e); } }; }, onRender: function () { return new TagNode('input').setAttrs(merge(this.attrs, this._addAttrs)); }, onInput: function (e) { var onChange = this.attrs.onChange; onChange && onChange(e); applyBatch(); if (this.isMounted()) { var control = this.getDomNode(), value = this.attrs.value; // attrs could be changed during applyBatch() if (typeof value !== 'undefined' && control.value !== value) { control.value = value; } } }, onRefRequest: function () { return this.getDomNode(); } }); var namedRadioInputs = new SimpleMap$1(); var Radio = createComponent({ onInit: function () { var _this = this; this._addAttrs = { onChange: function (e) { _this.onChange(e); } }; }, onRender: function () { return new TagNode('input').setAttrs(merge(this.attrs, this._addAttrs)); }, onMount: function () { var name = this.attrs.name; if (name) { addToNamedRadioInputs(name, this); } }, onUpdate: function (_ref) { var prevName = _ref.name; var name = this.attrs.name; if (name !== prevName) { if (prevName) { removeFromNamedRadioInputs(prevName, this); } if (name) { addToNamedRadioInputs(name, this); } } }, onUnmount: function () { var name = this.attrs.name; if (name) { removeFromNamedRadioInputs(name, this); } }, onChange: function (e) { var onChange = this.attrs.onChange; onChange && onChange(e); applyBatch(); if (this.isMounted()) { var control = this.getDomNode(), _attrs = this.attrs, name = _attrs.name, checked = _attrs.checked; // attrs could be changed during applyBatch() if (typeof checked !== 'undefined' && control.checked !== checked) { if (name) { var radioInputs = namedRadioInputs.get(name), len = radioInputs.length; var i = 0, radioInput = void 0, _checked = void 0; while (i < len) { radioInput = radioInputs[i++]; _checked = radioInput.attrs.checked; if (typeof _checked !== 'undefined') { var radioControl = radioInput.getDomNode(); if (_checked !== radioControl.checked) { radioControl.checked = _checked; } } } } else { control.checked = checked; } } } }, onRefRequest: function () { return this.getDomNode(); } }); function addToNamedRadioInputs(name, input) { var radioInputs = namedRadioInputs.get(name); if (radioInputs) { radioInputs.push(input); } else { namedRadioInputs.set(name, [input]); } } function removeFromNamedRadioInputs(name, input) { var radioInputs = namedRadioInputs.get(name), len = radioInputs.length; var i = 0; while (i < len) { if (radioInputs[i] === input) { if (len === 1) { namedRadioInputs.delete(name); } else { radioInputs.splice(i, 1); } return; } i++; } } var CheckBox = createComponent({ onInit: function () { var _this = this; this._addAttrs = { onChange: function (e) { _this.onChange(e); } }; }, onRender: function () { return new TagNode('input').setAttrs(merge(this.attrs, this._addAttrs)); }, onChange: function (e) { var onChange = this.attrs.onChange; onChange && onChange(e); applyBatch(); if (this.isMounted()) { var control = this.getDomNode(), checked = this.attrs.checked; // attrs could be changed during applyBatch() if (typeof checked !== 'undefined' && control.checked !== checked) { control.checked = checked; } } }, onRefRequest: function () { return this.getDomNode(); } }); var File = createComponent({ onRender: function () { return new TagNode('input').setAttrs(this.attrs); }, onRefRequest: function () { return this.getDomNode(); } }); var ATTRS_SET$2 = 4; var CHILDREN_SET$4 = 8; function ComponentNode(component) { if (IS_DEBUG) { restrictObjProp(this, 'type'); restrictObjProp(this, 'key'); restrictObjProp(this, 'attrs'); restrictObjProp(this, 'children'); this.__isFrozen = false; } this.type = NODE_TYPE_COMPONENT; this.key = null; this.attrs = obj; this.children = null; if (IS_DEBUG) { this.__isFrozen = true; this._sets = 0; } this._component = component; this._instance = null; this._ctx = obj; this._ref = null; } ComponentNode.prototype = { getDomNode: function () { return this._instance && this._instance.getDomNode(); }, setKey: setKey, setRef: setRef, setAttrs: function (attrs) { if (IS_DEBUG) { if (this._sets & ATTRS_SET$2) { console.warn('Attrs are already set and shouldn\'t be set again.'); } this.__isFrozen = false; } this.attrs = this.attrs === obj ? attrs : merge(this.attrs, attrs); if (IS_DEBUG) { Object.freeze(this.attrs); this._sets |= ATTRS_SET$2; this.__isFrozen = true; } if (this._component === Input) { switch (this.attrs.type) { case 'radio': this._component = Radio; break; case 'checkbox': this._component = CheckBox; break; case 'file': this._component = File; break; } } return this; }, setChildren: function (children) { if (IS_DEBUG) { if (this._sets & CHILDREN_SET$4) { console.warn('Children are already set and shouldn\'t be set again.'); } this.__isFrozen = false; } this.children = children; if (IS_DEBUG) { this._sets |= CHILDREN_SET$4; this.__isFrozen = true; } return this; }, setCtx: function (ctx) { this._ctx = ctx; return this; }, renderToDom: function (parentNs) { if (IS_DEBUG) { checkReuse(this, this._component.name || 'Anonymous'); } return this._getInstance().renderToDom(parentNs); }, renderToString: function () { return this._getInstance().renderToString(); }, adoptDom: function (domNode, domIdx) { if (IS_DEBUG) { checkReuse(this, this._component.name || 'Anonymous'); } return this._getInstance().adoptDom(domNode, domIdx); }, mount: function () { this._instance.getRootNode().mount(); this._instance.mount(); this._ref && this._ref(this._instance.onRefRequest()); }, unmount: function () { if (this._instance) { this._instance.getRootNode().unmount(); this._instance.unmount(); this._instance = null; this._ref && this._ref(null); } }, clone: function () { var res = new ComponentNode(this._component); if (IS_DEBUG) { res.__isFrozen = false; } res.key = this.key; res.attrs = this.attrs; res.children = this.children; if (IS_DEBUG) { res.__isFrozen = true; } res._ctx = this._ctx; res._ref = this._ref; return res; }, patch: function (node) { var instance = this._getInstance(); if (this === node) { instance.patch(node.attrs, node.children, node._ctx); } else if (this.type === node.type && this._component === node._component) { instance.patch(node.attrs, node.children, node._ctx); node._instance = instance; this._patchRef(node); } else { patchOps.replace(this, node); this._instance = null; } }, _patchRef: function (node) { if (this._ref) { if (this._ref !== node._ref) { this._ref(null); if (node._ref) { node._ref(node._instance.onRefRequest()); } } } else if (node._ref) { node._ref(node._instance.onRefRequest()); } }, _getInstance: function () { return this._instance || (this._instance = new this._component(this.attrs, this.children, this._ctx)); } }; function isNode(obj) { return obj instanceof ComponentNode || obj instanceof FragmentNode || obj instanceof FunctionComponentNode || obj instanceof TagNode || obj instanceof TextNode; } function checkChildren(children) { var keys = {}, len = children.length; var i = 0, child = void 0; while (i < len) { child = children[i++]; if (!isNode(child)) { throw TypeError('vidom: Unexpected type of child. Only a node is expected to be here.'); } if (child.key != null) { if (child.key in keys) { throw Error('vidom: Childrens\' keys must be unique across the children. ' + ('Found duplicate of "' + child._key + '" key.')); } else { keys[child.key] = true; } } } } var AMP_RE$1 = /&/g; var LT_RE = /</g; var GT_RE = />/g; function escapeHtml(str) { str = str + ''; var i = str.length, escapes = 0; // 1 — escape '&', 2 — escape '<', 4 — escape '>' while (i--) { switch (str[i]) { case '&': escapes |= 1; break; case '<': escapes |= 2; break; case '>': escapes |= 4; break; } } if (escapes & 1) { str = str.replace(AMP_RE$1, '&amp;'); } if (escapes & 2) { str = str.replace(LT_RE, '&lt;'); } if (escapes & 4) { str = str.replace(GT_RE, '&gt;'); } return str; } var TOP_LEVEL_NS_TAGS = { 'http://www.w3.org/2000/svg': 'svg', 'http://www.w3.org/1998/Math/MathML': 'math' }; var parentTags = { thead: 'table', tbody: 'table', tfoot: 'table', tr: 'tbody', td: 'tr' }; var helperDomNodes = {}; function createElementByHtml(html, tag, ns) { var parentTag = parentTags[tag] || 'div', helperDomNode = helperDomNodes[parentTag] || (helperDomNodes[parentTag] = document.createElement(parentTag)); if (!ns || !TOP_LEVEL_NS_TAGS[ns] || TOP_LEVEL_NS_TAGS[ns] === tag) { helperDomNode.innerHTML = html; return helperDomNode.removeChild(helperDomNode.firstChild); } var topLevelTag = TOP_LEVEL_NS_TAGS[ns]; helperDomNode.innerHTML = '<' + topLevelTag + ' xmlns="' + ns + '">' + html + '</' + topLevelTag + '>'; return helperDomNode.removeChild(helperDomNode.firstChild).firstChild; } var SHORT_TAGS = { area: true, base: true, br: true, col: true, command: true, embed: true, hr: true, img: true, input: true, keygen: true, link: true, menuitem: true, meta: true, param: true, source: true, track: true, wbr: true }; var USE_DOM_STRINGS = isTrident || isEdge; var ATTRS_SET = 4; var CHILDREN_SET = 8; var NS_SET = 16; function TagNode(tag) { if (IS_DEBUG) { restrictObjProp(this, 'type'); restrictObjProp(this, 'tag'); restrictObjProp(this, 'key'); restrictObjProp(this, 'attrs'); restrictObjProp(this, 'children'); this.__isFrozen = false; } this.type = NODE_TYPE_TAG; this.tag = tag; this.key = null; this.attrs = obj; this.children = null; if (IS_DEBUG) { this.__isFrozen = true; this._sets = 0; } this._domNode = null; this._ns = null; this._escapeChildren = true; this._ctx = obj; this._ref = null; } TagNode.prototype = { getDomNode: function () { return this._domNode; }, setKey: setKey, setRef: setRef, setNs: function (ns) { if (IS_DEBUG) { if (this._sets & NS_SET) { consoleWrapper.warn('Namespace is already set and shouldn\'t be set again.'); } } this._ns = ns; if (IS_DEBUG) { this._sets |= NS_SET; } return this; }, setAttrs: function (attrs) { if (IS_DEBUG) { if (this._sets & ATTRS_SET) { consoleWrapper.warn('Attrs are already set and shouldn\'t be set again.'); } checkAttrs(attrs); this.__isFrozen = false; } this.attrs = this.attrs === obj ? attrs : merge(this.attrs, attrs); if (IS_DEBUG) { Object.freeze(this.attrs); this._sets |= ATTRS_SET; this.__isFrozen = true; } return this; }, setChildren: function (children) { if (IS_DEBUG) { if (this._sets & CHILDREN_SET) { consoleWrapper.warn('Children are already set and shouldn\'t be set again.'); } this.__isFrozen = false; } this.children = processChildren(children); if (IS_DEBUG) { if (Array.isArray(this.children)) { Object.freeze(this.children); } this._sets |= CHILDREN_SET; this.__isFrozen = true; } return this; }, setHtml: function (html) { if (IS_DEBUG) { if (this._sets & CHILDREN_SET) { consoleWrapper.warn('Children are already set and shouldn\'t be set again.'); } this.__isFrozen = false; } this.children = html; if (IS_DEBUG) { this._sets |= CHILDREN_SET; this.__isFrozen = true; } this._escapeChildren = false; return this; }, setCtx: function (ctx) { if (ctx !== obj) { this._ctx = ctx; var children = this.children; if (children && typeof children !== 'string') { var len = children.length; var i = 0; while (i < len) { children[i++].setCtx(ctx); } } } return this; }, renderToDom: function (parentNs) { if (IS_DEBUG) { checkReuse(this, this.tag); } var tag = this.tag, children = this.children, ns = this._ns || parentNs; if (USE_DOM_STRINGS && children && typeof children !== 'string') { var _domNode = createElementByHtml(this.renderToString(), tag, ns); this.adoptDom([_domNode], 0); return _domNode; } var domNode = this._domNode = createElement(tag, ns), attrs = this.attrs; if (children) { if (typeof children === 'string') { this._escapeChildren ? domNode.textContent = children : domNode.innerHTML = children; } else { var i = 0; var len = children.length; while (i < len) { domNode.appendChild(children[i++].renderToDom(ns)); } } } if (attrs !== obj) { var name = void 0, value = void 0; for (name in attrs) { if ((value = attrs[name]) != null) { if (ATTRS_TO_EVENTS[name]) { addListener(domNode, ATTRS_TO_EVENTS[name], value); } else { domAttrs(name).set(domNode, name, value); } } } } return domNode; }, renderToString: function () { var tag = this.tag; if (tag === '!') { return '<!---->'; } var ns = this._ns, attrs = this.attrs; var children = this.children, res = '<' + tag; if (ns) { res += ' xmlns="' + ns + '"'; } if (attrs !== obj) { var name = void 0, value = void 0, attrHtml = void 0; for (name in attrs) { value = attrs[name]; if (value != null) { if (name === 'value') { switch (tag) { case 'textarea': children = value; continue; case 'select': this.setCtx({ value: value, multiple: attrs.multiple }); continue; case 'option': var ctx = this._ctx; if (ctx.multiple ? isInArray(ctx.value, value) : ctx.value === value) { res += ' ' + domAttrs('selected').toString('selected', true); } } } if (!ATTRS_TO_EVENTS[name] && (attrHtml = domAttrs(name).toString(name, value))) { res += ' ' + attrHtml; } } } } if (SHORT_TAGS[tag]) { res += '/>'; } else { res += '>'; if (children) { if (typeof children === 'string') { res += this._escapeChildren ? escapeHtml(children) : children; } else { var i = 0; var len = children.length; while (i < len) { res += children[i++].renderToString(); } } } res += '</' + tag + '>'; } return res; }, adoptDom: function (domNodes, domIdx) { if (IS_DEBUG) { checkReuse(this, this.tag); } var domNode = this._domNode = domNodes[domIdx], attrs = this.attrs, children = this.children; if (attrs !== obj) { var name = void 0, value = void 0; for (name in attrs) { if ((value = attrs[name]) != null && ATTRS_TO_EVENTS[name]) { addListener(domNode, ATTRS_TO_EVENTS[name], value); } } } if (children && typeof children !== 'string') { var i = 0; var len = children.length; if (len) { var domChildren = domNode.childNodes; var domChildIdx = 0; while (i < len) { domChildIdx = children[i++].adoptDom(domChildren, domChildIdx); } } } return domIdx + 1; }, mount: function () { var children = this.children; if (children && typeof children !== 'string') { var i = 0; var len = children.length; while (i < len) { children[i++].mount(); } } this._ref && this._ref(this._domNode); }, unmount: function () { var children = this.children; if (children && typeof children !== 'string') { var i = 0; var len = children.length; while (i < len) { children[i++].unmount(); } } removeListeners(this._domNode); this._domNode = null; this._ref && this._ref(null); }, clone: function () { var res = new TagNode(this.tag); if (IS_DEBUG) { res.__isFrozen = false; } res.key = this.key; res.attrs = this.attrs; res.children = this.children; if (IS_DEBUG) { res.__isFrozen = true; } res._sets = NS_SET; res._ns = this._ns; res._escapeChildren = this._escapeChildren; res._ctx = this._ctx; res._ref = this._ref; return res; }, patch: function (node) { if (this === node) { this._patchChildren(node); } else if (this.type === node.type && this.tag === node.tag && this._ns === node._ns) { node._domNode = this._domNode; this._patchAttrs(node); this._patchChildren(node); this._patchRef(node); } else { patchOps.replace(this, node); } }, _patchChildren: function (node) { var childrenA = this.children, childrenB = node.children; if (!childrenA && !childrenB) { return; } var isChildrenAText = typeof childrenA === 'string', isChildrenBText = typeof childrenB === 'string'; if (isChildrenBText) { if (isChildrenAText) { if (childrenA !== childrenB) { patchOps.updateText(this, childrenB, node._escapeChildren); } return; } childrenA && childrenA.length && patchOps.removeChildren(this); childrenB && patchOps.updateText(this, childrenB, node._escapeChildren); return; } if (!childrenB || !childrenB.length) { if (childrenA) { isChildrenAText ? patchOps.removeText(this) : childrenA.length && patchOps.removeChildren(this); } return; } if (isChildrenAText && childrenA) { patchOps.removeText(this); } if (isChildrenAText || !childrenA || !childrenA.length) { var childrenBLen = childrenB.length; var iB = 0; while (iB < childrenBLen) { patchOps.appendChild(node, childrenB[iB++]); } return; } patchChildren(this, node); }, _patchAttrs: function (node) { var attrsA = this.attrs, attrsB = node.attrs; if (attrsA === attrsB) { return; } var attrName = void 0; if (attrsB !== obj) { var attrAVal = void 0, attrBVal = void 0, isAttrAValArray = void 0, isAttrBValArray = void 0; for (attrName in attrsB) { attrBVal = attrsB[attrName]; if (attrsA === obj || (attrAVal = attrsA[attrName]) == null) { if (attrBVal != null) { patchOps.updateAttr(this, attrName, attrBVal); } } else if (attrBVal == null) { patchOps.removeAttr(this, attrName); } else if (typeof attrBVal === 'object' && typeof attrAVal === 'object') { isAttrBValArray = Array.isArray(attrBVal); isAttrAValArray = Array.isArray(attrAVal); if (isAttrBValArray || isAttrAValArray) { if (isAttrBValArray && isAttrAValArray) { this._patchAttrArr(attrName, attrAVal, attrBVal); } else { patchOps.updateAttr(this, attrName, attrBVal); } } else { this._patchAttrObj(attrName, attrAVal, attrBVal); } } else if (attrAVal !== attrBVal) { patchOps.updateAttr(this, attrName, attrBVal); } } } if (attrsA !== obj) { for (attrName in attrsA) { if ((attrsB === obj || !(attrName in attrsB)) && attrsA[attrName] != null) { patchOps.removeAttr(this, attrName); } } } }, _patchAttrArr: function (attrName, arrA, arrB) { if (arrA === arrB) { return; } var lenA = arrA.length; var hasDiff = false; if (lenA === arrB.length) { var i = 0; while (!hasDiff && i < lenA) { if (arrA[i] != arrB[i]) { hasDiff = true; } ++i; } } else { hasDiff = true; } hasDiff && patchOps.updateAttr(this, attrName, arrB); }, _patchAttrObj: function (attrName, objA, objB) { if (objA === objB) { return; } var diffObj = {}; var hasDiff = false; for (var i in objB) { if (objA[i] != objB[i]) { hasDiff = true; diffObj[i] = objB[i]; } } for (var _i in objA) { if (objA[_i] != null && !(_i in objB)) { hasDiff = true; diffObj[_i] = null; } } hasDiff && patchOps.updateAttr(this, attrName, diffObj); }, _patchRef: function (node) { if (this._ref) { if (this._ref !== node._ref) { this._ref(null); if (node._ref) { node._ref(node._domNode); } } } else if (node._ref) { node._ref(node._domNode); } } }; function processChildren(children) { if (children == null) { return null; } var typeOfChildren = typeof children; if (typeOfChildren === 'object') { var res = Array.isArray(children) ? children : [children]; if (IS_DEBUG) { checkChildren(res); } return res; } return typeOfChildren === 'string' ? children : children.toString(); } function checkAttrs(attrs) { for (var name in attrs) { if (name.substr(0, 2) === 'on' && !ATTRS_TO_EVENTS[name]) { throw Error('vidom: Unsupported type of dom event listener "' + name + '".'); } } } var TextArea = createComponent({ onInit: function () { var _this = this; this._addAttrs = { onChange: null, onInput: function (e) { _this.onInput(e); } }; }, onRender: function () { return new TagNode('textarea').setAttrs(merge(this.attrs, this._addAttrs)); }, onInput: function (e) { var onChange = this.attrs.onChange; onChange && onChange(e); applyBatch(); if (this.isMounted()) { var control = this.getDomNode(), value = this.attrs.value; // attrs could be changed during applyBatch() if (typeof value !== 'undefined' && control.value !== value) { control.value = value; } } }, onRefRequest: function () { return this.getDomNode(); } }); var Select = createComponent({ onInit: function () { var _this = this; this._addAttrs = { onChange: function (e) { _this.onChange(e); } }; }, onRender: function () { return new TagNode('select').setAttrs(merge(this.attrs, this._addAttrs)).setChildren(this.children); }, onChange: function (e) { var target = e.target, _attrs = this.attrs, onChange = _attrs.onChange, multiple = _attrs.multiple; if (onChange) { if (multiple) { var newValue = [], options = target.options, len = options.length; var i = 0, option = void 0; while (i < len) { option = options[i++]; if (option.selected) { newValue.push(option.value); } } onChange(e, newValue); } else { onChange(e); } } applyBatch(); if (this.isMounted()) { var _attrs2 = this.attrs, value = _attrs2.value, _multiple = _attrs2.multiple; // attrs could be changed during applyBatch() if (typeof value !== 'undefined') { if (_multiple) { var _options = target.options, _len = _options.length; var _i = 0, _option = void 0; while (_i < _len) { _option = _options[_i++]; _option.selected = isInArray(value, _option.value); } } else if (target.value != value) { target.value = value; } } } }, onRefRequest: function () { return this.getDomNode(); } }); function createNode(type) { switch (typeof type) { case 'string': switch (type) { case 'fragment': return new FragmentNode(); case 'text': return new TextNode(); case 'input': return new ComponentNode(Input); case 'textarea': return new ComponentNode(TextArea); case 'select': return new ComponentNode(Select); default: return new TagNode(type); } case 'function': return type.__vidom__component__ ? new ComponentNode(type) : new FunctionComponentNode(type); default: if (IS_DEBUG) { throw TypeError('vidom: Unexpected type of node is passed to the node factory.'); } } } function renderToString(tree) { return '<!--vidom-->' + tree.renderToString(); } function normalizeChildren(children) { if (children == null) { return null; } var typeOfChildren = typeof children; if (typeOfChildren !== 'object') { return typeOfChildren === 'string' ? children || null : '' + children; } if (!Array.isArray(children)) { return children; } if (!children.length) { return null; } var res = children, i = 0, hasContentBefore = false, child = void 0; var len = children.length, alreadyNormalizeChildren = {}; while (i < len) { child = i in alreadyNormalizeChildren ? alreadyNormalizeChildren[i] : normalizeChildren(children[i]); if (child === null) { if (res !== null) { if (!hasContentBefore) { res = null; } else if (res === children) { res = children.slice(0, i); } } } else if (typeof child === 'object') { if (Array.isArray(child)) { res = hasContentBefore ? (res === children ? res.slice(0, i) : Array.isArray(res) ? res : [toNode(res)]).concat(child) : child; } else if (res !== children) { if (!hasContentBefore) { res = child; } else if (Array.isArray(res)) { res.push(child); } else { res = [toNode(res), child]; } } else if (child !== children[i]) { if (hasContentBefore) { res = res.slice(0, i); res.push(child); } else { res = child; } } hasContentBefore = true; } else { var nextChild = void 0, j = i; // join all next text nodes while (++j < len) { nextChild = alreadyNormalizeChildren[j] = normalizeChildren(children[j]); if (typeof nextChild === 'string') { child += nextChild; } else if (nextChild !== null) { break; } } if (hasContentBefore) { if (Array.isArray(res)) { if (res === children) { res = res.slice(0, i); } res.push(toNode(child)); } else { res = [res, toNode(child)]; } } else { res = '' + child; } i = j - 1; hasContentBefore = true; } ++i; } return res; } function toNode(obj) { return typeof obj === 'object' ? obj : createNode('text').setChildren(obj); } var Component = createComponent(); exports.node = createNode; exports.createComponent = createComponent; exports.renderToString = renderToString; exports.normalizeChildren = normalizeChildren; exports.IS_DEBUG = IS_DEBUG; exports.console = consoleWrapper; exports.Component = Component; exports.mount = mount; exports.mountSync = mountSync; exports.unmount = unmount; exports.unmountSync = unmountSync; exports.getMountedRootNodes = getMountedRootNodes; Object.defineProperty(exports, '__esModule', { value: true }); })));
{ "content_hash": "4306b91f5b507b0ef91e379c1e3a347a", "timestamp": "", "source": "github", "line_count": 3572, "max_line_length": 363, "avg_line_length": 25.5498320268757, "alnum_prop": 0.5172576262272089, "repo_name": "sashberd/cdnjs", "id": "be2df1826e2630c42e3be40a283f639f2d247113", "size": "91274", "binary": false, "copies": "23", "ref": "refs/heads/master", "path": "ajax/libs/vidom/0.8.6/vidom.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package org.apache.orc.impl; import org.apache.orc.CompressionKind; import java.io.IOException; import java.math.BigDecimal; import java.sql.Date; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; import org.apache.orc.OrcFile; import org.apache.orc.util.BloomFilter; import org.apache.orc.util.BloomFilterIO; import org.apache.orc.BooleanColumnStatistics; import org.apache.orc.ColumnStatistics; import org.apache.orc.CompressionCodec; import org.apache.orc.DataReader; import org.apache.orc.DateColumnStatistics; import org.apache.orc.DecimalColumnStatistics; import org.apache.orc.DoubleColumnStatistics; import org.apache.orc.IntegerColumnStatistics; import org.apache.orc.OrcConf; import org.apache.orc.OrcProto; import org.apache.orc.Reader; import org.apache.orc.RecordReader; import org.apache.orc.StringColumnStatistics; import org.apache.orc.StripeInformation; import org.apache.orc.TimestampColumnStatistics; import org.apache.orc.TypeDescription; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.common.io.DiskRange; import org.apache.hadoop.hive.common.io.DiskRangeList; import org.apache.hadoop.hive.common.io.DiskRangeList.CreateHelper; import org.apache.hadoop.hive.common.type.HiveDecimal; import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch; import org.apache.hadoop.hive.ql.io.sarg.PredicateLeaf; import org.apache.hadoop.hive.ql.io.sarg.SearchArgument; import org.apache.hadoop.hive.ql.io.sarg.SearchArgument.TruthValue; import org.apache.hadoop.hive.serde2.io.DateWritable; import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable; import org.apache.hadoop.hive.ql.util.TimestampUtils; import org.apache.hadoop.io.Text; public class RecordReaderImpl implements RecordReader { static final Logger LOG = LoggerFactory.getLogger(RecordReaderImpl.class); private static final boolean isLogDebugEnabled = LOG.isDebugEnabled(); private static final Object UNKNOWN_VALUE = new Object(); protected final Path path; private final long firstRow; private final List<StripeInformation> stripes = new ArrayList<StripeInformation>(); private OrcProto.StripeFooter stripeFooter; private final long totalRowCount; protected final TypeDescription schema; private final List<OrcProto.Type> types; private final int bufferSize; private final SchemaEvolution evolution; // the file included columns indexed by the file's column ids. private final boolean[] fileIncluded; private final long rowIndexStride; private long rowInStripe = 0; private int currentStripe = -1; private long rowBaseInStripe = 0; private long rowCountInStripe = 0; private final Map<StreamName, InStream> streams = new HashMap<StreamName, InStream>(); DiskRangeList bufferChunks = null; private final TreeReaderFactory.TreeReader reader; private final OrcProto.RowIndex[] indexes; private final OrcProto.BloomFilterIndex[] bloomFilterIndices; private final OrcProto.Stream.Kind[] bloomFilterKind; private final SargApplier sargApp; // an array about which row groups aren't skipped private boolean[] includedRowGroups = null; private final DataReader dataReader; private final boolean ignoreNonUtf8BloomFilter; private final OrcFile.WriterVersion writerVersion; /** * Given a list of column names, find the given column and return the index. * * @param evolution the mapping from reader to file schema * @param columnName the column name to look for * @return the file column number or -1 if the column wasn't found */ static int findColumns(SchemaEvolution evolution, String columnName) { TypeDescription readerSchema = evolution.getReaderBaseSchema(); List<String> fieldNames = readerSchema.getFieldNames(); List<TypeDescription> children = readerSchema.getChildren(); for (int i = 0; i < fieldNames.size(); ++i) { if (columnName.equals(fieldNames.get(i))) { TypeDescription result = evolution.getFileType(children.get(i)); return result == null ? -1 : result.getId(); } } return -1; } /** * Find the mapping from predicate leaves to columns. * @param sargLeaves the search argument that we need to map * @param evolution the mapping from reader to file schema * @return an array mapping the sarg leaves to concrete column numbers in the * file */ public static int[] mapSargColumnsToOrcInternalColIdx(List<PredicateLeaf> sargLeaves, SchemaEvolution evolution) { int[] result = new int[sargLeaves.size()]; Arrays.fill(result, -1); for(int i=0; i < result.length; ++i) { String colName = sargLeaves.get(i).getColumnName(); result[i] = findColumns(evolution, colName); } return result; } /** * Given a list of column names, find the given column and return the index. * * @param columnNames the list of potential column names * @param columnName the column name to look for * @param rootColumn offset the result with the rootColumn * @return the column number or -1 if the column wasn't found */ private static int findColumns(String[] columnNames, String columnName, int rootColumn) { for(int i=0; i < columnNames.length; ++i) { if (columnName.equals(columnNames[i])) { return i + rootColumn; } } return -1; } /** * Find the mapping from predicate leaves to columns. * @param sargLeaves the search argument that we need to map * @param columnNames the names of the columns * @param rootColumn the offset of the top level row, which offsets the * result * @return an array mapping the sarg leaves to concrete column numbers * @deprecated Use #mapSargColumnsToOrcInternalColIdx(List, SchemaEvolution) */ @Deprecated public static int[] mapSargColumnsToOrcInternalColIdx(List<PredicateLeaf> sargLeaves, String[] columnNames, int rootColumn) { int[] result = new int[sargLeaves.size()]; Arrays.fill(result, -1); for(int i=0; i < result.length; ++i) { String colName = sargLeaves.get(i).getColumnName(); result[i] = findColumns(columnNames, colName, rootColumn); } return result; } protected RecordReaderImpl(ReaderImpl fileReader, Reader.Options options) throws IOException { this.writerVersion = fileReader.getWriterVersion(); if (options.getSchema() == null) { if (LOG.isInfoEnabled()) { LOG.info("Reader schema not provided -- using file schema " + fileReader.getSchema()); } evolution = new SchemaEvolution(fileReader.getSchema(), null, options); } else { // Now that we are creating a record reader for a file, validate that // the schema to read is compatible with the file schema. // evolution = new SchemaEvolution(fileReader.getSchema(), options.getSchema(), options); if (LOG.isDebugEnabled() && evolution.hasConversion()) { LOG.debug("ORC file " + fileReader.path.toString() + " has data type conversion --\n" + "reader schema: " + options.getSchema().toString() + "\n" + "file schema: " + fileReader.getSchema()); } } this.schema = evolution.getReaderSchema(); this.path = fileReader.path; this.types = fileReader.types; this.bufferSize = fileReader.bufferSize; this.rowIndexStride = fileReader.rowIndexStride; this.ignoreNonUtf8BloomFilter = OrcConf.IGNORE_NON_UTF8_BLOOM_FILTERS.getBoolean(fileReader.conf); SearchArgument sarg = options.getSearchArgument(); if (sarg != null && rowIndexStride != 0) { sargApp = new SargApplier(sarg, rowIndexStride, evolution, writerVersion); } else { sargApp = null; } long rows = 0; long skippedRows = 0; long offset = options.getOffset(); long maxOffset = options.getMaxOffset(); for(StripeInformation stripe: fileReader.getStripes()) { long stripeStart = stripe.getOffset(); if (offset > stripeStart) { skippedRows += stripe.getNumberOfRows(); } else if (stripeStart < maxOffset) { this.stripes.add(stripe); rows += stripe.getNumberOfRows(); } } Boolean zeroCopy = options.getUseZeroCopy(); if (zeroCopy == null) { zeroCopy = OrcConf.USE_ZEROCOPY.getBoolean(fileReader.conf); } if (options.getDataReader() != null) { this.dataReader = options.getDataReader().clone(); } else { this.dataReader = RecordReaderUtils.createDefaultDataReader( DataReaderProperties.builder() .withBufferSize(bufferSize) .withCompression(fileReader.compressionKind) .withFileSystem(fileReader.fileSystem) .withPath(fileReader.path) .withTypeCount(types.size()) .withZeroCopy(zeroCopy) .build()); } this.dataReader.open(); firstRow = skippedRows; totalRowCount = rows; Boolean skipCorrupt = options.getSkipCorruptRecords(); if (skipCorrupt == null) { skipCorrupt = OrcConf.SKIP_CORRUPT_DATA.getBoolean(fileReader.conf); } TreeReaderFactory.ReaderContext readerContext = new TreeReaderFactory.ReaderContext() .setSchemaEvolution(evolution) .skipCorrupt(skipCorrupt); reader = TreeReaderFactory.createTreeReader(evolution.getReaderSchema(), readerContext); this.fileIncluded = evolution.getFileIncluded(); indexes = new OrcProto.RowIndex[types.size()]; bloomFilterIndices = new OrcProto.BloomFilterIndex[types.size()]; bloomFilterKind = new OrcProto.Stream.Kind[types.size()]; advanceToNextRow(reader, 0L, true); } public static final class PositionProviderImpl implements PositionProvider { private final OrcProto.RowIndexEntry entry; private int index; public PositionProviderImpl(OrcProto.RowIndexEntry entry) { this(entry, 0); } public PositionProviderImpl(OrcProto.RowIndexEntry entry, int startPos) { this.entry = entry; this.index = startPos; } @Override public long getNext() { return entry.getPositions(index++); } } public OrcProto.StripeFooter readStripeFooter(StripeInformation stripe ) throws IOException { return dataReader.readStripeFooter(stripe); } enum Location { BEFORE, MIN, MIDDLE, MAX, AFTER } /** * Given a point and min and max, determine if the point is before, at the * min, in the middle, at the max, or after the range. * @param point the point to test * @param min the minimum point * @param max the maximum point * @param <T> the type of the comparision * @return the location of the point */ static <T> Location compareToRange(Comparable<T> point, T min, T max) { int minCompare = point.compareTo(min); if (minCompare < 0) { return Location.BEFORE; } else if (minCompare == 0) { return Location.MIN; } int maxCompare = point.compareTo(max); if (maxCompare > 0) { return Location.AFTER; } else if (maxCompare == 0) { return Location.MAX; } return Location.MIDDLE; } /** * Get the maximum value out of an index entry. * @param index * the index entry * @return the object for the maximum value or null if there isn't one */ static Object getMax(ColumnStatistics index) { if (index instanceof IntegerColumnStatistics) { return ((IntegerColumnStatistics) index).getMaximum(); } else if (index instanceof DoubleColumnStatistics) { return ((DoubleColumnStatistics) index).getMaximum(); } else if (index instanceof StringColumnStatistics) { return ((StringColumnStatistics) index).getMaximum(); } else if (index instanceof DateColumnStatistics) { return ((DateColumnStatistics) index).getMaximum(); } else if (index instanceof DecimalColumnStatistics) { return ((DecimalColumnStatistics) index).getMaximum(); } else if (index instanceof TimestampColumnStatistics) { return ((TimestampColumnStatistics) index).getMaximum(); } else if (index instanceof BooleanColumnStatistics) { if (((BooleanColumnStatistics)index).getTrueCount()!=0) { return Boolean.TRUE; } else { return Boolean.FALSE; } } else { return null; } } /** * Get the minimum value out of an index entry. * @param index * the index entry * @return the object for the minimum value or null if there isn't one */ static Object getMin(ColumnStatistics index) { if (index instanceof IntegerColumnStatistics) { return ((IntegerColumnStatistics) index).getMinimum(); } else if (index instanceof DoubleColumnStatistics) { return ((DoubleColumnStatistics) index).getMinimum(); } else if (index instanceof StringColumnStatistics) { return ((StringColumnStatistics) index).getMinimum(); } else if (index instanceof DateColumnStatistics) { return ((DateColumnStatistics) index).getMinimum(); } else if (index instanceof DecimalColumnStatistics) { return ((DecimalColumnStatistics) index).getMinimum(); } else if (index instanceof TimestampColumnStatistics) { return ((TimestampColumnStatistics) index).getMinimum(); } else if (index instanceof BooleanColumnStatistics) { if (((BooleanColumnStatistics)index).getFalseCount()!=0) { return Boolean.FALSE; } else { return Boolean.TRUE; } } else { return UNKNOWN_VALUE; // null is not safe here } } /** * Evaluate a predicate with respect to the statistics from the column * that is referenced in the predicate. * @param statsProto the statistics for the column mentioned in the predicate * @param predicate the leaf predicate we need to evaluation * @param bloomFilter the bloom filter * @param writerVersion the version of software that wrote the file * @param type what is the kind of this column * @return the set of truth values that may be returned for the given * predicate. */ static TruthValue evaluatePredicateProto(OrcProto.ColumnStatistics statsProto, PredicateLeaf predicate, OrcProto.Stream.Kind kind, OrcProto.ColumnEncoding encoding, OrcProto.BloomFilter bloomFilter, OrcFile.WriterVersion writerVersion, TypeDescription.Category type) { ColumnStatistics cs = ColumnStatisticsImpl.deserialize(statsProto); Object minValue = getMin(cs); Object maxValue = getMax(cs); // files written before ORC-135 stores timestamp wrt to local timezone causing issues with PPD. // disable PPD for timestamp for all old files if (type.equals(TypeDescription.Category.TIMESTAMP)) { if (!writerVersion.includes(OrcFile.WriterVersion.ORC_135)) { LOG.debug("Not using predication pushdown on {} because it doesn't " + "include ORC-135. Writer version: {}", predicate.getColumnName(), writerVersion); return TruthValue.YES_NO_NULL; } if (predicate.getType() != PredicateLeaf.Type.TIMESTAMP && predicate.getType() != PredicateLeaf.Type.DATE && predicate.getType() != PredicateLeaf.Type.STRING) { return TruthValue.YES_NO_NULL; } } return evaluatePredicateRange(predicate, minValue, maxValue, cs.hasNull(), BloomFilterIO.deserialize(kind, encoding, writerVersion, type, bloomFilter)); } /** * Evaluate a predicate with respect to the statistics from the column * that is referenced in the predicate. * @param stats the statistics for the column mentioned in the predicate * @param predicate the leaf predicate we need to evaluation * @return the set of truth values that may be returned for the given * predicate. */ public static TruthValue evaluatePredicate(ColumnStatistics stats, PredicateLeaf predicate, BloomFilter bloomFilter) { Object minValue = getMin(stats); Object maxValue = getMax(stats); return evaluatePredicateRange(predicate, minValue, maxValue, stats.hasNull(), bloomFilter); } static TruthValue evaluatePredicateRange(PredicateLeaf predicate, Object min, Object max, boolean hasNull, BloomFilter bloomFilter) { // if we didn't have any values, everything must have been null if (min == null) { if (predicate.getOperator() == PredicateLeaf.Operator.IS_NULL) { return TruthValue.YES; } else { return TruthValue.NULL; } } else if (min == UNKNOWN_VALUE) { return TruthValue.YES_NO_NULL; } TruthValue result; Object baseObj = predicate.getLiteral(); // Predicate object and stats objects are converted to the type of the predicate object. Object minValue = getBaseObjectForComparison(predicate.getType(), min); Object maxValue = getBaseObjectForComparison(predicate.getType(), max); Object predObj = getBaseObjectForComparison(predicate.getType(), baseObj); result = evaluatePredicateMinMax(predicate, predObj, minValue, maxValue, hasNull); if (shouldEvaluateBloomFilter(predicate, result, bloomFilter)) { return evaluatePredicateBloomFilter(predicate, predObj, bloomFilter, hasNull); } else { return result; } } private static boolean shouldEvaluateBloomFilter(PredicateLeaf predicate, TruthValue result, BloomFilter bloomFilter) { // evaluate bloom filter only when // 1) Bloom filter is available // 2) Min/Max evaluation yield YES or MAYBE // 3) Predicate is EQUALS or IN list if (bloomFilter != null && result != TruthValue.NO_NULL && result != TruthValue.NO && (predicate.getOperator().equals(PredicateLeaf.Operator.EQUALS) || predicate.getOperator().equals(PredicateLeaf.Operator.NULL_SAFE_EQUALS) || predicate.getOperator().equals(PredicateLeaf.Operator.IN))) { return true; } return false; } private static TruthValue evaluatePredicateMinMax(PredicateLeaf predicate, Object predObj, Object minValue, Object maxValue, boolean hasNull) { Location loc; switch (predicate.getOperator()) { case NULL_SAFE_EQUALS: loc = compareToRange((Comparable) predObj, minValue, maxValue); if (loc == Location.BEFORE || loc == Location.AFTER) { return TruthValue.NO; } else { return TruthValue.YES_NO; } case EQUALS: loc = compareToRange((Comparable) predObj, minValue, maxValue); if (minValue.equals(maxValue) && loc == Location.MIN) { return hasNull ? TruthValue.YES_NULL : TruthValue.YES; } else if (loc == Location.BEFORE || loc == Location.AFTER) { return hasNull ? TruthValue.NO_NULL : TruthValue.NO; } else { return hasNull ? TruthValue.YES_NO_NULL : TruthValue.YES_NO; } case LESS_THAN: loc = compareToRange((Comparable) predObj, minValue, maxValue); if (loc == Location.AFTER) { return hasNull ? TruthValue.YES_NULL : TruthValue.YES; } else if (loc == Location.BEFORE || loc == Location.MIN) { return hasNull ? TruthValue.NO_NULL : TruthValue.NO; } else { return hasNull ? TruthValue.YES_NO_NULL : TruthValue.YES_NO; } case LESS_THAN_EQUALS: loc = compareToRange((Comparable) predObj, minValue, maxValue); if (loc == Location.AFTER || loc == Location.MAX) { return hasNull ? TruthValue.YES_NULL : TruthValue.YES; } else if (loc == Location.BEFORE) { return hasNull ? TruthValue.NO_NULL : TruthValue.NO; } else { return hasNull ? TruthValue.YES_NO_NULL : TruthValue.YES_NO; } case IN: if (minValue.equals(maxValue)) { // for a single value, look through to see if that value is in the // set for (Object arg : predicate.getLiteralList()) { predObj = getBaseObjectForComparison(predicate.getType(), arg); loc = compareToRange((Comparable) predObj, minValue, maxValue); if (loc == Location.MIN) { return hasNull ? TruthValue.YES_NULL : TruthValue.YES; } } return hasNull ? TruthValue.NO_NULL : TruthValue.NO; } else { // are all of the values outside of the range? for (Object arg : predicate.getLiteralList()) { predObj = getBaseObjectForComparison(predicate.getType(), arg); loc = compareToRange((Comparable) predObj, minValue, maxValue); if (loc == Location.MIN || loc == Location.MIDDLE || loc == Location.MAX) { return hasNull ? TruthValue.YES_NO_NULL : TruthValue.YES_NO; } } return hasNull ? TruthValue.NO_NULL : TruthValue.NO; } case BETWEEN: List<Object> args = predicate.getLiteralList(); if (args == null || args.isEmpty()) { return TruthValue.YES_NO; } Object predObj1 = getBaseObjectForComparison(predicate.getType(), args.get(0)); loc = compareToRange((Comparable) predObj1, minValue, maxValue); if (loc == Location.BEFORE || loc == Location.MIN) { Object predObj2 = getBaseObjectForComparison(predicate.getType(), args.get(1)); Location loc2 = compareToRange((Comparable) predObj2, minValue, maxValue); if (loc2 == Location.AFTER || loc2 == Location.MAX) { return hasNull ? TruthValue.YES_NULL : TruthValue.YES; } else if (loc2 == Location.BEFORE) { return hasNull ? TruthValue.NO_NULL : TruthValue.NO; } else { return hasNull ? TruthValue.YES_NO_NULL : TruthValue.YES_NO; } } else if (loc == Location.AFTER) { return hasNull ? TruthValue.NO_NULL : TruthValue.NO; } else { return hasNull ? TruthValue.YES_NO_NULL : TruthValue.YES_NO; } case IS_NULL: // min = null condition above handles the all-nulls YES case return hasNull ? TruthValue.YES_NO : TruthValue.NO; default: return hasNull ? TruthValue.YES_NO_NULL : TruthValue.YES_NO; } } private static TruthValue evaluatePredicateBloomFilter(PredicateLeaf predicate, final Object predObj, BloomFilter bloomFilter, boolean hasNull) { switch (predicate.getOperator()) { case NULL_SAFE_EQUALS: // null safe equals does not return *_NULL variant. So set hasNull to false return checkInBloomFilter(bloomFilter, predObj, false); case EQUALS: return checkInBloomFilter(bloomFilter, predObj, hasNull); case IN: for (Object arg : predicate.getLiteralList()) { // if atleast one value in IN list exist in bloom filter, qualify the row group/stripe Object predObjItem = getBaseObjectForComparison(predicate.getType(), arg); TruthValue result = checkInBloomFilter(bloomFilter, predObjItem, hasNull); if (result == TruthValue.YES_NO_NULL || result == TruthValue.YES_NO) { return result; } } return hasNull ? TruthValue.NO_NULL : TruthValue.NO; default: return hasNull ? TruthValue.YES_NO_NULL : TruthValue.YES_NO; } } private static TruthValue checkInBloomFilter(BloomFilter bf, Object predObj, boolean hasNull) { TruthValue result = hasNull ? TruthValue.NO_NULL : TruthValue.NO; if (predObj instanceof Long) { if (bf.testLong(((Long) predObj).longValue())) { result = TruthValue.YES_NO_NULL; } } else if (predObj instanceof Double) { if (bf.testDouble(((Double) predObj).doubleValue())) { result = TruthValue.YES_NO_NULL; } } else if (predObj instanceof String || predObj instanceof Text || predObj instanceof HiveDecimalWritable || predObj instanceof BigDecimal) { if (bf.testString(predObj.toString())) { result = TruthValue.YES_NO_NULL; } } else if (predObj instanceof Timestamp) { if (bf.testLong(SerializationUtils.convertToUtc(TimeZone.getDefault(), ((Timestamp) predObj).getTime()))) { result = TruthValue.YES_NO_NULL; } } else if (predObj instanceof Date) { if (bf.testLong(DateWritable.dateToDays((Date) predObj))) { result = TruthValue.YES_NO_NULL; } } else { // if the predicate object is null and if hasNull says there are no nulls then return NO if (predObj == null && !hasNull) { result = TruthValue.NO; } else { result = TruthValue.YES_NO_NULL; } } if (result == TruthValue.YES_NO_NULL && !hasNull) { result = TruthValue.YES_NO; } if (LOG.isDebugEnabled()) { LOG.debug("Bloom filter evaluation: " + result.toString()); } return result; } /** * An exception for when we can't cast things appropriately */ static class SargCastException extends IllegalArgumentException { public SargCastException(String string) { super(string); } } private static Object getBaseObjectForComparison(PredicateLeaf.Type type, Object obj) { if (obj == null) { return null; } switch (type) { case BOOLEAN: if (obj instanceof Boolean) { return obj; } else { // will only be true if the string conversion yields "true", all other values are // considered false return Boolean.valueOf(obj.toString()); } case DATE: if (obj instanceof Date) { return obj; } else if (obj instanceof String) { return Date.valueOf((String) obj); } else if (obj instanceof Timestamp) { return DateWritable.timeToDate(((Timestamp) obj).getTime() / 1000L); } // always string, but prevent the comparison to numbers (are they days/seconds/milliseconds?) break; case DECIMAL: if (obj instanceof Boolean) { return new HiveDecimalWritable(((Boolean) obj).booleanValue() ? HiveDecimal.ONE : HiveDecimal.ZERO); } else if (obj instanceof Integer) { return new HiveDecimalWritable(((Integer) obj).intValue()); } else if (obj instanceof Long) { return new HiveDecimalWritable(((Long) obj)); } else if (obj instanceof Float || obj instanceof Double || obj instanceof String) { return new HiveDecimalWritable(obj.toString()); } else if (obj instanceof BigDecimal) { return new HiveDecimalWritable(HiveDecimal.create((BigDecimal) obj)); } else if (obj instanceof HiveDecimal) { return new HiveDecimalWritable((HiveDecimal) obj); } else if (obj instanceof HiveDecimalWritable) { return obj; } else if (obj instanceof Timestamp) { return new HiveDecimalWritable(Double.toString( TimestampUtils.getDouble((Timestamp) obj))); } break; case FLOAT: if (obj instanceof Number) { // widening conversion return ((Number) obj).doubleValue(); } else if (obj instanceof HiveDecimal) { return ((HiveDecimal) obj).doubleValue(); } else if (obj instanceof String) { return Double.valueOf(obj.toString()); } else if (obj instanceof Timestamp) { return TimestampUtils.getDouble((Timestamp) obj); } else if (obj instanceof HiveDecimal) { return ((HiveDecimal) obj).doubleValue(); } else if (obj instanceof BigDecimal) { return ((BigDecimal) obj).doubleValue(); } break; case LONG: if (obj instanceof Number) { // widening conversion return ((Number) obj).longValue(); } else if (obj instanceof HiveDecimal) { return ((HiveDecimal) obj).longValue(); } else if (obj instanceof String) { return Long.valueOf(obj.toString()); } break; case STRING: return (obj.toString()); case TIMESTAMP: if (obj instanceof Timestamp) { return obj; } else if (obj instanceof Integer) { return new Timestamp(((Number) obj).longValue()); } else if (obj instanceof Float) { return TimestampUtils.doubleToTimestamp(((Float) obj).doubleValue()); } else if (obj instanceof Double) { return TimestampUtils.doubleToTimestamp(((Double) obj).doubleValue()); } else if (obj instanceof HiveDecimal) { return TimestampUtils.decimalToTimestamp((HiveDecimal) obj); } else if (obj instanceof HiveDecimalWritable) { return TimestampUtils.decimalToTimestamp(((HiveDecimalWritable) obj).getHiveDecimal()); } else if (obj instanceof Date) { return new Timestamp(((Date) obj).getTime()); } // float/double conversion to timestamp is interpreted as seconds whereas integer conversion // to timestamp is interpreted as milliseconds by default. The integer to timestamp casting // is also config driven. The filter operator changes its promotion based on config: // "int.timestamp.conversion.in.seconds". Disable PPD for integer cases. break; default: break; } throw new SargCastException(String.format( "ORC SARGS could not convert from %s to %s", obj.getClass() .getSimpleName(), type)); } public static class SargApplier { public final static boolean[] READ_ALL_RGS = null; public final static boolean[] READ_NO_RGS = new boolean[0]; private final OrcFile.WriterVersion writerVersion; private final SearchArgument sarg; private final List<PredicateLeaf> sargLeaves; private final int[] filterColumns; private final long rowIndexStride; // same as the above array, but indices are set to true private final boolean[] sargColumns; private SchemaEvolution evolution; private final long[] exceptionCount; public SargApplier(SearchArgument sarg, long rowIndexStride, SchemaEvolution evolution, OrcFile.WriterVersion writerVersion) { this.writerVersion = writerVersion; this.sarg = sarg; sargLeaves = sarg.getLeaves(); filterColumns = mapSargColumnsToOrcInternalColIdx(sargLeaves, evolution); this.rowIndexStride = rowIndexStride; // included will not be null, row options will fill the array with // trues if null sargColumns = new boolean[evolution.getFileIncluded().length]; for (int i : filterColumns) { // filter columns may have -1 as index which could be partition // column in SARG. if (i > 0) { sargColumns[i] = true; } } this.evolution = evolution; exceptionCount = new long[sargLeaves.size()]; } /** * Pick the row groups that we need to load from the current stripe. * * @return an array with a boolean for each row group or null if all of the * row groups must be read. * @throws IOException */ public boolean[] pickRowGroups(StripeInformation stripe, OrcProto.RowIndex[] indexes, OrcProto.Stream.Kind[] bloomFilterKinds, List<OrcProto.ColumnEncoding> encodings, OrcProto.BloomFilterIndex[] bloomFilterIndices, boolean returnNone) throws IOException { long rowsInStripe = stripe.getNumberOfRows(); int groupsInStripe = (int) ((rowsInStripe + rowIndexStride - 1) / rowIndexStride); boolean[] result = new boolean[groupsInStripe]; // TODO: avoid alloc? TruthValue[] leafValues = new TruthValue[sargLeaves.size()]; boolean hasSelected = false; boolean hasSkipped = false; TruthValue[] exceptionAnswer = new TruthValue[leafValues.length]; for (int rowGroup = 0; rowGroup < result.length; ++rowGroup) { for (int pred = 0; pred < leafValues.length; ++pred) { int columnIx = filterColumns[pred]; if (columnIx == -1) { // the column is a virtual column leafValues[pred] = TruthValue.YES_NO_NULL; } else if (exceptionAnswer[pred] != null) { leafValues[pred] = exceptionAnswer[pred]; } else { if (indexes[columnIx] == null) { throw new AssertionError("Index is not populated for " + columnIx); } OrcProto.RowIndexEntry entry = indexes[columnIx].getEntry(rowGroup); if (entry == null) { throw new AssertionError("RG is not populated for " + columnIx + " rg " + rowGroup); } OrcProto.ColumnStatistics stats = entry.getStatistics(); OrcProto.BloomFilter bf = null; OrcProto.Stream.Kind bfk = null; if (bloomFilterIndices != null && bloomFilterIndices[columnIx] != null) { bfk = bloomFilterKinds[columnIx]; bf = bloomFilterIndices[columnIx].getBloomFilter(rowGroup); } if (evolution != null && evolution.isPPDSafeConversion(columnIx)) { PredicateLeaf predicate = sargLeaves.get(pred); try { leafValues[pred] = evaluatePredicateProto(stats, predicate, bfk, encodings.get(columnIx), bf, writerVersion, evolution.getFileSchema(). findSubtype(columnIx).getCategory()); } catch (Exception e) { exceptionCount[pred] += 1; if (e instanceof SargCastException) { LOG.info("Skipping ORC PPD - " + e.getMessage() + " on " + predicate); } else { if (LOG.isWarnEnabled()) { final String reason = e.getClass().getSimpleName() + " when evaluating predicate." + " Skipping ORC PPD." + " Stats: " + stats + " Predicate: " + predicate; LOG.warn(reason, e); } } boolean hasNoNull = stats.hasHasNull() && !stats.getHasNull(); if (predicate.getOperator().equals(PredicateLeaf.Operator.NULL_SAFE_EQUALS) || hasNoNull) { exceptionAnswer[pred] = TruthValue.YES_NO; } else { exceptionAnswer[pred] = TruthValue.YES_NO_NULL; } leafValues[pred] = exceptionAnswer[pred]; } } else { leafValues[pred] = TruthValue.YES_NO_NULL; } if (LOG.isTraceEnabled()) { LOG.trace("Stats = " + stats); LOG.trace("Setting " + sargLeaves.get(pred) + " to " + leafValues[pred]); } } } result[rowGroup] = sarg.evaluate(leafValues).isNeeded(); hasSelected = hasSelected || result[rowGroup]; hasSkipped = hasSkipped || (!result[rowGroup]); if (LOG.isDebugEnabled()) { LOG.debug("Row group " + (rowIndexStride * rowGroup) + " to " + (rowIndexStride * (rowGroup + 1) - 1) + " is " + (result[rowGroup] ? "" : "not ") + "included."); } } return hasSkipped ? ((hasSelected || !returnNone) ? result : READ_NO_RGS) : READ_ALL_RGS; } /** * Get the count of exceptions for testing. * @return */ long[] getExceptionCount() { return exceptionCount; } } /** * Pick the row groups that we need to load from the current stripe. * * @return an array with a boolean for each row group or null if all of the * row groups must be read. * @throws IOException */ protected boolean[] pickRowGroups() throws IOException { // if we don't have a sarg or indexes, we read everything if (sargApp == null) { return null; } readRowIndex(currentStripe, fileIncluded, sargApp.sargColumns); return sargApp.pickRowGroups(stripes.get(currentStripe), indexes, bloomFilterKind, stripeFooter.getColumnsList(), bloomFilterIndices, false); } private void clearStreams() { // explicit close of all streams to de-ref ByteBuffers for (InStream is : streams.values()) { is.close(); } if (bufferChunks != null) { if (dataReader.isTrackingDiskRanges()) { for (DiskRangeList range = bufferChunks; range != null; range = range.next) { if (!(range instanceof BufferChunk)) { continue; } dataReader.releaseBuffer(((BufferChunk) range).getChunk()); } } } bufferChunks = null; streams.clear(); } /** * Read the current stripe into memory. * * @throws IOException */ private void readStripe() throws IOException { StripeInformation stripe = beginReadStripe(); includedRowGroups = pickRowGroups(); // move forward to the first unskipped row if (includedRowGroups != null) { while (rowInStripe < rowCountInStripe && !includedRowGroups[(int) (rowInStripe / rowIndexStride)]) { rowInStripe = Math.min(rowCountInStripe, rowInStripe + rowIndexStride); } } // if we haven't skipped the whole stripe, read the data if (rowInStripe < rowCountInStripe) { // if we aren't projecting columns or filtering rows, just read it all if (isFullRead() && includedRowGroups == null) { readAllDataStreams(stripe); } else { readPartialDataStreams(stripe); } reader.startStripe(streams, stripeFooter); // if we skipped the first row group, move the pointers forward if (rowInStripe != 0) { seekToRowEntry(reader, (int) (rowInStripe / rowIndexStride)); } } } private boolean isFullRead() { for (boolean isColumnPresent : fileIncluded){ if (!isColumnPresent){ return false; } } return true; } private StripeInformation beginReadStripe() throws IOException { StripeInformation stripe = stripes.get(currentStripe); stripeFooter = readStripeFooter(stripe); clearStreams(); // setup the position in the stripe rowCountInStripe = stripe.getNumberOfRows(); rowInStripe = 0; rowBaseInStripe = 0; for (int i = 0; i < currentStripe; ++i) { rowBaseInStripe += stripes.get(i).getNumberOfRows(); } // reset all of the indexes for (int i = 0; i < indexes.length; ++i) { indexes[i] = null; } return stripe; } private void readAllDataStreams(StripeInformation stripe) throws IOException { long start = stripe.getIndexLength(); long end = start + stripe.getDataLength(); // explicitly trigger 1 big read DiskRangeList toRead = new DiskRangeList(start, end); bufferChunks = dataReader.readFileData(toRead, stripe.getOffset(), false); List<OrcProto.Stream> streamDescriptions = stripeFooter.getStreamsList(); createStreams(streamDescriptions, bufferChunks, null, dataReader.getCompressionCodec(), bufferSize, streams); } /** * Plan the ranges of the file that we need to read given the list of * columns and row groups. * * @param streamList the list of streams available * @param indexes the indexes that have been loaded * @param includedColumns which columns are needed * @param includedRowGroups which row groups are needed * @param isCompressed does the file have generic compression * @param encodings the encodings for each column * @param types the types of the columns * @param compressionSize the compression block size * @return the list of disk ranges that will be loaded */ static DiskRangeList planReadPartialDataStreams (List<OrcProto.Stream> streamList, OrcProto.RowIndex[] indexes, boolean[] includedColumns, boolean[] includedRowGroups, boolean isCompressed, List<OrcProto.ColumnEncoding> encodings, List<OrcProto.Type> types, int compressionSize, boolean doMergeBuffers) { long offset = 0; // figure out which columns have a present stream boolean[] hasNull = RecordReaderUtils.findPresentStreamsByColumn(streamList, types); CreateHelper list = new CreateHelper(); for (OrcProto.Stream stream : streamList) { long length = stream.getLength(); int column = stream.getColumn(); OrcProto.Stream.Kind streamKind = stream.getKind(); // since stream kind is optional, first check if it exists if (stream.hasKind() && (StreamName.getArea(streamKind) == StreamName.Area.DATA) && (column < includedColumns.length && includedColumns[column])) { // if we aren't filtering or it is a dictionary, load it. if (includedRowGroups == null || RecordReaderUtils.isDictionary(streamKind, encodings.get(column))) { RecordReaderUtils.addEntireStreamToRanges(offset, length, list, doMergeBuffers); } else { RecordReaderUtils.addRgFilteredStreamToRanges(stream, includedRowGroups, isCompressed, indexes[column], encodings.get(column), types.get(column), compressionSize, hasNull[column], offset, length, list, doMergeBuffers); } } offset += length; } return list.extract(); } void createStreams(List<OrcProto.Stream> streamDescriptions, DiskRangeList ranges, boolean[] includeColumn, CompressionCodec codec, int bufferSize, Map<StreamName, InStream> streams) throws IOException { long streamOffset = 0; for (OrcProto.Stream streamDesc : streamDescriptions) { int column = streamDesc.getColumn(); if ((includeColumn != null && (column < includeColumn.length && !includeColumn[column])) || streamDesc.hasKind() && (StreamName.getArea(streamDesc.getKind()) != StreamName.Area.DATA)) { streamOffset += streamDesc.getLength(); continue; } List<DiskRange> buffers = RecordReaderUtils.getStreamBuffers( ranges, streamOffset, streamDesc.getLength()); StreamName name = new StreamName(column, streamDesc.getKind()); streams.put(name, InStream.create(name.toString(), buffers, streamDesc.getLength(), codec, bufferSize)); streamOffset += streamDesc.getLength(); } } private void readPartialDataStreams(StripeInformation stripe) throws IOException { List<OrcProto.Stream> streamList = stripeFooter.getStreamsList(); DiskRangeList toRead = planReadPartialDataStreams(streamList, indexes, fileIncluded, includedRowGroups, dataReader.getCompressionCodec() != null, stripeFooter.getColumnsList(), types, bufferSize, true); if (LOG.isDebugEnabled()) { LOG.debug("chunks = " + RecordReaderUtils.stringifyDiskRanges(toRead)); } bufferChunks = dataReader.readFileData(toRead, stripe.getOffset(), false); if (LOG.isDebugEnabled()) { LOG.debug("merge = " + RecordReaderUtils.stringifyDiskRanges(bufferChunks)); } createStreams(streamList, bufferChunks, fileIncluded, dataReader.getCompressionCodec(), bufferSize, streams); } /** * Read the next stripe until we find a row that we don't skip. * * @throws IOException */ private void advanceStripe() throws IOException { rowInStripe = rowCountInStripe; while (rowInStripe >= rowCountInStripe && currentStripe < stripes.size() - 1) { currentStripe += 1; readStripe(); } } /** * Skip over rows that we aren't selecting, so that the next row is * one that we will read. * * @param nextRow the row we want to go to * @throws IOException */ private boolean advanceToNextRow( TreeReaderFactory.TreeReader reader, long nextRow, boolean canAdvanceStripe) throws IOException { long nextRowInStripe = nextRow - rowBaseInStripe; // check for row skipping if (rowIndexStride != 0 && includedRowGroups != null && nextRowInStripe < rowCountInStripe) { int rowGroup = (int) (nextRowInStripe / rowIndexStride); if (!includedRowGroups[rowGroup]) { while (rowGroup < includedRowGroups.length && !includedRowGroups[rowGroup]) { rowGroup += 1; } if (rowGroup >= includedRowGroups.length) { if (canAdvanceStripe) { advanceStripe(); } return canAdvanceStripe; } nextRowInStripe = Math.min(rowCountInStripe, rowGroup * rowIndexStride); } } if (nextRowInStripe >= rowCountInStripe) { if (canAdvanceStripe) { advanceStripe(); } return canAdvanceStripe; } if (nextRowInStripe != rowInStripe) { if (rowIndexStride != 0) { int rowGroup = (int) (nextRowInStripe / rowIndexStride); seekToRowEntry(reader, rowGroup); reader.skipRows(nextRowInStripe - rowGroup * rowIndexStride); } else { reader.skipRows(nextRowInStripe - rowInStripe); } rowInStripe = nextRowInStripe; } return true; } @Override public boolean nextBatch(VectorizedRowBatch batch) throws IOException { try { if (rowInStripe >= rowCountInStripe) { currentStripe += 1; if (currentStripe >= stripes.size()) { batch.size = 0; return false; } readStripe(); } int batchSize = computeBatchSize(batch.getMaxSize()); rowInStripe += batchSize; reader.setVectorColumnCount(batch.getDataColumnCount()); reader.nextBatch(batch, batchSize); batch.selectedInUse = false; batch.size = batchSize; advanceToNextRow(reader, rowInStripe + rowBaseInStripe, true); return batch.size != 0; } catch (IOException e) { // Rethrow exception with file name in log message throw new IOException("Error reading file: " + path, e); } } private int computeBatchSize(long targetBatchSize) { final int batchSize; // In case of PPD, batch size should be aware of row group boundaries. If only a subset of row // groups are selected then marker position is set to the end of range (subset of row groups // within strip). Batch size computed out of marker position makes sure that batch size is // aware of row group boundary and will not cause overflow when reading rows // illustration of this case is here https://issues.apache.org/jira/browse/HIVE-6287 if (rowIndexStride != 0 && includedRowGroups != null && rowInStripe < rowCountInStripe) { int startRowGroup = (int) (rowInStripe / rowIndexStride); if (!includedRowGroups[startRowGroup]) { while (startRowGroup < includedRowGroups.length && !includedRowGroups[startRowGroup]) { startRowGroup += 1; } } int endRowGroup = startRowGroup; while (endRowGroup < includedRowGroups.length && includedRowGroups[endRowGroup]) { endRowGroup += 1; } final long markerPosition = (endRowGroup * rowIndexStride) < rowCountInStripe ? (endRowGroup * rowIndexStride) : rowCountInStripe; batchSize = (int) Math.min(targetBatchSize, (markerPosition - rowInStripe)); if (isLogDebugEnabled && batchSize < targetBatchSize) { LOG.debug("markerPosition: " + markerPosition + " batchSize: " + batchSize); } } else { batchSize = (int) Math.min(targetBatchSize, (rowCountInStripe - rowInStripe)); } return batchSize; } @Override public void close() throws IOException { clearStreams(); dataReader.close(); } @Override public long getRowNumber() { return rowInStripe + rowBaseInStripe + firstRow; } /** * Return the fraction of rows that have been read from the selected. * section of the file * * @return fraction between 0.0 and 1.0 of rows consumed */ @Override public float getProgress() { return ((float) rowBaseInStripe + rowInStripe) / totalRowCount; } private int findStripe(long rowNumber) { for (int i = 0; i < stripes.size(); i++) { StripeInformation stripe = stripes.get(i); if (stripe.getNumberOfRows() > rowNumber) { return i; } rowNumber -= stripe.getNumberOfRows(); } throw new IllegalArgumentException("Seek after the end of reader range"); } public OrcIndex readRowIndex(int stripeIndex, boolean[] included, boolean[] sargColumns) throws IOException { return readRowIndex(stripeIndex, included, null, null, sargColumns); } public OrcIndex readRowIndex(int stripeIndex, boolean[] included, OrcProto.RowIndex[] indexes, OrcProto.BloomFilterIndex[] bloomFilterIndex, boolean[] sargColumns) throws IOException { StripeInformation stripe = stripes.get(stripeIndex); OrcProto.StripeFooter stripeFooter = null; // if this is the current stripe, use the cached objects. if (stripeIndex == currentStripe) { stripeFooter = this.stripeFooter; indexes = indexes == null ? this.indexes : indexes; bloomFilterIndex = bloomFilterIndex == null ? this.bloomFilterIndices : bloomFilterIndex; sargColumns = sargColumns == null ? (sargApp == null ? null : sargApp.sargColumns) : sargColumns; } return dataReader.readRowIndex(stripe, evolution.getFileType(0), stripeFooter, ignoreNonUtf8BloomFilter, included, indexes, sargColumns, writerVersion, bloomFilterKind, bloomFilterIndex); } private void seekToRowEntry(TreeReaderFactory.TreeReader reader, int rowEntry) throws IOException { PositionProvider[] index = new PositionProvider[indexes.length]; for (int i = 0; i < indexes.length; ++i) { if (indexes[i] != null) { index[i] = new PositionProviderImpl(indexes[i].getEntry(rowEntry)); } } reader.seek(index); } @Override public void seekToRow(long rowNumber) throws IOException { if (rowNumber < 0) { throw new IllegalArgumentException("Seek to a negative row number " + rowNumber); } else if (rowNumber < firstRow) { throw new IllegalArgumentException("Seek before reader range " + rowNumber); } // convert to our internal form (rows from the beginning of slice) rowNumber -= firstRow; // move to the right stripe int rightStripe = findStripe(rowNumber); if (rightStripe != currentStripe) { currentStripe = rightStripe; readStripe(); } readRowIndex(currentStripe, fileIncluded, sargApp == null ? null : sargApp.sargColumns); // if we aren't to the right row yet, advance in the stripe. advanceToNextRow(reader, rowNumber, true); } private static final String TRANSLATED_SARG_SEPARATOR = "_"; public static String encodeTranslatedSargColumn(int rootColumn, Integer indexInSourceTable) { return rootColumn + TRANSLATED_SARG_SEPARATOR + ((indexInSourceTable == null) ? -1 : indexInSourceTable); } public static int[] mapTranslatedSargColumns( List<OrcProto.Type> types, List<PredicateLeaf> sargLeaves) { int[] result = new int[sargLeaves.size()]; OrcProto.Type lastRoot = null; // Root will be the same for everyone as of now. String lastRootStr = null; for (int i = 0; i < result.length; ++i) { String[] rootAndIndex = sargLeaves.get(i).getColumnName().split(TRANSLATED_SARG_SEPARATOR); assert rootAndIndex.length == 2; String rootStr = rootAndIndex[0], indexStr = rootAndIndex[1]; int index = Integer.parseInt(indexStr); // First, check if the column even maps to anything. if (index == -1) { result[i] = -1; continue; } assert index >= 0; // Then, find the root type if needed. if (!rootStr.equals(lastRootStr)) { lastRoot = types.get(Integer.parseInt(rootStr)); lastRootStr = rootStr; } // Subtypes of the root types correspond, in order, to the columns in the table schema // (disregarding schema evolution that doesn't presently work). Get the index for the // corresponding subtype. result[i] = lastRoot.getSubtypes(index); } return result; } public CompressionCodec getCompressionCodec() { return dataReader.getCompressionCodec(); } }
{ "content_hash": "bcec2d6d269b0564f90a9fa6451e5af3", "timestamp": "", "source": "github", "line_count": 1343, "max_line_length": 113, "avg_line_length": 39.83618763961281, "alnum_prop": 0.6433457943925234, "repo_name": "pudidic/orc", "id": "0dacc70a4401e04682394d436964c05191eda17b", "size": "54306", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/core/src/java/org/apache/orc/impl/RecordReaderImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "639" }, { "name": "C", "bytes": "1690" }, { "name": "C++", "bytes": "1164764" }, { "name": "CMake", "bytes": "20716" }, { "name": "CSS", "bytes": "87995" }, { "name": "HTML", "bytes": "13686442" }, { "name": "Java", "bytes": "1895735" }, { "name": "JavaScript", "bytes": "3308" }, { "name": "Protocol Buffer", "bytes": "7180" }, { "name": "Ruby", "bytes": "60" }, { "name": "Shell", "bytes": "2295" } ], "symlink_target": "" }
// Package installcni implements the install CNI action package installcni import ( "bytes" "strings" "text/template" "sigs.k8s.io/kind/pkg/errors" "sigs.k8s.io/kind/pkg/internal/apis/config" "sigs.k8s.io/kind/pkg/cluster/internal/create/actions" "sigs.k8s.io/kind/pkg/cluster/nodeutils" "sigs.k8s.io/kind/pkg/internal/patch" ) type action struct{} // NewAction returns a new action for installing default CNI func NewAction() actions.Action { return &action{} } // Execute runs the action func (a *action) Execute(ctx *actions.ActionContext) error { ctx.Status.Start("Installing CNI 🔌") defer ctx.Status.End(false) allNodes, err := ctx.Nodes() if err != nil { return err } // get the target node for this task controlPlanes, err := nodeutils.ControlPlaneNodes(allNodes) if err != nil { return err } node := controlPlanes[0] // kind expects at least one always // read the manifest from the node var raw bytes.Buffer if err := node.Command("cat", "/kind/manifests/default-cni.yaml").SetStdout(&raw).Run(); err != nil { return errors.Wrap(err, "failed to read CNI manifest") } manifest := raw.String() // TODO: remove this check? // backwards compatibility for mounting your own manifest file to the default // location // NOTE: this is intentionally undocumented, as an internal implementation // detail. Going forward users should disable the default CNI and install // their own, or use the default. The internal templating mechanism is // not intended for external usage and is unstable. if strings.Contains(manifest, "would you kindly template this file") { t, err := template.New("cni-manifest").Parse(manifest) if err != nil { return errors.Wrap(err, "failed to parse CNI manifest template") } var out bytes.Buffer err = t.Execute(&out, &struct { PodSubnet string }{ PodSubnet: ctx.Config.Networking.PodSubnet, }) if err != nil { return errors.Wrap(err, "failed to execute CNI manifest template") } manifest = out.String() } // NOTE: this is intentionally undocumented, as an internal implementation // detail. Going forward users should disable the default CNI and install // their own, or use the default. The internal templating mechanism is // not intended for external usage and is unstable. if strings.Contains(manifest, "would you kindly patch this file") { // Add the controlplane endpoint so kindnet doesn´t have to wait for kube-proxy controlPlaneEndpoint, err := ctx.Provider.GetAPIServerInternalEndpoint(ctx.Config.Name) if err != nil { return err } patchValue := ` - op: add path: /spec/template/spec/containers/0/env/- value: name: CONTROL_PLANE_ENDPOINT value: ` + controlPlaneEndpoint controlPlanePatch6902 := config.PatchJSON6902{ Group: "apps", Version: "v1", Kind: "DaemonSet", Patch: patchValue, } patchedConfig, err := patch.KubeYAML(manifest, nil, []config.PatchJSON6902{controlPlanePatch6902}) if err != nil { return err } manifest = patchedConfig } ctx.Logger.V(5).Infof("Using the following Kindnetd config:\n%s", manifest) // install the manifest if err := node.Command( "kubectl", "create", "--kubeconfig=/etc/kubernetes/admin.conf", "-f", "-", ).SetStdin(strings.NewReader(manifest)).Run(); err != nil { return errors.Wrap(err, "failed to apply overlay network") } // mark success ctx.Status.End(true) return nil }
{ "content_hash": "079e9422d583172ca55e597764265bb1", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 102, "avg_line_length": 28.722689075630253, "alnum_prop": 0.711234640140433, "repo_name": "operator-framework/operator-lifecycle-manager", "id": "eeee6a287877fd6a6e4470c07a34036e27770c26", "size": "3991", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/sigs.k8s.io/kind/pkg/cluster/internal/create/actions/installcni/cni.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2078" }, { "name": "Go", "bytes": "3367162" }, { "name": "Makefile", "bytes": "10404" }, { "name": "Mustache", "bytes": "515" }, { "name": "Shell", "bytes": "19415" }, { "name": "Starlark", "bytes": "11071" } ], "symlink_target": "" }
<?php namespace Cac\MailingBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('cac_mailing'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
{ "content_hash": "b34db9264a610c8b2550dc961d560459", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 131, "avg_line_length": 30.24137931034483, "alnum_prop": 0.7160775370581528, "repo_name": "t-n-y/cac", "id": "b9df8072da53e8e869f97a17007cae2535a59a01", "size": "877", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Cac/MailingBundle/DependencyInjection/Configuration.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3208" }, { "name": "CSS", "bytes": "157377" }, { "name": "HTML", "bytes": "299616" }, { "name": "JavaScript", "bytes": "202590" }, { "name": "PHP", "bytes": "387508" }, { "name": "Ruby", "bytes": "161" } ], "symlink_target": "" }
import { Injectable } from '@angular/core'; export class Email { to: string; subject: string; body: string; } @Injectable() export class EmailService { public sendEmail(email: Email) { let plugins: any = (<any>window).cordova.plugins; plugins.email.isAvailable(() => { plugins.email.open(email); }); } }
{ "content_hash": "07dc018342767ac873796b96326cce50", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 51, "avg_line_length": 18.764705882352942, "alnum_prop": 0.677115987460815, "repo_name": "skounis/supermodular2", "id": "8692a77b577d8c9be358dc32cfc58687844783f1", "size": "319", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/services/email.service.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4249" }, { "name": "HTML", "bytes": "26158" }, { "name": "JavaScript", "bytes": "6369" }, { "name": "TypeScript", "bytes": "26184" } ], "symlink_target": "" }
import Ember from 'ember'; export default Ember.Controller.extend({ queryParams: ['environmentId','upgrade'], environmentId: null, upgrade: null, actions: { cancel() { this.send('goToPrevious','applications-tab.catalog'); } }, });
{ "content_hash": "4b433729af63a69c0d526ef53d57b206", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 59, "avg_line_length": 19.76923076923077, "alnum_prop": 0.6536964980544747, "repo_name": "ubiquityhosting/rancher_ui", "id": "c5faa6db693de5b3772fa4378bb558923d34a56f", "size": "257", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/applications-tab/catalog/launch/controller.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "59132" }, { "name": "HTML", "bytes": "285965" }, { "name": "JavaScript", "bytes": "588371" }, { "name": "Shell", "bytes": "8463" } ], "symlink_target": "" }
describe('Controller: MenuController', function () { // load the controller's module beforeEach(module('FinEurekaApp')); var MenuController, scope, $httpBackend; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, _$httpBackend_, $rootScope, menuFactory) { // place here mocked dependencies $httpBackend = _$httpBackend_; $httpBackend.expectGET("http://localhost:3000/productos").respond([ { "id": 0, "name": "Uthapizza", "image": "images/uthapizza.png", "category": "mains", "label": "Hot", "price": "4.99", "description": "A", "comments":[{}] }, { "id": 1, "name": "Uthapizza", "image": "images/uthapizza.png", "category": "mains", "label": "Hot", "price": "4.99", "description": "A", "comments":[{}] } ]); scope = $rootScope.$new(); MenuController = $controller('MenuController', { $scope: scope, menuFactory: menuFactory }); })); it('should have showDetails as false', function () { expect(scope.showDetails).toBe(false); }); it('should create "productos" with 2 productos fetched from xhr', function() { // expect(scope.productos.length).toBe(0); $httpBackend.flush(); expect(scope.productos.length).toBe(2); expect(scope.productos[0].name).toBe("Uthapizza"); expect(scope.productos[1].label).toBe("Hot"); }); });
{ "content_hash": "8bdebdd449d559bc3746ee840ecff87c", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 86, "avg_line_length": 26.607142857142858, "alnum_prop": 0.5825503355704698, "repo_name": "chechuco/FinEureka", "id": "da8dedba75db86ae8a7ba0db2a6ecf43d15c525d", "size": "1490", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/test/spec/controllers/menucontroller.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2963" }, { "name": "HTML", "bytes": "39735" }, { "name": "JavaScript", "bytes": "361854" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.io.parquet.vector; import org.apache.hadoop.hive.ql.exec.vector.ListColumnVector; import org.apache.hadoop.hive.ql.exec.vector.DecimalColumnVector; import org.apache.hadoop.hive.ql.exec.vector.BytesColumnVector; import org.apache.hadoop.hive.ql.exec.vector.LongColumnVector; import org.apache.hadoop.hive.ql.exec.vector.DoubleColumnVector; import org.apache.hadoop.hive.ql.exec.vector.ColumnVector; import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch; import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector; import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo; import org.apache.parquet.column.ColumnDescriptor; import org.apache.parquet.column.page.PageReader; import org.apache.parquet.schema.LogicalTypeAnnotation.DecimalLogicalTypeAnnotation; import org.apache.parquet.schema.Type; import java.io.IOException; import java.time.ZoneId; import java.util.ArrayList; import java.util.List; /** * It's column level Parquet reader which is used to read a batch of records for a list column. * TODO Currently List type only support non nested case. */ public class VectorizedListColumnReader extends BaseVectorizedColumnReader { // The value read in last time private Object lastValue; // flag to indicate if there is no data in parquet data page private boolean eof = false; // flag to indicate if it's the first time to read parquet data page with this instance boolean isFirstRow = true; public VectorizedListColumnReader(ColumnDescriptor descriptor, PageReader pageReader, boolean skipTimestampConversion, ZoneId writerTimezone, boolean skipProlepticConversion, boolean legacyConversionEnabled, Type type, TypeInfo hiveType) throws IOException { super(descriptor, pageReader, skipTimestampConversion, writerTimezone, skipProlepticConversion, legacyConversionEnabled, type, hiveType); } @Override public void readBatch(int total, ColumnVector column, TypeInfo columnType) throws IOException { ListColumnVector lcv = (ListColumnVector) column; // before readBatch, initial the size of offsets & lengths as the default value, // the actual size will be assigned in setChildrenInfo() after reading complete. lcv.offsets = new long[VectorizedRowBatch.DEFAULT_SIZE]; lcv.lengths = new long[VectorizedRowBatch.DEFAULT_SIZE]; // Because the length of ListColumnVector.child can't be known now, // the valueList will save all data for ListColumnVector temporary. List<Object> valueList = new ArrayList<>(); PrimitiveObjectInspector.PrimitiveCategory category = ((PrimitiveTypeInfo) ((ListTypeInfo) columnType).getListElementTypeInfo()).getPrimitiveCategory(); // read the first row in parquet data page, this will be only happened once for this instance if(isFirstRow){ if (!fetchNextValue(category)) { return; } isFirstRow = false; } int index = 0; while (!eof && index < total) { // add element to ListColumnVector one by one addElement(lcv, valueList, category, index); index++; } // Decode the value if necessary if (isCurrentPageDictionaryEncoded) { valueList = decodeDictionaryIds(category, valueList); } // Convert valueList to array for the ListColumnVector.child convertValueListToListColumnVector(category, lcv, valueList, index); } private int readPageIfNeed() throws IOException { // Compute the number of values we want to read in this page. int leftInPage = (int) (endOfPageValueCount - valuesRead); if (leftInPage == 0) { // no data left in current page, load data from new page readPage(); leftInPage = (int) (endOfPageValueCount - valuesRead); } return leftInPage; } private boolean fetchNextValue(PrimitiveObjectInspector.PrimitiveCategory category) throws IOException { int left = readPageIfNeed(); if (left > 0) { // get the values of repetition and definitionLevel readRepetitionAndDefinitionLevels(); // read the data if it isn't null if (definitionLevel == maxDefLevel) { if (isCurrentPageDictionaryEncoded) { lastValue = dataColumn.readValueDictionaryId(); } else { lastValue = readPrimitiveTypedRow(category); } } return true; } else { eof = true; return false; } } /** * The function will set all data from parquet data page for an element in ListColumnVector */ private void addElement(ListColumnVector lcv, List<Object> elements, PrimitiveObjectInspector.PrimitiveCategory category, int index) throws IOException { lcv.offsets[index] = elements.size(); // Return directly if last value is null if (definitionLevel < maxDefLevel) { lcv.isNull[index] = true; lcv.lengths[index] = 0; // fetch the data from parquet data page for next call fetchNextValue(category); return; } do { // add all data for an element in ListColumnVector, get out the loop if there is no data or the data is for new element elements.add(lastValue); } while (fetchNextValue(category) && (repetitionLevel != 0)); lcv.isNull[index] = false; lcv.lengths[index] = elements.size() - lcv.offsets[index]; } // Need to be in consistent with that VectorizedPrimitiveColumnReader#readBatchHelper // TODO Reduce the duplicated code private Object readPrimitiveTypedRow(PrimitiveObjectInspector.PrimitiveCategory category) { switch (category) { case INT: case BYTE: case SHORT: return dataColumn.readInteger(); case DATE: case INTERVAL_YEAR_MONTH: case LONG: return dataColumn.readLong(); case BOOLEAN: return dataColumn.readBoolean() ? 1 : 0; case DOUBLE: return dataColumn.readDouble(); case BINARY: return dataColumn.readBytes(); case STRING: case CHAR: case VARCHAR: return dataColumn.readString(); case FLOAT: return dataColumn.readFloat(); case DECIMAL: return dataColumn.readDecimal(); case TIMESTAMP: return dataColumn.readTimestamp(); case INTERVAL_DAY_TIME: default: throw new RuntimeException("Unsupported type in the list: " + type); } } private List decodeDictionaryIds(PrimitiveObjectInspector.PrimitiveCategory category, List valueList) { int total = valueList.size(); List resultList; List<Integer> intList = (List<Integer>) valueList; switch (category) { case INT: case BYTE: case SHORT: resultList = new ArrayList<Integer>(total); for (int i = 0; i < total; ++i) { resultList.add(dictionary.readInteger(intList.get(i))); } break; case DATE: case INTERVAL_YEAR_MONTH: case LONG: resultList = new ArrayList<Long>(total); for (int i = 0; i < total; ++i) { resultList.add(dictionary.readLong(intList.get(i))); } break; case BOOLEAN: resultList = new ArrayList<Long>(total); for (int i = 0; i < total; ++i) { resultList.add(dictionary.readBoolean(intList.get(i)) ? 1 : 0); } break; case DOUBLE: resultList = new ArrayList<Long>(total); for (int i = 0; i < total; ++i) { resultList.add(dictionary.readDouble(intList.get(i))); } break; case BINARY: resultList = new ArrayList<Long>(total); for (int i = 0; i < total; ++i) { resultList.add(dictionary.readBytes(intList.get(i))); } break; case STRING: case CHAR: case VARCHAR: resultList = new ArrayList<Long>(total); for (int i = 0; i < total; ++i) { resultList.add(dictionary.readString(intList.get(i))); } break; case FLOAT: resultList = new ArrayList<Float>(total); for (int i = 0; i < total; ++i) { resultList.add(dictionary.readFloat(intList.get(i))); } break; case DECIMAL: resultList = new ArrayList<Long>(total); for (int i = 0; i < total; ++i) { resultList.add(dictionary.readDecimal(intList.get(i))); } break; case TIMESTAMP: resultList = new ArrayList<Long>(total); for (int i = 0; i < total; ++i) { resultList.add(dictionary.readTimestamp(intList.get(i))); } break; case INTERVAL_DAY_TIME: default: throw new RuntimeException("Unsupported type in the list: " + type); } return resultList; } /** * The lengths & offsets will be initialized as default size (1024), * it should be set to the actual size according to the element number. */ private void setChildrenInfo(ListColumnVector lcv, int itemNum, int elementNum) { lcv.childCount = itemNum; long[] lcvLength = new long[elementNum]; long[] lcvOffset = new long[elementNum]; System.arraycopy(lcv.lengths, 0, lcvLength, 0, elementNum); System.arraycopy(lcv.offsets, 0, lcvOffset, 0, elementNum); lcv.lengths = lcvLength; lcv.offsets = lcvOffset; } private void fillColumnVector(PrimitiveObjectInspector.PrimitiveCategory category, ListColumnVector lcv, List valueList, int elementNum) { int total = valueList.size(); setChildrenInfo(lcv, total, elementNum); switch (category) { case BOOLEAN: lcv.child = new LongColumnVector(total); for (int i = 0; i < valueList.size(); i++) { ((LongColumnVector) lcv.child).vector[i] = ((List<Integer>) valueList).get(i); } break; case INT: case BYTE: case SHORT: case DATE: case INTERVAL_YEAR_MONTH: case LONG: lcv.child = new LongColumnVector(total); for (int i = 0; i < valueList.size(); i++) { ((LongColumnVector) lcv.child).vector[i] = ((List<Long>) valueList).get(i); } break; case DOUBLE: lcv.child = new DoubleColumnVector(total); for (int i = 0; i < valueList.size(); i++) { ((DoubleColumnVector) lcv.child).vector[i] = ((List<Double>) valueList).get(i); } break; case BINARY: case STRING: case CHAR: case VARCHAR: lcv.child = new BytesColumnVector(total); lcv.child.init(); for (int i = 0; i < valueList.size(); i++) { byte[] src = ((List<byte[]>) valueList).get(i); ((BytesColumnVector) lcv.child).setRef(i, src, 0, src.length); } break; case FLOAT: lcv.child = new DoubleColumnVector(total); for (int i = 0; i < valueList.size(); i++) { ((DoubleColumnVector) lcv.child).vector[i] = ((List<Float>) valueList).get(i); } break; case DECIMAL: decimalTypeCheck(type); DecimalLogicalTypeAnnotation logicalType = (DecimalLogicalTypeAnnotation) type.getLogicalTypeAnnotation(); int precision = logicalType.getPrecision(); int scale = logicalType.getScale(); lcv.child = new DecimalColumnVector(total, precision, scale); for (int i = 0; i < valueList.size(); i++) { ((DecimalColumnVector) lcv.child).vector[i].set(((List<byte[]>) valueList).get(i), scale); } break; case INTERVAL_DAY_TIME: case TIMESTAMP: default: throw new RuntimeException("Unsupported type in the list: " + type); } } /** * Finish the result ListColumnVector with all collected information. */ private void convertValueListToListColumnVector( PrimitiveObjectInspector.PrimitiveCategory category, ListColumnVector lcv, List valueList, int elementNum) { // Fill the child of ListColumnVector with valueList fillColumnVector(category, lcv, valueList, elementNum); setIsRepeating(lcv); } private void setIsRepeating(ListColumnVector lcv) { ColumnVector child0 = getChildData(lcv, 0); for (int i = 1; i < lcv.offsets.length; i++) { ColumnVector currentChild = getChildData(lcv, i); if (!compareColumnVector(child0, currentChild)) { lcv.isRepeating = false; return; } } lcv.isRepeating = true; } /** * Get the child ColumnVector of ListColumnVector */ private ColumnVector getChildData(ListColumnVector lcv, int index) { if (lcv.offsets[index] > Integer.MAX_VALUE || lcv.lengths[index] > Integer.MAX_VALUE) { throw new RuntimeException("The element number in list is out of scope."); } if (lcv.isNull[index]) { return null; } int start = (int)lcv.offsets[index]; int length = (int)lcv.lengths[index]; ColumnVector child = lcv.child; ColumnVector resultCV = null; if (child instanceof LongColumnVector) { resultCV = new LongColumnVector(length); try { System.arraycopy(((LongColumnVector) lcv.child).vector, start, ((LongColumnVector) resultCV).vector, 0, length); } catch (Exception e) { throw new RuntimeException( "Fail to copy at index:" + index + ", start:" + start + ",length:" + length + ",vec " + "len:" + ((LongColumnVector) lcv.child).vector.length + ", offset len:" + lcv .offsets.length + ", len len:" + lcv.lengths.length, e); } } if (child instanceof DoubleColumnVector) { resultCV = new DoubleColumnVector(length); System.arraycopy(((DoubleColumnVector) lcv.child).vector, start, ((DoubleColumnVector) resultCV).vector, 0, length); } if (child instanceof BytesColumnVector) { resultCV = new BytesColumnVector(length); System.arraycopy(((BytesColumnVector) lcv.child).vector, start, ((BytesColumnVector) resultCV).vector, 0, length); } if (child instanceof DecimalColumnVector) { resultCV = new DecimalColumnVector(length, ((DecimalColumnVector) child).precision, ((DecimalColumnVector) child).scale); System.arraycopy(((DecimalColumnVector) lcv.child).vector, start, ((DecimalColumnVector) resultCV).vector, 0, length); } return resultCV; } private boolean compareColumnVector(ColumnVector cv1, ColumnVector cv2) { if (cv1 == null && cv2 == null) { return true; } else { if (cv1 != null && cv2 != null) { if (cv1 instanceof LongColumnVector && cv2 instanceof LongColumnVector) { return compareLongColumnVector((LongColumnVector) cv1, (LongColumnVector) cv2); } if (cv1 instanceof DoubleColumnVector && cv2 instanceof DoubleColumnVector) { return compareDoubleColumnVector((DoubleColumnVector) cv1, (DoubleColumnVector) cv2); } if (cv1 instanceof BytesColumnVector && cv2 instanceof BytesColumnVector) { return compareBytesColumnVector((BytesColumnVector) cv1, (BytesColumnVector) cv2); } if (cv1 instanceof DecimalColumnVector && cv2 instanceof DecimalColumnVector) { return compareDecimalColumnVector((DecimalColumnVector) cv1, (DecimalColumnVector) cv2); } throw new RuntimeException( "Unsupported ColumnVector comparision between " + cv1.getClass().getName() + " and " + cv2.getClass().getName()); } else { return false; } } } private boolean compareLongColumnVector(LongColumnVector cv1, LongColumnVector cv2) { int length1 = cv1.vector.length; int length2 = cv2.vector.length; if (length1 == length2) { for (int i = 0; i < length1; i++) { if (cv1.vector[i] != cv2.vector[i]) { return false; } } } else { return false; } return true; } private boolean compareDoubleColumnVector(DoubleColumnVector cv1, DoubleColumnVector cv2) { int length1 = cv1.vector.length; int length2 = cv2.vector.length; if (length1 == length2) { for (int i = 0; i < length1; i++) { if (cv1.vector[i] != cv2.vector[i]) { return false; } } } else { return false; } return true; } private boolean compareDecimalColumnVector(DecimalColumnVector cv1, DecimalColumnVector cv2) { int length1 = cv1.vector.length; int length2 = cv2.vector.length; if (length1 == length2 && cv1.scale == cv2.scale && cv1.precision == cv2.precision) { for (int i = 0; i < length1; i++) { if (cv1.vector[i] != null && cv2.vector[i] == null || cv1.vector[i] == null && cv2.vector[i] != null || cv1.vector[i] != null && cv2.vector[i] != null && !cv1.vector[i].equals(cv2.vector[i])) { return false; } } } else { return false; } return true; } private boolean compareBytesColumnVector(BytesColumnVector cv1, BytesColumnVector cv2) { int length1 = cv1.vector.length; int length2 = cv2.vector.length; if (length1 == length2) { for (int i = 0; i < length1; i++) { int innerLen1 = cv1.vector[i].length; int innerLen2 = cv2.vector[i].length; if (innerLen1 == innerLen2) { for (int j = 0; j < innerLen1; j++) { if (cv1.vector[i][j] != cv2.vector[i][j]) { return false; } } } else { return false; } } } else { return false; } return true; } }
{ "content_hash": "78bb4973e23cbb2600ca8ca00ce7b68f", "timestamp": "", "source": "github", "line_count": 499, "max_line_length": 155, "avg_line_length": 35.91583166332666, "alnum_prop": 0.6549492244169177, "repo_name": "lirui-apache/hive", "id": "93d9509edd58052e56a69f60d531c1c9334bdaea", "size": "17922", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ql/src/java/org/apache/hadoop/hive/ql/io/parquet/vector/VectorizedListColumnReader.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "54376" }, { "name": "Batchfile", "bytes": "845" }, { "name": "C", "bytes": "28218" }, { "name": "C++", "bytes": "45308" }, { "name": "CSS", "bytes": "5157" }, { "name": "GAP", "bytes": "179818" }, { "name": "HTML", "bytes": "58711" }, { "name": "HiveQL", "bytes": "7568849" }, { "name": "Java", "bytes": "52828789" }, { "name": "JavaScript", "bytes": "43855" }, { "name": "M4", "bytes": "2276" }, { "name": "PHP", "bytes": "148097" }, { "name": "PLSQL", "bytes": "5261" }, { "name": "PLpgSQL", "bytes": "302587" }, { "name": "Perl", "bytes": "319842" }, { "name": "PigLatin", "bytes": "12333" }, { "name": "Python", "bytes": "408633" }, { "name": "Roff", "bytes": "5379" }, { "name": "SQLPL", "bytes": "409" }, { "name": "Shell", "bytes": "299497" }, { "name": "TSQL", "bytes": "2556735" }, { "name": "Thrift", "bytes": "144783" }, { "name": "XSLT", "bytes": "20199" }, { "name": "q", "bytes": "320552" } ], "symlink_target": "" }
class Golden::Menu::HierarchicalMenusController < ApplicationController include ::TheSortableTreeController::Rebuild before_filter :authenticate_session! before_filter :new_menu, only: [:create] load_and_authorize_resource :menu, class: 'Golden::Menu::HierarchicalMenu', parent: false #, find_by: :url def index @menu = @menus.nested_set.select('id, url, name, description, parent_id') respond_with @menus end def show respond_with @menu end def new respond_with @menu end def edit end def create @menu.save respond_with @menu end def update @menu.update_attributes menu_params respond_with @menu end def destroy @menu.destroy respond_with @menu end def list @menu = @menus.nested_set @menus = @menus.paginate page: params[:page] end protected def menu_params if params.respond_to? :permit params.require(:menu).permit(Golden::Menu.permitted_fields) else params[:menu] end end def new_menu @menu = Golden::Menu::HierarchicalMenu.new menu_params end def the_define_common_variables ['@menu', 'menus', Golden::Menu::HierarchicalMenu] end end
{ "content_hash": "df2be72a40c64f8666810563997859da", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 108, "avg_line_length": 19.459016393442624, "alnum_prop": 0.6798652064026959, "repo_name": "goldenio/golden-menu", "id": "665df362717bfedb1b15068e8d2b2d44110d194b", "size": "1187", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/golden/menu/hierarchical_menus_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "11266" } ], "symlink_target": "" }
package command import ( "fmt" "strconv" "github.com/coreos/etcd/Godeps/_workspace/src/github.com/spf13/cobra" "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context" "github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc" pb "github.com/coreos/etcd/etcdserver/etcdserverpb" ) // NewCompactionCommand returns the cobra command for "compaction". func NewCompactionCommand() *cobra.Command { return &cobra.Command{ Use: "compaction", Short: "Compaction compacts the event history in etcd.", Run: compactionCommandFunc, } } // compactionCommandFunc executes the "compaction" command. func compactionCommandFunc(cmd *cobra.Command, args []string) { if len(args) != 1 { ExitWithError(ExitBadArgs, fmt.Errorf("compaction command needs 1 argument.")) } rev, err := strconv.ParseInt(args[0], 10, 64) if err != nil { ExitWithError(ExitError, err) } endpoint, err := cmd.Flags().GetString("endpoint") if err != nil { ExitWithError(ExitError, err) } conn, err := grpc.Dial(endpoint) if err != nil { ExitWithError(ExitBadConnection, err) } kv := pb.NewKVClient(conn) req := &pb.CompactionRequest{Revision: rev} kv.Compact(context.Background(), req) }
{ "content_hash": "a7a39f8fb6843f453e5f02a709415d9b", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 80, "avg_line_length": 27.022222222222222, "alnum_prop": 0.725328947368421, "repo_name": "cchamplin/etcd", "id": "9844b4227336ea30bddca3c3c165547efa37dbe9", "size": "1806", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "etcdctlv3/command/compaction_command.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "941" }, { "name": "Go", "bytes": "1732997" }, { "name": "Makefile", "bytes": "1019" }, { "name": "Protocol Buffer", "bytes": "15758" }, { "name": "Scheme", "bytes": "9281" }, { "name": "Shell", "bytes": "16163" } ], "symlink_target": "" }
require 'psych' require 'set' module Overcover class RspecCollector class << self def paths @paths ||= [] end def should_analyse?(path) paths.empty? || paths.any? {|p| path.start_with?(p) } end def add_filter(filter) paths << filter end def reset puts "[overcover] deleting log files in #{dir}" log_files.each do |f| File.delete(f) end end def record(result) open(@log_file, 'a') do |f| f.puts Psych.dump(result) end end def dir ENV["OVERCOVER_DIR"] || "." end def log_files files = Dir.glob(File.join(dir, "overcover.*.tmp")) if block_given? files.each do |f| yield f end end files end def log_file @log_file end def start @log_file = File.join(dir ,"overcover.#{Time.now.utc.strftime("%Y%m%d%H%M%S%N")}.tmp") yield self if block_given? puts "[overcover] writing to log file #{@log_file}" if CoverageCollector.supported? collector = CoverageCollector.new(self) else puts "[overcover] WARNING: Using the slow TraceCollector since this version of ruby" puts "[overcover] does not support Coverage.peek_result. Use MRI 2.3+ for faster results." collector = TraceCollector.new(self) end root_path = Dir.pwd.to_s RSpec.configure do |config| # overcover config.before(:example) do |example| # puts "BEFORE #{example} #{example.location}" # puts "puts pid=#{Process.pid}" file = example.file_path.sub(root_path, ".") collector.before(file) end config.after(:example) do |example| # puts "AFTER #{example} #{example.location}" # puts "puts pid=#{Process.pid}" file = example.file_path.sub(root_path, ".") collector.after(file) end config.after(:suite) do |suite| Overcover::Reporter.summarize end end end end end end
{ "content_hash": "681844d24e8faf68bf9f26456afdf50a", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 100, "avg_line_length": 22.53061224489796, "alnum_prop": 0.5280797101449275, "repo_name": "skizz/overcover", "id": "70f3975d1daf861960d67433e3e5037f47fd50e9", "size": "2208", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/overcover/rspec_collector.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "15583" }, { "name": "Shell", "bytes": "131" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "6f7c79aa21145b1e32f75896abc95ac9", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "4ebbaed24d3deeed7c086007637c58154b6a41fd", "size": "199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Schizachyrium/Schizachyrium mexicanum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.dataartisans.flink_demo.sinks import java.util import org.apache.flink.configuration.Configuration import org.apache.flink.streaming.api.functions.sink.RichSinkFunction import org.elasticsearch.action.index.IndexRequest import org.elasticsearch.action.update.UpdateRequest import org.elasticsearch.client.transport.TransportClient import org.elasticsearch.common.settings.ImmutableSettings import org.elasticsearch.common.transport.InetSocketTransportAddress import scala.collection.JavaConversions._ /** * SinkFunction to either insert or update an entry in an Elasticsearch index. * * @param host Hostname of the Elasticsearch instance. * @param port Port of the Elasticsearch instance. * @param cluster Name of the Elasticsearch cluster. * @param index Name of the Elasticsearch index. * @param mapping Name of the index mapping. * * @tparam T Record type to write to Elasticsearch. */ abstract class ElasticsearchUpsertSink[T](host: String, port: Int, cluster: String, index: String, mapping: String) extends RichSinkFunction[T] { private var client: TransportClient = null def insertJson(record: T): Map[String, AnyRef] def updateJson(record: T): Map[String, AnyRef] def indexKey(record: T): String @throws[Exception] override def open(parameters: Configuration) { val config = new util.HashMap[String, String] config.put("bulk.flush.max.actions", "1") config.put("cluster.name", cluster) val settings = ImmutableSettings.settingsBuilder() .put(config) .build() client = new TransportClient(settings) .addTransportAddress(new InetSocketTransportAddress(host, port)) } @throws[Exception] override def invoke(r: T) { // do an upsert request to elastic search // index document if it does not exist val indexRequest = new IndexRequest(index, mapping, indexKey(r)) .source(mapAsJavaMap(insertJson(r))) // update document if it exists val updateRequest = new UpdateRequest(index, mapping, indexKey(r)) .doc(mapAsJavaMap(updateJson(r))) .upsert(indexRequest) client.update(updateRequest).get() } }
{ "content_hash": "f2e7618f9bb8a16d61b84e75b61594e0", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 115, "avg_line_length": 31, "alnum_prop": 0.7503506311360448, "repo_name": "dataArtisans/flink-streaming-demo", "id": "106c6a4c233a2aebc327749cf22c13f60ac4c08a", "size": "2737", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/scala/com/dataartisans/flink_demo/sinks/ElasticsearchUpsertSink.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "35288" }, { "name": "Shell", "bytes": "1685" } ], "symlink_target": "" }
var MemoryCards = (function(){ var alphabet = ' abcdefghijklmnopqrstuvwxyz'; function MemoryCardset(numPairs) { //card set ctor if (numPairs < 1) numPairs = 1; if (!numPairs || (numPairs > 26)) numPairs = 26; this.values = []; while (numPairs) { this.values.push(alphabet[numPairs]); this.values.push(alphabet[numPairs].toUpperCase()); --numPairs; } this.match = function(a,b) { return a.toUpperCase() == b.toUpperCase(); } // this.display could remain undefined if MemoryGame allows it to be optional, // but in case it's required, provide this identity function: this.display = function(val) { return val; } } return MemoryCardset; })();
{ "content_hash": "0117f81d6e70ef6016b8527b04690459", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 78, "avg_line_length": 29.09090909090909, "alnum_prop": 0.71875, "repo_name": "portlandcodeschool/jse-planning", "id": "1fc9e698d67ae91fae121bbab06ac309a5f52f4d", "size": "640", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "homework/week8/templates-old/old-cards.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2377" }, { "name": "HTML", "bytes": "7379" }, { "name": "JavaScript", "bytes": "305145" } ], "symlink_target": "" }
<?php namespace Symfony\Components\BrowserKit; /** * CookieJar. * * @package Symfony * @subpackage Components_BrowserKit * @author Fabien Potencier <fabien.potencier@symfony-project.com> */ class CookieJar { protected $cookieJar = array(); /** * Sets a cookie. * * @param Symfony\Components\BrowserKit\Cookie $cookie A Cookie instance */ public function set(Cookie $cookie) { $this->cookieJar[$cookie->getName()] = $cookie; } /** * Gets a cookie by name. * * @param string $name The cookie name * * @return Symfony\Components\BrowserKit\Cookie|null A Cookie instance or null if the cookie does not exist */ public function get($name) { $this->flushExpiredCookies(); return isset($this->cookieJar[$name]) ? $this->cookieJar[$name] : null; } /** * Removes a cookie by name. * * @param string $name The cookie name */ public function expire($name) { unset($this->cookieJar[$name]); } /** * Removes all the cookies from the jar. */ public function clear() { $this->cookieJar = array(); } /** * Updates the cookie jar from a Response object. * * @param Symfony\Components\BrowserKit\Response $response A Response object * @param string $url The base URL */ public function updateFromResponse(Response $response, $uri = null) { foreach ($response->getHeader('Set-Cookie', false) as $cookie) { $this->set(Cookie::fromString($cookie), $uri); } } /** * Returns not yet expired cookies. * * @return array An array of cookies */ public function all() { $this->flushExpiredCookies(); return $this->cookieJar; } /** * Returns not yet expired cookie values for the given URI. * * @param string $uri A URI * * @return array An array of cookie values */ public function getValues($uri) { $this->flushExpiredCookies(); $parts = parse_url($uri); $cookies = array(); foreach ($this->cookieJar as $cookie) { if ($cookie->getDomain() && $cookie->getDomain() != substr($parts['host'], -strlen($cookie->getDomain()))) { continue; } if ($cookie->getPath() != substr($parts['path'], 0, strlen($cookie->getPath()))) { continue; } if ($cookie->isSecure() && 'https' != $parts['scheme']) { continue; } $cookies[$cookie->getName()] = $cookie->getValue(); } return $cookies; } /** * Removes all expired cookies. */ public function flushExpiredCookies() { $cookies = $this->cookieJar; foreach ($cookies as $name => $cookie) { if ($cookie->isExpired()) { unset($this->cookieJar[$name]); } } } }
{ "content_hash": "38685f4883ba08cc5db6ceaab72197e0", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 120, "avg_line_length": 23.50769230769231, "alnum_prop": 0.5346858638743456, "repo_name": "dynamicguy/gpweb", "id": "0906e734d8ec5e59bd1dff91556e995fb2ee47c6", "size": "3303", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/vendor/symfony/src/Symfony/Components/BrowserKit/CookieJar.php", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!DOCTYPE HTML> <html lang="en"> <head> <title>Code for Sri Lanka</title> <link rel="shortcut icon" type="image/jpg" href="favicon.ico"/> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> <link rel="stylesheet" href="assets/css/main.css" /> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-139382284-1"></script> </head> <body class="is-preload"> <header id="header"> <h1>Code for Sri Lanka </h1> <p>Our Coding For Us!<br /> We are a civic group, bridging technology and government <br /> with the ambition of making a better Sri Lanka.</p> </header> <footer id="footer"> <p><a href="https://github.com/codeforsrilanka" target="_blank">Contribute on Github</a></p> <ul class="icons"> <li><a href="https://www.facebook.com/codeforsl/" target="_blank" class="icon brands fa-facebook"><span class="label">Twitter</span></a></li> <li><a href="https://twitter.com/codeforsrilanka" target="_blank" class="icon brands fa-twitter"><span class="label">Twitter</span></a></li> <li><a href="https://www.linkedin.com/company/codeforsrilanka" target="_blank" class="icon brands fa-linkedin"><span class="label">LinkedIn</span></a></li> <li><a href="https://www.youtube.com/channel/UC3uipVoKQdFW7gYLloI1pcQ" target="_blank" class="icon brands fa-youtube"><span class="label">Youtube</span></a></li> <li><a href="mailto:codeforsrilanka@gmail.com" class="icon fa-envelope"><span class="label">Email</span></a></li> </ul> <ul class="copyright"> <li>&copy; Code for Sri Lanka</li> <li class="fas fa-heart"style="color:red;"></li> </ul> </footer> <script src="assets/js/main.js"></script> </body> </html>
{ "content_hash": "615e405bf2b5d0b0edf7fe625be58602", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 167, "avg_line_length": 50.432432432432435, "alnum_prop": 0.6441586280814576, "repo_name": "codeforsrilanka/codeforsrilanka.github.io", "id": "70377fff17debf491a117db6566c71b2561092b1", "size": "1866", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.html", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "222449" }, { "name": "HTML", "bytes": "11414" }, { "name": "JavaScript", "bytes": "5081" } ], "symlink_target": "" }
package alluxio.master.journal.ufs; import alluxio.conf.ServerConfiguration; import alluxio.Constants; import alluxio.conf.PropertyKey; import alluxio.underfs.UnderFileSystem; import alluxio.util.ThreadFactoryUtils; import com.google.common.base.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import javax.annotation.concurrent.ThreadSafe; /** * A garbage collector that periodically snapshots the journal and deletes files that are not * necessary anymore. The implementation guarantees that the journal contains all the information * required to recover the master full state. */ @ThreadSafe final class UfsJournalGarbageCollector implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(UfsJournalGarbageCollector.class); private final ScheduledExecutorService mExecutor = Executors.newSingleThreadScheduledExecutor( ThreadFactoryUtils.build("UfsJournalGarbageCollector-%d", true)); private final UfsJournal mJournal; private final UnderFileSystem mUfs; private ScheduledFuture<?> mGc; /** * Creates the {@link UfsJournalGarbageCollector} instance. * * @param journal the UFS journal handle */ UfsJournalGarbageCollector(UfsJournal journal) { mJournal = Preconditions.checkNotNull(journal, "journal"); mUfs = mJournal.getUfs(); mGc = mExecutor.scheduleAtFixedRate(this::gc, Constants.SECOND_MS, ServerConfiguration.getMs(PropertyKey.MASTER_JOURNAL_GC_PERIOD_MS), TimeUnit.MILLISECONDS); } @Override public void close() { if (mGc != null) { mGc.cancel(true); mGc = null; } mExecutor.shutdown(); } /** * Deletes unneeded snapshots. */ void gc() { UfsJournalSnapshot snapshot; try { snapshot = UfsJournalSnapshot.getSnapshot(mJournal); } catch (IOException e) { LOG.warn("Failed to get journal snapshot with error {}.", e.getMessage()); return; } long checkpointSequenceNumber = 0; // Checkpoint. List<UfsJournalFile> checkpoints = snapshot.getCheckpoints(); if (!checkpoints.isEmpty()) { checkpointSequenceNumber = checkpoints.get(checkpoints.size() - 1).getEnd(); } for (int i = 0; i < checkpoints.size() - 1; i++) { // Only keep at most 2 checkpoints. if (i < checkpoints.size() - 2) { deleteNoException(checkpoints.get(i).getLocation()); } // For the the second last checkpoint. Check whether it has been there for a long time. gcFileIfStale(checkpoints.get(i), checkpointSequenceNumber); } for (UfsJournalFile log : snapshot.getLogs()) { gcFileIfStale(log, checkpointSequenceNumber); } for (UfsJournalFile tmpCheckpoint : snapshot.getTemporaryCheckpoints()) { gcFileIfStale(tmpCheckpoint, checkpointSequenceNumber); } } /** * Garbage collects a file if necessary. * * @param file the file * @param checkpointSequenceNumber the first sequence number that has not been checkpointed */ private void gcFileIfStale(UfsJournalFile file, long checkpointSequenceNumber) { if (file.getEnd() > checkpointSequenceNumber && !file.isTmpCheckpoint()) { return; } long lastModifiedTimeMs; try { lastModifiedTimeMs = mUfs.getFileStatus(file.getLocation().toString()).getLastModifiedTime(); } catch (IOException e) { LOG.warn("Failed to get the last modified time for {}.", file.getLocation()); return; } long thresholdMs = file.isTmpCheckpoint() ? ServerConfiguration.getMs(PropertyKey.MASTER_JOURNAL_TEMPORARY_FILE_GC_THRESHOLD_MS) : ServerConfiguration.getMs(PropertyKey.MASTER_JOURNAL_GC_THRESHOLD_MS); if (System.currentTimeMillis() - lastModifiedTimeMs > thresholdMs) { deleteNoException(file.getLocation()); } } /** * Deletes a file and swallows the exception by logging it. * * @param location the file location */ private void deleteNoException(URI location) { try { mUfs.deleteFile(location.toString()); LOG.info("Garbage collected journal file {}.", location); } catch (IOException e) { LOG.warn("Failed to garbage collect journal file {}.", location); } } }
{ "content_hash": "848f324ec5910fa335bf7c11bfa4953e", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 99, "avg_line_length": 32.09285714285714, "alnum_prop": 0.7137769864233252, "repo_name": "calvinjia/tachyon", "id": "eb25e3ab3a06581be31273f6ebfb8c4fc16bacb6", "size": "5005", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "core/server/common/src/main/java/alluxio/master/journal/ufs/UfsJournalGarbageCollector.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "10146" }, { "name": "Dockerfile", "bytes": "5206" }, { "name": "Go", "bytes": "27246" }, { "name": "HTML", "bytes": "7039" }, { "name": "Java", "bytes": "11063149" }, { "name": "JavaScript", "bytes": "6914" }, { "name": "Python", "bytes": "11519" }, { "name": "Roff", "bytes": "5919" }, { "name": "Ruby", "bytes": "19102" }, { "name": "Shell", "bytes": "164560" }, { "name": "Smarty", "bytes": "7836" }, { "name": "TypeScript", "bytes": "274301" } ], "symlink_target": "" }
package com.malin.rxjava.utils; import rx.Subscription; import rx.subscriptions.CompositeSubscription; public class RxUtils { private RxUtils() { } public static void unsubscribeIfNotNull(Subscription subscription) { if (subscription != null) { subscription.unsubscribe(); } } public static CompositeSubscription getNewCompositeSubIfUnsubscribed(CompositeSubscription subscription) { if (subscription == null || subscription.isUnsubscribed()) { return new CompositeSubscription(); } return subscription; } }
{ "content_hash": "b71a742b24a9743d59ad7c396a64ba97", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 110, "avg_line_length": 22.40740740740741, "alnum_prop": 0.6793388429752066, "repo_name": "androidmalin/RengwuxianRxjava", "id": "43f3f6787ee1461da096430f4c282f338921aabf", "size": "1742", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/malin/rxjava/utils/RxUtils.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "103923" } ], "symlink_target": "" }
/*** elektra.TicketsPG ****************************************************** $Header: $ In dieser Klasse werden fuer WebRequest und WebInterface die Daten fuer eine Anfrage einer Ermaessigung in einer Preisgruppe eines Kartenauftrages verpackt (c) ORESTES Lizenzvertreibsges. mbH 2005 Karsten Rolfs OrderInData bzw. RequestInData |- Bon |- Artikel |- Card |- TicketsPG |- Tickets *****************************************************************************/ package elektra; public class Tickets { private String szReduction; private Integer nTickets; // Anzahl ermaessigte Karten in PG public Tickets() { setReduction("0"); setTickets("0"); } public void setReduction(String a) { this.szReduction = a; } public void setTickets(String a) { this.nTickets = new Integer(a); } public String getReduction() { return this.szReduction; } public Integer getTickets() { return this.nTickets; } }
{ "content_hash": "c123f1c010e01ba987480456a979b393", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 88, "avg_line_length": 21.06122448979592, "alnum_prop": 0.563953488372093, "repo_name": "yanhongwang/TicketBookingSystem", "id": "4f3ae8a5e577fc5752a1791ee653053f7e2a010f", "size": "1032", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/elektra/Tickets.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "76272" }, { "name": "Java", "bytes": "2374148" }, { "name": "JavaScript", "bytes": "247196" }, { "name": "Shell", "bytes": "11182" }, { "name": "XSLT", "bytes": "102585" } ], "symlink_target": "" }
<?php namespace Yoast\WP\SEO\Helpers; use Yoast\WP\SEO\Models\SEO_Links; /** * A helper object for URLs. */ class Url_Helper { /** * Retrieve home URL with proper trailing slash. * * @param string $path Path relative to home URL. * @param string|null $scheme Scheme to apply. * * @return string Home URL with optional path, appropriately slashed if not. */ public function home( $path = '', $scheme = null ) { $home_url = \home_url( $path, $scheme ); if ( ! empty( $path ) ) { return $home_url; } $home_path = \wp_parse_url( $home_url, \PHP_URL_PATH ); if ( $home_path === '/' ) { // Home at site root, already slashed. return $home_url; } if ( \is_null( $home_path ) ) { // Home at site root, always slash. return \trailingslashit( $home_url ); } if ( \is_string( $home_path ) ) { // Home in subdirectory, slash if permalink structure has slash. return \user_trailingslashit( $home_url ); } return $home_url; } /** * Determines whether the plugin is active for the entire network. * * @return bool Whether or not the plugin is network-active. */ public function is_plugin_network_active() { static $network_active = null; if ( ! \is_multisite() ) { return false; } // If a cached result is available, bail early. if ( $network_active !== null ) { return $network_active; } $network_active_plugins = \wp_get_active_network_plugins(); // Consider MU plugins and network-activated plugins as network-active. $network_active = \strpos( \wp_normalize_path( \WPSEO_FILE ), \wp_normalize_path( \WPMU_PLUGIN_DIR ) ) === 0 || \in_array( \WP_PLUGIN_DIR . '/' . \WPSEO_BASENAME, $network_active_plugins, true ); return $network_active; } /** * Retrieve network home URL if plugin is network-activated, or home url otherwise. * * @return string Home URL with optional path, appropriately slashed if not. */ public function network_safe_home_url() { /** * Action: 'wpseo_home_url' - Allows overriding of the home URL. */ \do_action( 'wpseo_home_url' ); // If the plugin is network-activated, use the network home URL. if ( self::is_plugin_network_active() ) { return \network_home_url(); } return \home_url(); } /** * Check whether a url is relative. * * @param string $url URL string to check. * * @return bool True when url is relative. */ public function is_relative( $url ) { return ( \strpos( $url, 'http' ) !== 0 && \strpos( $url, '//' ) !== 0 ); } /** * Gets the path from the passed URL. * * @codeCoverageIgnore It only wraps a WordPress function. * * @param string $url The URL to get the path from. * * @return string The path of the URL. Returns an empty string if URL parsing fails. */ public function get_url_path( $url ) { return (string) \wp_parse_url( $url, \PHP_URL_PATH ); } /** * Determines the file extension of the given url. * * @param string $url The URL. * * @return string The extension. */ public function get_extension_from_url( $url ) { $path = $this->get_url_path( $url ); if ( $path === '' ) { return ''; } $parts = \explode( '.', $path ); if ( empty( $parts ) || \count( $parts ) === 1 ) { return ''; } return \end( $parts ); } /** * Ensures that the given url is an absolute url. * * @param string $url The url that needs to be absolute. * * @return string The absolute url. */ public function ensure_absolute_url( $url ) { if ( ! \is_string( $url ) || $url === '' ) { return $url; } if ( $this->is_relative( $url ) === true ) { return $this->build_absolute_url( $url ); } return $url; } /** * Parse the home URL setting to find the base URL for relative URLs. * * @param string|null $path Optional path string. * * @return string */ public function build_absolute_url( $path = null ) { $path = \wp_parse_url( $path, \PHP_URL_PATH ); $url_parts = \wp_parse_url( \home_url() ); $base_url = \trailingslashit( $url_parts['scheme'] . '://' . $url_parts['host'] ); if ( ! \is_null( $path ) ) { $base_url .= \ltrim( $path, '/' ); } return $base_url; } /** * Returns the link type. * * @param array $url The URL, as parsed by wp_parse_url. * @param array|null $home_url Optional. The home URL, as parsed by wp_parse_url. Used to avoid reparsing the home_url. * @param bool $is_image Whether or not the link is an image. * * @return string The link type. */ public function get_link_type( $url, $home_url = null, $is_image = false ) { // If there is no scheme and no host the link is always internal. // Beware, checking just the scheme isn't enough as a link can be //yoast.com for instance. if ( empty( $url['scheme'] ) && empty( $url['host'] ) ) { return ( $is_image ) ? SEO_Links::TYPE_INTERNAL_IMAGE : SEO_Links::TYPE_INTERNAL; } // If there is a scheme but it's not http(s) then the link is always external. if ( \array_key_exists( 'scheme', $url ) && ! \in_array( $url['scheme'], [ 'http', 'https' ], true ) ) { return ( $is_image ) ? SEO_Links::TYPE_EXTERNAL_IMAGE : SEO_Links::TYPE_EXTERNAL; } if ( \is_null( $home_url ) ) { $home_url = \wp_parse_url( \home_url() ); } // When the base host is equal to the host. if ( isset( $url['host'] ) && $url['host'] !== $home_url['host'] ) { return ( $is_image ) ? SEO_Links::TYPE_EXTERNAL_IMAGE : SEO_Links::TYPE_EXTERNAL; } // There is no base path and thus all URLs of the same domain are internal. if ( empty( $home_url['path'] ) ) { return ( $is_image ) ? SEO_Links::TYPE_INTERNAL_IMAGE : SEO_Links::TYPE_INTERNAL; } // When there is a path and it matches the start of the url. if ( isset( $url['path'] ) && \strpos( $url['path'], $home_url['path'] ) === 0 ) { return ( $is_image ) ? SEO_Links::TYPE_INTERNAL_IMAGE : SEO_Links::TYPE_INTERNAL; } return ( $is_image ) ? SEO_Links::TYPE_EXTERNAL_IMAGE : SEO_Links::TYPE_EXTERNAL; } }
{ "content_hash": "9434c72affaf9153d99036a3497074aa", "timestamp": "", "source": "github", "line_count": 216, "max_line_length": 120, "avg_line_length": 27.76851851851852, "alnum_prop": 0.6115371790596865, "repo_name": "andrewchart/andrewchart.co.uk-2017", "id": "3d8a30eab214613f20419147f262ab455757c8cd", "size": "5998", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "wp-content/plugins/wordpress-seo/src/helpers/url-helper.php", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "36741" }, { "name": "CSS", "bytes": "571057" }, { "name": "HTML", "bytes": "735482" }, { "name": "JavaScript", "bytes": "2142937" }, { "name": "LiveScript", "bytes": "6103" }, { "name": "M4", "bytes": "221" }, { "name": "PHP", "bytes": "8821189" }, { "name": "PostScript", "bytes": "1363542" }, { "name": "SCSS", "bytes": "7164" }, { "name": "Shell", "bytes": "3901" }, { "name": "Twig", "bytes": "25857" }, { "name": "XSLT", "bytes": "4171" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns:msxsl="urn:schemas-microsoft-com:xslt"> <head> <meta content="en-us" http-equiv="Content-Language" /> <meta content="text/html; charset=utf-16" http-equiv="Content-Type" /> <title _locid="PortabilityAnalysis0">.NET Portability Report</title> <style> /* Body style, for the entire document */ body { background: #F3F3F4; color: #1E1E1F; font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 0; margin: 0; } /* Header1 style, used for the main title */ h1 { padding: 10px 0px 10px 10px; font-size: 21pt; background-color: #E2E2E2; border-bottom: 1px #C1C1C2 solid; color: #201F20; margin: 0; font-weight: normal; } /* Header2 style, used for "Overview" and other sections */ h2 { font-size: 18pt; font-weight: normal; padding: 15px 0 5px 0; margin: 0; } /* Header3 style, used for sub-sections, such as project name */ h3 { font-weight: normal; font-size: 15pt; margin: 0; padding: 15px 0 5px 0; background-color: transparent; } h4 { font-weight: normal; font-size: 12pt; margin: 0; padding: 0 0 0 0; background-color: transparent; } /* Color all hyperlinks one color */ a { color: #1382CE; } /* Paragraph text (for longer informational messages) */ p { font-size: 10pt; } /* Table styles */ table { border-spacing: 0 0; border-collapse: collapse; font-size: 10pt; } table th { background: #E7E7E8; text-align: left; text-decoration: none; font-weight: normal; padding: 3px 6px 3px 6px; } table td { vertical-align: top; padding: 3px 6px 5px 5px; margin: 0px; border: 1px solid #E7E7E8; background: #F7F7F8; } .NoBreakingChanges { color: darkgreen; font-weight:bold; } .FewBreakingChanges { color: orange; font-weight:bold; } .ManyBreakingChanges { color: red; font-weight:bold; } .BreakDetails { margin-left: 30px; } .CompatMessage { font-style: italic; font-size: 10pt; } .GoodMessage { color: darkgreen; } /* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */ .localLink { color: #1E1E1F; background: #EEEEED; text-decoration: none; } .localLink:hover { color: #1382CE; background: #FFFF99; text-decoration: none; } /* Center text, used in the over views cells that contain message level counts */ .textCentered { text-align: center; } /* The message cells in message tables should take up all avaliable space */ .messageCell { width: 100%; } /* Padding around the content after the h1 */ #content { padding: 0px 12px 12px 12px; } /* The overview table expands to width, with a max width of 97% */ #overview table { width: auto; max-width: 75%; } /* The messages tables are always 97% width */ #messages table { width: 97%; } /* All Icons */ .IconSuccessEncoded, .IconInfoEncoded, .IconWarningEncoded, .IconErrorEncoded { min-width: 18px; min-height: 18px; background-repeat: no-repeat; background-position: center; } /* Success icon encoded */ .IconSuccessEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconSuccess#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABPElEQVR4Xp1Tv0vDUBi8FqeA4NpBcBLcWnQSApncOnTo4FSnjP0DsnXpH5CxiwbHDg4Zuj4oOEXiJgiC4FDcCkLWmIMc1Pfw+eMgQ77v3Xf3Pe51YKGqqisAEwCR1TIAsiAIblSo6xrdHeJR85Xle3mdmCQKb0PsfqyxxzM8K15HZADl/H5+sHpZwYfxyRjTs+kWwKBx8yoHd2mRiuzF8mkJniWH/13u3Fjrs/EdhsdDFHGB/DLXEJBDLh1MWPAhPo1BLB4WX5yQywHR+m3tVe/t97D52CB/ziG0nIgD/qDuYg8WuCcVZ2YGwlJ3YDugkpR/VNcAEx6GEKhERSr71FuO4YCM4XBdwKvecjIlkSnsO0Hyp/GxSeJAdzBKzpOtnPwyyiPdAZhpZptT04tU+zk7s8czeges//s5C5+CwqrR4/gw+AAAAABJRU5ErkJggg==); } /* Information icon encoded */ .IconInfoEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconInformation#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHElEQVR4Xs2TsUoDQRRF7wwoziokjZUKadInhdhukR9YP8DMX1hYW+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/mv9gkhtyMDhcAxgzRsp7flj8B/HF1RsMXq+NZMkopaHe7lbKxQUEIGbKsYNoGn969060hZBkQex/W8oRQwsQaW2o3Ago2SVcJUzAgY3N0lTCZZm+zPS8HB51gMmS1DEYyOz9acKO1D8JWTlafKIMxdhvlfdyT94Vv5h7P8Ky7nQzACmhvKq3zk3PjW9asz9D/1oigecsioooAAAAASUVORK5CYII=); } /* Warning icon encoded */ .IconWarningEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconWarning#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/QGTCxdWJgiQYWKXJWKIXHIlyw5lqr34tQgEOdcBsCOx5yZK3hCCKdYXneQkh4pEfqzLfu+wVDSyyzFoJjfz9NB+pAF+eizx2Vruts0k15mPgvS6GYvpVtQhB61IB/dk6AF6fS4Ben0uIX5odtFe8Q/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/gFq44JaVSCXeQAAAABJRU5ErkJggg==); } /* Error icon encoded */ .IconErrorEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconError#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABQElEQVR4XqWTvUoEQRCE6wYPZUA80AfwAQz23uCMjA7MDRQEIzPBVEyNTQUFIw00vcQTTMzuAh/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+GsHRk0fQmPAH1GfmZirbCfDJ61tw3Px8/8pZsPAG4jlVhcPgZ7adwNWBB68lkRQWFiTgFlbnLY3DGGM7izIJIyT/jjIvEJw6fdJTc6krDzh6aMwMP9bvDH4ADSsa9uSWVJkAAAAASUVORK5CYII=); } </style> </head> <body> <h1 _locid="PortabilityReport">.NET Portability Report</h1> <div id="content"> <div id="submissionId" style="font-size:8pt;"> <p> <i> Submission Id&nbsp; 383a9e1c-8611-47dc-b2b4-dc160b64f83e </i> </p> </div> <h2 _locid="SummaryTitle"> <a name="Portability Summary"></a>Portability Summary </h2> <div id="summary"> <table> <tbody> <tr> <th>Assembly</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> </tr> <tr> <td><strong><a href="#FlatFile.FixedLength">FlatFile.FixedLength</a></strong></td> <td class="text-center">100.00 %</td> <td class="text-center">98.37 %</td> <td class="text-center">100.00 %</td> <td class="text-center">98.37 %</td> </tr> </tbody> </table> </div> <div id="details"> <a name="FlatFile.FixedLength"><h3>FlatFile.FixedLength</h3></a> <table> <tbody> <tr> <th>Target type</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> <th>Recommended changes</th> </tr> <tr> <td>System.Collections.ArrayList</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">#ctor</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">Add(System.Object)</td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </tbody> </table> <p> <a href="#Portability Summary">Back to Summary</a> </p> </div> </div> </body> </html>
{ "content_hash": "0fc4982491e1a44c274198000058d611", "timestamp": "", "source": "github", "line_count": 295, "max_line_length": 562, "avg_line_length": 40.9593220338983, "alnum_prop": 0.5183315401804187, "repo_name": "kuhlenh/port-to-core", "id": "16060a417f921b75da5f8170ea35e569ebe6ac67", "size": "12083", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "Reports/fl/flatfile.fixedlength.0.2.16/FlatFile.FixedLength-net45.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2323514650" } ], "symlink_target": "" }
package org.openkilda.wfm.share.zk; public enum ZkStreams { ZK }
{ "content_hash": "6f18de58154088ba5d3a2dfc7c36715f", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 35, "avg_line_length": 10.285714285714286, "alnum_prop": 0.6944444444444444, "repo_name": "telstra/open-kilda", "id": "96d2ec70b8ec146686f2ebd9d532de3a95adf175", "size": "689", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src-java/base-topology/base-storm-topology/src/main/java/org/openkilda/wfm/share/zk/ZkStreams.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "89798" }, { "name": "CMake", "bytes": "4314" }, { "name": "CSS", "bytes": "233390" }, { "name": "Dockerfile", "bytes": "30541" }, { "name": "Groovy", "bytes": "2234079" }, { "name": "HTML", "bytes": "362166" }, { "name": "Java", "bytes": "14631453" }, { "name": "JavaScript", "bytes": "369015" }, { "name": "Jinja", "bytes": "937" }, { "name": "Makefile", "bytes": "20500" }, { "name": "Python", "bytes": "367364" }, { "name": "Shell", "bytes": "62664" }, { "name": "TypeScript", "bytes": "867537" } ], "symlink_target": "" }
var tb = new KrdToolbox(); (function () { "use strict"; var USE_COOKIES = false; var DEBUG_LEVEL = 2; var REDCAP = "REDCAP"; var LOCAL = "LOCAL"; var app = angular.module('Vand-AID', ['library-canvas', 'va-sidebox', 'ngResource', 'ngAnimate', 'ngMaterial', 'ngSanitize', 'menuBar', 'va-topbar']); app.config(function ($mdThemingProvider) { // from http://mcg.mbitson.com/#/ $mdThemingProvider.definePalette('vanderbiltPrimary', { "50": "#f6f2e9", "100": "#e0d3b2", "200": "#d0bd8a", "300": "#bca057", "400": "#af9146", "500": "#997f3d", "600": "#836d34", "700": "#6d5b2c", "800": "#574923", "900": "#41361a", "A100": "#f6f2e9", "A200": "#e0d3b2", "A400": "#af9146", "A700": "#6d5b2c", 'contrastDefaultColor': 'light', // whether, by default, text (contrast) // on this palette should be dark or light 'contrastDarkColors': ['50', '100', //hues which contrast should be 'dark' by default '200', '300', '400', 'A100'], 'contrastLightColors': undefined // could also specify this if default was 'dark' }); $mdThemingProvider.definePalette('vanderbiltBlueAccent', { "50": "#bedce5", "100": "#87bfcf", "200": "#5faabe", "300": "#3e8599", "400": "#357283", "500": "#2c5f6d", "600": "#234c57", "700": "#1a3941", "800": "#12262c", "900": "#091316", "A100": "#bedce5", "A200": "#87bfcf", "A400": "#357283", "A700": "#1a3941", 'contrastDefaultColor': 'light', }); $mdThemingProvider.theme('default') .accentPalette('vanderbiltBlueAccent'); $mdThemingProvider.theme('default') .primaryPalette('vanderbiltPrimary'); }); /** * ***************************************************************** * App controller * ***************************************************************** */ app.controller("VandAIDApp", function ($http, $scope, $mdSidenav, $mdToast, $mdDialog, $mdMedia) { var self = this; var loadFields = function (user) { var filename = "/resources/metadata_export.json"; $http.get(filename).then( // on success function (data) { // setTimeout(function () { console.log("timeout finished, initializing data"); $scope.fm.initialize(data.data); if (typeof(user) != "undefined") { loadDefaults(user.key); } else { loadDefaults(); } // }, 2000); } , // on failure function () { console.log("failed to load fields from ", filename); } ); }; /** * Loads defaults for fields from a JSON file * @param username */ var loadDefaults = function (username) { // Load status of selected items var fields_filename; if (typeof(username) != "undefined") { fields_filename = "/data/" + username + ".data.json"; } else { fields_filename = "/resources/defaults_record_export.json"; } console.log("Attempting to load from " + fields_filename); $http.get(fields_filename).then( // on default record found and loaded function (data) { $scope.fm.loadFieldValues(data.data[0]); console.log("Loaded values from " + fields_filename); }, // on failure function () { console.log("Unable to load values from " + fields_filename); if (typeof(username) != "undefined") { loadDefaults(); } } ); }; /** * Loads items from a JSON resource * @param filename * @param $resource */ var loadItems = function (filename) { var defaultFilename = "/resources/items.json"; if (typeof(filename) == "undefined") { filename = defaultFilename; } filename = defaultFilename; $http.get(filename).then( function (data) { // setTimeout(function() { console.log("timeout finished, initializing items"); $scope.itemManager.initialize(data.data.items); // }, 3000); }, function () { showSimpleToast("Unable to find " + filename); // escape if fail at getting default if (filename == defaultFilename) return; loadItems(); }); }; /** * Basic constructor for a {User} object * @constructor */ function User() { this.id = ""; this.key = ""; this.name = ""; this.logged_in = false; this.source = ""; this.consented = false; } $scope.toggleToolbox = function (val) { if (typeof val === 'undefined') { val = $scope.tabData.hide; } $scope.tabData.hide = !val; }; $scope.toggleSidenav = function (menuId) { $mdSidenav(menuId).toggle(); }; /** * Displays a short, unobtrusive message on the screen * @param toastContent The content of the message */ var showSimpleToast = function (toastContent) { $mdToast.show( $mdToast.simple() .content(toastContent) .position('top right') .hideDelay(3000) ); }; var originatorEv; this.openMenu = function ($mdOpenMenu, ev) { originatorEv = ev; $mdOpenMenu(ev); }; $scope.addNewRecord = function (newKey) { console.log('attempting to add record: ' + newKey); // 'if' Checks to be sure not adding an element already in the array if ($scope.records.indexOf(newKey) == -1) $scope.records.push(newKey) }; $scope.updateRecords = function (newKeysText) { $scope.records = []; var newKeysArray = newKeysText.split('\n'); for (var i = 0; i < newKeysArray.length; i++) { $scope.addNewRecord(newKeysArray[i]); } }; $scope.toggle = tb.toggle; $scope.exists = tb.exists; /** *************************************************************** * BEGIN VARIABLE DECLARATIONS * @type {Array} * **************************************************************** */ $scope.isReady = false; $scope.fm = new FieldManager; $scope.itemManager = new ItemManager(); var fmObserver = new Observer(); fmObserver.update = function (newValue, oldValue) { if ($scope.fm.isReady && $scope.itemManager.isReady()) { $scope.isReady = true; } }; $scope.fm.addObserver(fmObserver); var imObserver = new Observer(); imObserver.update = function (newValue, oldValue) { $scope.isReady = $scope.fm.isReady && $scope.itemManager.isReady(); }; $scope.itemManager.addObserver(imObserver); $scope.vaOptions = { show_labels: false }; $scope.records = []; $scope.apiData = ""; $scope.showToolbox = true; $scope.showSettings = false; $scope.tabData = { selectedIndex: 0 }; $scope.selectedIndex = 0; $scope.updateSelected = function(newIndex) { $scope.user = new User(); $scope.user.key = $scope.records[newIndex]; loadFields($scope.user); loadItems(); }; $scope.$watch('selectedIndex', function(newValue, oldValue) { console.log("Updating selected index: " + $scope.selectedIndex); $scope.updateSelected($scope.selectedIndex); }); }); app.directive('elementList', function () { return { restrict: 'E', templateUrl: 'element-list.html' }; }); app.directive('username', function () { return { restrict: 'E', templateUrl: 'library/username.html', controller: function ($scope) { } } }); app.directive('fieldPane', function() { return { restrict : 'E', templateUrl : 'field-pane.html', scope: true, link: function(scope, element, attrs) { scope.fieldAlign = attrs.fieldAlign || "vertical"; }, controller: function($scope) { $scope.$watch('isReady', function(newValue, oldValue) { // console.log('isReady: ' + newValue); if (newValue) { $scope.field = $scope.fm.fields[$scope.fieldId]; } }); $scope.field = $scope.fm.fields[$scope.fieldId]; $scope.getWidgetType = function( fieldType ) { switch (fieldType) { case "radio": case "yesno": case "truefalse": return "fields/radio.html"; case "checkbox": return "fields/checkbox.html"; case "checklist": return "fields/checklist.html"; case "text": case "notes": default: return "fields/text.html"; } }; }, controllerAs: 'fieldCtrl' }; }); })();
{ "content_hash": "fb80c67e377933a4ae19c9aadff75837", "timestamp": "", "source": "github", "line_count": 340, "max_line_length": 100, "avg_line_length": 26.32941176470588, "alnum_prop": 0.5246872207327972, "repo_name": "KevinDufendach/vandaid-nicuhandoff", "id": "48134b1ae01214fe9aea6b0f622b3f679b28959c", "size": "8952", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/eval.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7958" }, { "name": "HTML", "bytes": "69619" }, { "name": "JavaScript", "bytes": "81195" }, { "name": "PHP", "bytes": "5185" } ], "symlink_target": "" }
package com.mysql.jdbc; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.SQLException; import java.util.Properties; public class ReflectiveStatementInterceptorAdapter implements StatementInterceptorV2 { private final StatementInterceptor toProxy; final Method v2PostProcessMethod; public ReflectiveStatementInterceptorAdapter(StatementInterceptor toProxy) { this.toProxy = toProxy; this.v2PostProcessMethod = getV2PostProcessMethod(toProxy.getClass()); } public void destroy() { this.toProxy.destroy(); } public boolean executeTopLevelOnly() { return this.toProxy.executeTopLevelOnly(); } public void init(Connection conn, Properties props) throws SQLException { this.toProxy.init(conn, props); } public ResultSetInternalMethods postProcess(String sql, Statement interceptedStatement, ResultSetInternalMethods originalResultSet, Connection connection, int warningCount, boolean noIndexUsed, boolean noGoodIndexUsed, SQLException statementException) throws SQLException { try { return (ResultSetInternalMethods) this.v2PostProcessMethod.invoke(this.toProxy, new Object[] { sql, interceptedStatement, originalResultSet, connection, Integer.valueOf(warningCount), noIndexUsed ? Boolean.TRUE : Boolean.FALSE, noGoodIndexUsed ? Boolean.TRUE : Boolean.FALSE, statementException }); } catch (IllegalArgumentException e) { SQLException sqlEx = new SQLException("Unable to reflectively invoke interceptor"); sqlEx.initCause(e); throw sqlEx; } catch (IllegalAccessException e) { SQLException sqlEx = new SQLException("Unable to reflectively invoke interceptor"); sqlEx.initCause(e); throw sqlEx; } catch (InvocationTargetException e) { SQLException sqlEx = new SQLException("Unable to reflectively invoke interceptor"); sqlEx.initCause(e); throw sqlEx; } } public ResultSetInternalMethods preProcess(String sql, Statement interceptedStatement, Connection connection) throws SQLException { return this.toProxy.preProcess(sql, interceptedStatement, connection); } public static final Method getV2PostProcessMethod(Class<?> toProxyClass) { try { Method postProcessMethod = toProxyClass.getMethod("postProcess", new Class[] { String.class, Statement.class, ResultSetInternalMethods.class, Connection.class, Integer.TYPE, Boolean.TYPE, Boolean.TYPE, SQLException.class }); return postProcessMethod; } catch (SecurityException e) { return null; } catch (NoSuchMethodException e) { return null; } } }
{ "content_hash": "367037625744f89a62a28ed5669933dc", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 158, "avg_line_length": 39.41095890410959, "alnum_prop": 0.6965589155370178, "repo_name": "anderslatif/forbr_ndingen-display", "id": "d7a3f904211f904a511e4a65f169e26b1a09e01f", "size": "3972", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "mysql-connector-java-5.1.38/src/com/mysql/jdbc/ReflectiveStatementInterceptorAdapter.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "14592" }, { "name": "HTML", "bytes": "655112" }, { "name": "Java", "bytes": "6506135" }, { "name": "JavaScript", "bytes": "827" } ], "symlink_target": "" }
<?php namespace core\interfaces; /** * Interface PathHelperInterface * @package core\interfaces * Интерфейс для класса PathHelper */ interface PathHelperInterface{ /** * @param $path string Относительный или абсолютный путь к файлу или папке * @return bool Проверяет существует ли данный файл или папка, возращает результат проверки */ static function isExist($path); /** * @return mixed Получает рутовую директорию приложения */ static function getRootDirectory(); /** * @param $path string Относительный или абсолютный путь к файлу или папке * @return string Возращает абсолютный, по возможности реальный, путь к файлу или папке */ static function createPath($path); /** * @param $version string Версии приложения к файлам которого строить путь * @param $path string Путь относительно корневой папки версии * @throws \Exception Функция принимает только абсолютный путь * @throws \Exception Папка не существует * @return string Абсолютный путь к файлу приложения с учетом его версии */ static function createVersionedPath($version, $path); /** * @param $path string Путь к файлу или папке * @return bool Проверят является ли путь абсолютным, возращает результат проверки * @throws \Exception Пустой путь */ static function isAbsolutePath($path); /** * Подключение файла отностетельно корня приложения * @param $path string Относительный или абсолютный путь к файлу * @throws \Exception Файл не существует */ static function requireFile($path); /** * Подключение файла отностетельно версии приложения * @param $version string Версия приложения * @param $path string Относительный или абсолютный путь к файлу * @throws \Exception Файл не существует */ public static function requireVersionedFile($version, $path); /** * @return string Абсолютный путь к папке с настройками приложения */ public static function getSettingsFolderPath(); /** * @return string Абсолютный путь к папке с резервными копиями */ static function getBackupsPath(); /** * @param $version string Версия приложения резервные копии базы данных которого требуются * @return string Абсолютный путь к папке с резервными копиямибазы данных этого приложения */ public static function getDatabasesDumpPath($version); /** * @param $database string База, дамп которой нужно взять * @param $version string Версия приложения резервные копия базы данных которого требуется * @return bool|string Абсолютный путь к файлу с резервной копией базы данных этого приложения */ static function getLastDatabaseDump($database, $version); }
{ "content_hash": "5000b069590fbba077d02693de6d3efd", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 102, "avg_line_length": 38.1375, "alnum_prop": 0.6414290396591281, "repo_name": "savchukoleksii/beaversteward", "id": "a99d25e7c176b48a525ba675e0d59b12f40aa6f9", "size": "4129", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "www/application/core/interfaces/PathHelperInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "3092" }, { "name": "CSS", "bytes": "72333" }, { "name": "HTML", "bytes": "1333071" }, { "name": "JavaScript", "bytes": "5641362" }, { "name": "PHP", "bytes": "5916922" }, { "name": "Roff", "bytes": "29" } ], "symlink_target": "" }
import mongoose = require("mongoose"); import { IUserModel } from "./IUserModel"; var userSchema = new mongoose.Schema({ email: { type: String, required: true }, password: { type: String, required: true}, displayName: String }); var User = mongoose.model<IUserModel>("User", userSchema,'myUserCol'); export default User;
{ "content_hash": "4d9b46aa9ea10101a9e3beb5139fdf10", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 70, "avg_line_length": 22.6, "alnum_prop": 0.6873156342182891, "repo_name": "ziaukhan/learn-node-typescript", "id": "2e75cb4c6a07146d8a9d06b2657c7e09b3f52523", "size": "384", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "step08_chapter08_MongoDB/typed_mongoose/basic3/User.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "769927" }, { "name": "HTML", "bytes": "3276" }, { "name": "JavaScript", "bytes": "4017101" }, { "name": "Ruby", "bytes": "971" }, { "name": "TypeScript", "bytes": "95019" } ], "symlink_target": "" }
<properties XML_version="1.2"> <property Type="stringfield" Value="1.212" id="TIOptionsVersion"></property> <property Type="stringfield" Value="-D=__MSP430F47187__ --data_model=restricted --use_hw_mpy=32 --silicon_errata=CPU19" id="CompilerBuildOptions"></property> <property Type="stringfield" Value="-llibmath.a -i${CCS_BASE_ROOT}/msp430/lib/4xx --use_hw_mpy=32 --cinit_hold_wdt=on" id="LinkerBuildOptions"></property> </properties>
{ "content_hash": "7ea0db53b07663197e54ba0cb50495c9", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 159, "avg_line_length": 87.2, "alnum_prop": 0.7362385321100917, "repo_name": "pftbest/msp430_svd", "id": "9c9b861b2e4632b2aa74ca5765eb67aef95fd089", "size": "436", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "msp430-gcc-support-files/targetdb/options/MSP430F47187_TI.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "154338488" }, { "name": "Python", "bytes": "3616" }, { "name": "Rust", "bytes": "24457" } ], "symlink_target": "" }
package com.vmware.vim25; /** * @author Steve Jin (http://www.doublecloud.org) * @version 5.1 */ @SuppressWarnings("all") public class ClusterDpmHostConfigSpec extends ArrayUpdateSpec { public ClusterDpmHostConfigInfo info; public ClusterDpmHostConfigInfo getInfo() { return this.info; } public void setInfo(ClusterDpmHostConfigInfo info) { this.info=info; } }
{ "content_hash": "db1c6b55029a1634134b89ebd4be2ede", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 63, "avg_line_length": 18.285714285714285, "alnum_prop": 0.7369791666666666, "repo_name": "xebialabs/vijava", "id": "30e976c56c1a30352bd64a41ec731d5195848679", "size": "2024", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/vmware/vim25/ClusterDpmHostConfigSpec.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Groovy", "bytes": "377" }, { "name": "Java", "bytes": "7842140" } ], "symlink_target": "" }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAvatarsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('avatars', function (Blueprint $table) { $table->increments('id'); $table->integer('u_id'); $table->string('url'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('avatars'); } }
{ "content_hash": "7a2e433a32afa9e86f4912df80a6e2ff", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 63, "avg_line_length": 20.12121212121212, "alnum_prop": 0.5542168674698795, "repo_name": "tinythink/tms", "id": "38e60b4e903fe150ac04c15b2f05c4a42e2932f3", "size": "664", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "database/migrations/2017_07_20_172830_create_avatars_table.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "416585" }, { "name": "PHP", "bytes": "216161" }, { "name": "Shell", "bytes": "88" }, { "name": "Vue", "bytes": "563" } ], "symlink_target": "" }
module API module Entities class SSHKeyWithUser < Entities::SSHKey expose :user, using: Entities::UserPublic end end end
{ "content_hash": "ce635363476bb3518b7393ebb0cefda3", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 47, "avg_line_length": 19.857142857142858, "alnum_prop": 0.7050359712230215, "repo_name": "mmkassem/gitlabhq", "id": "95559bbf2ac151a242f1e3ece1c1830ba009d8c5", "size": "170", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "lib/api/entities/ssh_key_with_user.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "113683" }, { "name": "CoffeeScript", "bytes": "139197" }, { "name": "Cucumber", "bytes": "119759" }, { "name": "HTML", "bytes": "447030" }, { "name": "JavaScript", "bytes": "29805" }, { "name": "Ruby", "bytes": "2417833" }, { "name": "Shell", "bytes": "14336" } ], "symlink_target": "" }
<?php namespace couchServe\Service\Lib\Exceptions; class ModuleRegistryException extends GenericException {}
{ "content_hash": "350136f5e0084bc5dbf0151dc04dd260", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 61, "avg_line_length": 29.25, "alnum_prop": 0.7948717948717948, "repo_name": "filecage/couchserve-service", "id": "9d263b55eb371b46fc9ffe0424fd55d3fc585627", "size": "117", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Lib/Exceptions/ModuleRegistryException.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "99794" } ], "symlink_target": "" }
<!DOCTYPE html> <!--[if lt IE 7]> <html lang="en" ng-app="myApp" class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html lang="en" ng-app="myApp" class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html lang="en" ng-app="myApp" class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html lang="en" ng-app="myApp" class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>My AngularJS App</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="app/bower_components/html5-boilerplate/css/normalize.css"> <link rel="stylesheet" href="app/bower_components/html5-boilerplate/css/main.css"> <link rel="stylesheet" href="app/bower_components/semantic-ui/dist/semantic.css"> <link rel="stylesheet" href="app/app.css"> <script src="app/bower_components/html5-boilerplate/js/vendor/modernizr-2.6.2.min.js"></script> </head> <body> <!--[if lt IE 7]> <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif]--> <div ng-view></div> <!-- Placer dans le footer <div>Angular seed app: v<span app-version></span></div> --> <!-- In production use: <script src="//ajax.googleapis.com/ajax/libs/angularjs/x.x.x/angular.min.js"></script> --> <script src="app/bower_components/angular/angular.js"></script> <script src="app/bower_components/angular-route/angular-route.js"></script> <script src="app/bower_components/jquery/dist/jquery.js"></script> <script src="app/bower_components/semantic-ui/dist/semantic.js"></script> <script src="app/bower_components/lodash/lodash.js"></script> <script src="app/bower_components/restangular/dist/restangular.js"></script> <script src="app/components/version/version.js"></script> <script src="app/components/version/version-directive.js"></script> <script src="app/components/version/interpolate-filter.js"></script> <script src="app/app.js"></script> <!-- SERVICES --> <script src="app/login/loginService.js"></script> <!-- MODULES --> <script src="app/login/loginModule.js"></script> <!-- CONTROLEURS --> <script src="app/login/loginCtrl.js"></script> <script src="app/dashboard/dashboardCtrl.js"></script> </body> </html>
{ "content_hash": "53c6905c6e67863343d06c4d8ce3a10a", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 178, "avg_line_length": 44.767857142857146, "alnum_prop": 0.6549660949341842, "repo_name": "grmxque/seed-angular-php", "id": "78d7b1b437acecf22f7bea50b0447943bc1aa68b", "size": "2507", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "201" }, { "name": "CSS", "bytes": "400" }, { "name": "HTML", "bytes": "7639" }, { "name": "JavaScript", "bytes": "6695" }, { "name": "PHP", "bytes": "12892" } ], "symlink_target": "" }
<?php namespace QCharts\CoreBundle\ResultFormatter; class HCPolarFormatter extends HCUniversalFormatter { /** * @return array */ public function getChartConfig() { return [ "polar"=>true, "type"=>$this->getChartType($this->chartType) ]; } /** * @param $complexType * @return mixed */ public static function getChartType($complexType) { $regex = '/polar_/'; $result = preg_replace($regex, '', $complexType); return $result; } }
{ "content_hash": "d8c98c5bb2d0e3e915c7c703c5c64ea1", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 57, "avg_line_length": 18.4, "alnum_prop": 0.5507246376811594, "repo_name": "arnulfojr/qcharts", "id": "de3a1bce8e615a69b24dd94dc17dc95bb44508a5", "size": "552", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "QCharts/CoreBundle/ResultFormatter/HCPolarFormatter.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "12140" }, { "name": "HTML", "bytes": "75588" }, { "name": "JavaScript", "bytes": "112968" }, { "name": "PHP", "bytes": "452060" } ], "symlink_target": "" }
[Back to the "Repos API"](../../repos.md) | [Back to the navigation](../../README.md) ### List workflow runs for a repository https://docs.github.com/en/rest/reference/actions#list-workflow-runs-for-a-repository ```php $workflowRuns = $client->api('repo')->workflowRuns()->all('KnpLabs', 'php-github-api'); ``` ### List workflow runs https://docs.github.com/en/rest/reference/actions#list-workflow-runs ```php $runs = $client->api('repo')->workflowRuns()->listRuns('KnpLabs', 'php-github-api', $workflow); ``` ### Get a workflow run https://docs.github.com/en/rest/reference/actions#get-a-workflow-run ```php $workflowRun = $client->api('repo')->workflowRuns()->show('KnpLabs', 'php-github-api', $runId); ``` ### Delete a workflow run https://docs.github.com/en/rest/reference/actions#delete-a-workflow-run ```php $client->api('repo')->workflowRuns()->remove('KnpLabs', 'php-github-api', $runId); ``` ### Re-run a workflow https://docs.github.com/en/rest/reference/actions#re-run-a-workflow ```php $client->api('repo')->workflowRuns()->rerun('KnpLabs', 'php-github-api', $runId); ``` ### Cancel a workflow run https://docs.github.com/en/rest/reference/actions#cancel-a-workflow-run ```php $client->api('repo')->workflowRuns()->cancel('KnpLabs', 'php-github-api', $runId); ``` ### Get workflow run usage https://docs.github.com/en/rest/reference/actions#get-workflow-run-usage ```php $workflowUsage = $client->api('repo')->workflowRuns()->usage('KnpLabs', 'php-github-api', $runId); ``` ### Download workflow run logs https://docs.github.com/en/rest/reference/actions#download-workflow-run-logs ```php $logs = $client->api('repo')->workflowRuns()->downloadLogs('KnpLabs', 'php-github-api', $runId); file_put_contents('logs.zip', $logs); ``` ### Delete workflow run logs https://docs.github.com/en/rest/reference/actions#delete-workflow-run-logs ```php $client->api('repo')->workflowRuns()->deleteLogs('KnpLabs', 'php-github-api', $runId); ``` ### Approve workflow run https://docs.github.com/en/rest/reference/actions#approve-a-workflow-run-for-a-fork-pull-request ```php $client->api('repo')->workflowRuns()->approve('KnpLabs', 'php-github-api', $runId); ```
{ "content_hash": "834ec7c35ae8a76538b17ab40e16089f", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 98, "avg_line_length": 26.3855421686747, "alnum_prop": 0.689041095890411, "repo_name": "acrobat/php-github-api", "id": "4b879ca5b98c0ed25d88be61617a245eab85f24a", "size": "2228", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "doc/repo/actions/workflow_runs.md", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "721903" } ], "symlink_target": "" }
package sve2.fhbay.interfaces; import javax.ejb.Local; @Local public interface ArticleAdminLocal extends ArticleAdmin { }
{ "content_hash": "3f215bfb20f2d79d49101d04f518ce3c", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 57, "avg_line_length": 15.625, "alnum_prop": 0.808, "repo_name": "thomasfischl/fhbay", "id": "9b5b937f43fe2ab6bc819e2d2994eb638e03588e", "size": "125", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fhbay-server/fhbay-beans/src/main/java/sve2/fhbay/interfaces/ArticleAdminLocal.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "57863" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Ramalina scopulorum var. nigripes Wedd. ### Remarks null
{ "content_hash": "5011782daf235461816128b63e8a536e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 11.076923076923077, "alnum_prop": 0.7152777777777778, "repo_name": "mdoering/backbone", "id": "b899cebdaccd862b9a6c431682fb4bc4e6b22ae4", "size": "207", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Ramalinaceae/Ramalina/Ramalina scopulorum/Ramalina scopulorum nigripes/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
namespace os::mem::detail { class Pmr_pool : public std::enable_shared_from_this<Pmr_pool>, public std::pmr::memory_resource { public: using Resource = os::mem::Pmr_pool::Resource; using Resource_ptr = os::mem::Pmr_pool::Resource_ptr; Pmr_pool(std::size_t total_max, std::size_t suballoc_max, std::size_t max_allocs) : cap_total_{total_max}, cap_suballoc_{suballoc_max}, max_resources_{max_allocs} {} void* do_allocate(size_t size, size_t align) override { if (UNLIKELY(size + allocated_ > cap_total_)) { //printf("pmr about to throw bad alloc: sz=%zu alloc=%zu cap=%zu\n", size, allocated_, cap_total_); throw std::bad_alloc(); } // Adapt to aligned_alloc's minimum size- and alignemnt requiremnets if (align < sizeof(void*)) align = sizeof(void*); if (size < sizeof(void*)) size = sizeof(void*); void* buf = aligned_alloc(align, size); if (buf == nullptr) { //printf("pmr aligned_alloc return nullptr, throw bad alloc\n"); throw std::bad_alloc(); } allocated_ += size; allocations_++; return buf; } void do_deallocate (void* ptr, size_t size, size_t) override { // Adapt to aligned_alloc if (size < sizeof(void*)) size = sizeof(void*); free(ptr); allocated_ -= size; deallocations_++; } bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { return *this == other; } Resource_ptr resource_from_raw(Resource* raw) { Resource_ptr res_ptr(raw, [this](auto* res) { Expects(res->pool().get() == this); this->return_resource(res); }); return res_ptr; } Resource_ptr new_resource() { Expects(resource_count() < max_resources_); auto res = resource_from_raw(new Pmr_resource(shared_ptr())); used_resources_++; Ensures(res != nullptr); Ensures(resource_count() <= max_resources_); return res; } Resource_ptr release_front() { auto released = std::move(free_resources_.front()); free_resources_.pop_front(); used_resources_++; return released; } void return_resource(Resource* raw) { Expects(used_resources_ > 0); auto res_ptr = resource_from_raw(raw); used_resources_--; free_resources_.emplace_back(std::move(res_ptr)); } Resource_ptr get_resource() { if (! free_resources_.empty()) { auto& res = free_resources_.front(); if (UNLIKELY(! res->empty() and resource_count() < max_resources_)) { return new_resource(); } return release_front(); } if (resource_count() >= max_resources_) return nullptr; return new_resource(); } std::shared_ptr<Pmr_pool> shared_ptr() { return shared_from_this(); } std::size_t resource_count() { return used_resources_ + free_resources_.size(); } std::size_t free_resources() { return free_resources_.size(); } std::size_t used_resources() { return used_resources_; } std::size_t total_capacity() { return cap_total_; } void set_resource_capacity(std::size_t sz) { cap_suballoc_ = sz; } void set_total_capacity(std::size_t sz) { cap_total_ = sz; } std::size_t resource_capacity() { if (cap_suballoc_ == 0) { auto div = cap_total_ / (used_resources_ + os::mem::Pmr_pool::resource_division_offset); return std::min(div, allocatable()); } return cap_suballoc_; } std::size_t bytes_booked() { return cap_suballoc_ * used_resources_; } std::size_t bytes_bookable() { auto booked = bytes_booked(); if (booked > cap_total_) return 0; return cap_total_ - booked; } std::size_t allocated() { return allocated_; } std::size_t alloc_count() { return allocations_; } std::size_t dealloc_count() { return deallocations_; } bool full() { return allocated_ >= cap_total_; } bool empty() { return allocated_ == 0; } std::size_t allocatable() { auto allocd = allocated(); if (allocd > cap_total_) return 0; return cap_total_ - allocd; } // NOTE: This can cause leaks or other chaos if you're not sure what you're doing void clear_free_resources() { for (auto& res : free_resources_) { *res = Resource(shared_ptr()); } } private: std::size_t allocated_ = 0; std::size_t allocations_ = 0; std::size_t deallocations_ = 0; std::size_t cap_total_ = 0; std::size_t cap_suballoc_ = 0; std::size_t max_resources_ = 0; std::size_t used_resources_ = 0; std::deque<Resource_ptr> free_resources_{}; }; } // os::mem::detail namespace os::mem { // // Pmr_pool implementatino (PIMPL wrapper) // std::size_t Pmr_pool::total_capacity() { return impl->total_capacity(); } std::size_t Pmr_pool::resource_capacity() { return impl->resource_capacity(); } std::size_t Pmr_pool::allocatable() { return impl->allocatable(); } std::size_t Pmr_pool::allocated() { return impl->allocated(); } void Pmr_pool::set_resource_capacity(std::size_t s) { impl->set_resource_capacity(s); } void Pmr_pool::set_total_capacity(std::size_t s) { impl->set_total_capacity(s); }; Pmr_pool::Pmr_pool(size_t sz, size_t sz_sub, size_t max_allocs) : impl{std::make_shared<detail::Pmr_pool>(sz, sz_sub, max_allocs)}{} Pmr_pool::Resource_ptr Pmr_pool::get_resource() { return impl->get_resource(); } std::size_t Pmr_pool::resource_count() { return impl->resource_count(); } std::size_t Pmr_pool::alloc_count() { return impl->alloc_count(); } std::size_t Pmr_pool::dealloc_count() { return impl->dealloc_count(); } void Pmr_pool::return_resource(Resource* res) { impl->return_resource(res); } bool Pmr_pool::full() { return impl->full(); } bool Pmr_pool::empty() { return impl->empty(); } // // Pmr_resource implementation // Pmr_resource::Pmr_resource(Pool_ptr p) : pool_{p} {} std::size_t Pmr_resource::capacity() { return pool_->resource_capacity(); } std::size_t Pmr_resource::allocatable() { auto cap = capacity(); if (used > cap) return 0; return cap - used; } std::size_t Pmr_resource::allocated() { return used; } Pmr_resource::Pool_ptr Pmr_resource::pool() { return pool_; } void* Pmr_resource::do_allocate(std::size_t size, std::size_t align) { auto cap = capacity(); if (UNLIKELY(size + used > cap)) { throw std::bad_alloc(); } void* buf = pool_->allocate(size, align); used += size; allocs++; return buf; } void Pmr_resource::do_deallocate(void* ptr, std::size_t s, std::size_t a) { Expects(s != 0); // POSIX malloc will allow size 0, but return nullptr. bool trigger_non_full = UNLIKELY(full() and non_full != nullptr); bool trigger_avail_thresh = UNLIKELY(allocatable() < avail_thresh and allocatable() + s >= avail_thresh and avail != nullptr); pool_->deallocate(ptr,s,a); deallocs++; used -= s; if (UNLIKELY(trigger_avail_thresh)) { Ensures(allocatable() >= avail_thresh); Ensures(avail != nullptr); avail(*this); } if (UNLIKELY(trigger_non_full)) { Ensures(!full()); Ensures(non_full != nullptr); non_full(*this); } } bool Pmr_resource::do_is_equal(const std::pmr::memory_resource& other) const noexcept { if (const auto* other_ptr = dynamic_cast<const Pmr_resource*>(&other)) { return this == other_ptr; } return false; } bool Pmr_resource::full() { return used >= capacity(); } bool Pmr_resource::empty() { return used == 0; } } #endif
{ "content_hash": "f69dc299804e66653673c125cf5260bb", "timestamp": "", "source": "github", "line_count": 298, "max_line_length": 107, "avg_line_length": 26.71812080536913, "alnum_prop": 0.5810097965335342, "repo_name": "hioa-cs/IncludeOS", "id": "b8ca3032267462a46ff135a48d9f3686fab5318d", "size": "8106", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "api/util/detail/alloc_pmr.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "62723" }, { "name": "C", "bytes": "49793" }, { "name": "C++", "bytes": "3228612" }, { "name": "CMake", "bytes": "139023" }, { "name": "Dockerfile", "bytes": "3694" }, { "name": "GDB", "bytes": "255" }, { "name": "JavaScript", "bytes": "1956" }, { "name": "Makefile", "bytes": "1719" }, { "name": "Python", "bytes": "159923" }, { "name": "Shell", "bytes": "87390" } ], "symlink_target": "" }
3.0.5 / 2012-12-19 ================== * add throwing when a non-function is passed to a route * fix: explicitly remove Transfer-Encoding header from 204 and 304 responses * revert "add 'etag' option" 3.0.4 / 2012-12-05 ================== * add 'etag' option to disable `res.send()` Etags * add escaping of urls in text/plain in `res.redirect()` for old browsers interpreting as html * change crc32 module for a more liberal license * update connect 3.0.3 / 2012-11-13 ================== * update connect * update cookie module * fix cookie max-age 3.0.2 / 2012-11-08 ================== * add OPTIONS to cors example. Closes #1398 * fix route chaining regression. Closes #1397 3.0.1 / 2012-11-01 ================== * update connect 3.0.0 / 2012-10-23 ================== * add `make clean` * add "Basic" check to req.auth * add `req.auth` test coverage * add cb && cb(payload) to `res.jsonp()`. Closes #1374 * add backwards compat for `res.redirect()` status. Closes #1336 * add support for `res.json()` to retain previously defined Content-Types. Closes #1349 * update connect * change `res.redirect()` to utilize a pathname-relative Location again. Closes #1382 * remove non-primitive string support for `res.send()` * fix view-locals example. Closes #1370 * fix route-separation example 3.0.0rc5 / 2012-09-18 ================== * update connect * add redis search example * add static-files example * add "x-powered-by" setting (`app.disable('x-powered-by')`) * add "application/octet-stream" redirect Accept test case. Closes #1317 3.0.0rc4 / 2012-08-30 ================== * add `res.jsonp()`. Closes #1307 * add "verbose errors" option to error-pages example * add another route example to express(1) so people are not so confused * add redis online user activity tracking example * update connect dep * fix etag quoting. Closes #1310 * fix error-pages 404 status * fix jsonp callback char restrictions * remove old OPTIONS default response 3.0.0rc3 / 2012-08-13 ================== * update connect dep * fix signed cookies to work with `connect.cookieParser()` ("s:" prefix was missing) [tnydwrds] * fix `res.render()` clobbering of "locals" 3.0.0rc2 / 2012-08-03 ================== * add CORS example * update connect dep * deprecate `.createServer()` & remove old stale examples * fix: escape `res.redirect()` link * fix vhost example 3.0.0rc1 / 2012-07-24 ================== * add more examples to view-locals * add scheme-relative redirects (`res.redirect("//foo.com")`) support * update cookie dep * update connect dep * update send dep * fix `express(1)` -h flag, use -H for hogan. Closes #1245 * fix `res.sendfile()` socket error handling regression 3.0.0beta7 / 2012-07-16 ================== * update connect dep for `send()` root normalization regression 3.0.0beta6 / 2012-07-13 ================== * add `err.view` property for view errors. Closes #1226 * add "jsonp callback name" setting * add support for "/foo/:bar*" non-greedy matches * change `res.sendfile()` to use `send()` module * change `res.send` to use "response-send" module * remove `app.locals.use` and `res.locals.use`, use regular middleware 3.0.0beta5 / 2012-07-03 ================== * add "make check" support * add route-map example * add `res.json(obj, status)` support back for BC * add "methods" dep, remove internal methods module * update connect dep * update auth example to utilize cores pbkdf2 * updated tests to use "supertest" 3.0.0beta4 / 2012-06-25 ================== * Added `req.auth` * Added `req.range(size)` * Added `res.links(obj)` * Added `res.send(body, status)` support back for backwards compat * Added `.default()` support to `res.format()` * Added 2xx / 304 check to `req.fresh` * Revert "Added + support to the router" * Fixed `res.send()` freshness check, respect res.statusCode 3.0.0beta3 / 2012-06-15 ================== * Added hogan `--hjs` to express(1) [nullfirm] * Added another example to content-negotiation * Added `fresh` dep * Changed: `res.send()` always checks freshness * Fixed: expose connects mime module. Cloases #1165 3.0.0beta2 / 2012-06-06 ================== * Added `+` support to the router * Added `req.host` * Changed `req.param()` to check route first * Update connect dep 3.0.0beta1 / 2012-06-01 ================== * Added `res.format()` callback to override default 406 behaviour * Fixed `res.redirect()` 406. Closes #1154 3.0.0alpha5 / 2012-05-30 ================== * Added `req.ip` * Added `{ signed: true }` option to `res.cookie()` * Removed `res.signedCookie()` * Changed: dont reverse `req.ips` * Fixed "trust proxy" setting check for `req.ips` 3.0.0alpha4 / 2012-05-09 ================== * Added: allow `[]` in jsonp callback. Closes #1128 * Added `PORT` env var support in generated template. Closes #1118 [benatkin] * Updated: connect 2.2.2 3.0.0alpha3 / 2012-05-04 ================== * Added public `app.routes`. Closes #887 * Added _view-locals_ example * Added _mvc_ example * Added `res.locals.use()`. Closes #1120 * Added conditional-GET support to `res.send()` * Added: coerce `res.set()` values to strings * Changed: moved `static()` in generated apps below router * Changed: `res.send()` only set ETag when not previously set * Changed connect 2.2.1 dep * Changed: `make test` now runs unit / acceptance tests * Fixed req/res proto inheritance 3.0.0alpha2 / 2012-04-26 ================== * Added `make benchmark` back * Added `res.send()` support for `String` objects * Added client-side data exposing example * Added `res.header()` and `req.header()` aliases for BC * Added `express.createServer()` for BC * Perf: memoize parsed urls * Perf: connect 2.2.0 dep * Changed: make `expressInit()` middleware self-aware * Fixed: use app.get() for all core settings * Fixed redis session example * Fixed session example. Closes #1105 * Fixed generated express dep. Closes #1078 3.0.0alpha1 / 2012-04-15 ================== * Added `app.locals.use(callback)` * Added `app.locals` object * Added `app.locals(obj)` * Added `res.locals` object * Added `res.locals(obj)` * Added `res.format()` for content-negotiation * Added `app.engine()` * Added `res.cookie()` JSON cookie support * Added "trust proxy" setting * Added `req.subdomains` * Added `req.protocol` * Added `req.secure` * Added `req.path` * Added `req.ips` * Added `req.fresh` * Added `req.stale` * Added comma-delmited / array support for `req.accepts()` * Added debug instrumentation * Added `res.set(obj)` * Added `res.set(field, value)` * Added `res.get(field)` * Added `app.get(setting)`. Closes #842 * Added `req.acceptsLanguage()` * Added `req.acceptsCharset()` * Added `req.accepted` * Added `req.acceptedLanguages` * Added `req.acceptedCharsets` * Added "json replacer" setting * Added "json spaces" setting * Added X-Forwarded-Proto support to `res.redirect()`. Closes #92 * Added `--less` support to express(1) * Added `express.response` prototype * Added `express.request` prototype * Added `express.application` prototype * Added `app.path()` * Added `app.render()` * Added `res.type()` to replace `res.contentType()` * Changed: `res.redirect()` to add relative support * Changed: enable "jsonp callback" by default * Changed: renamed "case sensitive routes" to "case sensitive routing" * Rewrite of all tests with mocha * Removed "root" setting * Removed `res.redirect('home')` support * Removed `req.notify()` * Removed `app.register()` * Removed `app.redirect()` * Removed `app.is()` * Removed `app.helpers()` * Removed `app.dynamicHelpers()` * Fixed `res.sendfile()` with non-GET. Closes #723 * Fixed express(1) public dir for windows. Closes #866 2.5.9/ 2012-04-02 ================== * Added support for PURGE request method [pbuyle] * Fixed `express(1)` generated app `app.address()` before `listening` [mmalecki] 2.5.8 / 2012-02-08 ================== * Update mkdirp dep. Closes #991 2.5.7 / 2012-02-06 ================== * Fixed `app.all` duplicate DELETE requests [mscdex] 2.5.6 / 2012-01-13 ================== * Updated hamljs dev dep. Closes #953 2.5.5 / 2012-01-08 ================== * Fixed: set `filename` on cached templates [matthewleon] 2.5.4 / 2012-01-02 ================== * Fixed `express(1)` eol on 0.4.x. Closes #947 2.5.3 / 2011-12-30 ================== * Fixed `req.is()` when a charset is present 2.5.2 / 2011-12-10 ================== * Fixed: express(1) LF -> CRLF for windows 2.5.1 / 2011-11-17 ================== * Changed: updated connect to 1.8.x * Removed sass.js support from express(1) 2.5.0 / 2011-10-24 ================== * Added ./routes dir for generated app by default * Added npm install reminder to express(1) app gen * Added 0.5.x support * Removed `make test-cov` since it wont work with node 0.5.x * Fixed express(1) public dir for windows. Closes #866 2.4.7 / 2011-10-05 ================== * Added mkdirp to express(1). Closes #795 * Added simple _json-config_ example * Added shorthand for the parsed request's pathname via `req.path` * Changed connect dep to 1.7.x to fix npm issue... * Fixed `res.redirect()` __HEAD__ support. [reported by xerox] * Fixed `req.flash()`, only escape args * Fixed absolute path checking on windows. Closes #829 [reported by andrewpmckenzie] 2.4.6 / 2011-08-22 ================== * Fixed multiple param callback regression. Closes #824 [reported by TroyGoode] 2.4.5 / 2011-08-19 ================== * Added support for routes to handle errors. Closes #809 * Added `app.routes.all()`. Closes #803 * Added "basepath" setting to work in conjunction with reverse proxies etc. * Refactored `Route` to use a single array of callbacks * Added support for multiple callbacks for `app.param()`. Closes #801 Closes #805 * Changed: removed .call(self) for route callbacks * Dependency: `qs >= 0.3.1` * Fixed `res.redirect()` on windows due to `join()` usage. Closes #808 2.4.4 / 2011-08-05 ================== * Fixed `res.header()` intention of a set, even when `undefined` * Fixed `*`, value no longer required * Fixed `res.send(204)` support. Closes #771 2.4.3 / 2011-07-14 ================== * Added docs for `status` option special-case. Closes #739 * Fixed `options.filename`, exposing the view path to template engines 2.4.2. / 2011-07-06 ================== * Revert "removed jsonp stripping" for XSS 2.4.1 / 2011-07-06 ================== * Added `res.json()` JSONP support. Closes #737 * Added _extending-templates_ example. Closes #730 * Added "strict routing" setting for trailing slashes * Added support for multiple envs in `app.configure()` calls. Closes #735 * Changed: `res.send()` using `res.json()` * Changed: when cookie `path === null` don't default it * Changed; default cookie path to "home" setting. Closes #731 * Removed _pids/logs_ creation from express(1) 2.4.0 / 2011-06-28 ================== * Added chainable `res.status(code)` * Added `res.json()`, an explicit version of `res.send(obj)` * Added simple web-service example 2.3.12 / 2011-06-22 ================== * \#express is now on freenode! come join! * Added `req.get(field, param)` * Added links to Japanese documentation, thanks @hideyukisaito! * Added; the `express(1)` generated app outputs the env * Added `content-negotiation` example * Dependency: connect >= 1.5.1 < 2.0.0 * Fixed view layout bug. Closes #720 * Fixed; ignore body on 304. Closes #701 2.3.11 / 2011-06-04 ================== * Added `npm test` * Removed generation of dummy test file from `express(1)` * Fixed; `express(1)` adds express as a dep * Fixed; prune on `prepublish` 2.3.10 / 2011-05-27 ================== * Added `req.route`, exposing the current route * Added _package.json_ generation support to `express(1)` * Fixed call to `app.param()` function for optional params. Closes #682 2.3.9 / 2011-05-25 ================== * Fixed bug-ish with `../' in `res.partial()` calls 2.3.8 / 2011-05-24 ================== * Fixed `app.options()` 2.3.7 / 2011-05-23 ================== * Added route `Collection`, ex: `app.get('/user/:id').remove();` * Added support for `app.param(fn)` to define param logic * Removed `app.param()` support for callback with return value * Removed module.parent check from express(1) generated app. Closes #670 * Refactored router. Closes #639 2.3.6 / 2011-05-20 ================== * Changed; using devDependencies instead of git submodules * Fixed redis session example * Fixed markdown example * Fixed view caching, should not be enabled in development 2.3.5 / 2011-05-20 ================== * Added export `.view` as alias for `.View` 2.3.4 / 2011-05-08 ================== * Added `./examples/say` * Fixed `res.sendfile()` bug preventing the transfer of files with spaces 2.3.3 / 2011-05-03 ================== * Added "case sensitive routes" option. * Changed; split methods supported per rfc [slaskis] * Fixed route-specific middleware when using the same callback function several times 2.3.2 / 2011-04-27 ================== * Fixed view hints 2.3.1 / 2011-04-26 ================== * Added `app.match()` as `app.match.all()` * Added `app.lookup()` as `app.lookup.all()` * Added `app.remove()` for `app.remove.all()` * Added `app.remove.VERB()` * Fixed template caching collision issue. Closes #644 * Moved router over from connect and started refactor 2.3.0 / 2011-04-25 ================== * Added options support to `res.clearCookie()` * Added `res.helpers()` as alias of `res.locals()` * Added; json defaults to UTF-8 with `res.send()`. Closes #632. [Daniel * Dependency `connect >= 1.4.0` * Changed; auto set Content-Type in res.attachement [Aaron Heckmann] * Renamed "cache views" to "view cache". Closes #628 * Fixed caching of views when using several apps. Closes #637 * Fixed gotcha invoking `app.param()` callbacks once per route middleware. Closes #638 * Fixed partial lookup precedence. Closes #631 Shaw] 2.2.2 / 2011-04-12 ================== * Added second callback support for `res.download()` connection errors * Fixed `filename` option passing to template engine 2.2.1 / 2011-04-04 ================== * Added `layout(path)` helper to change the layout within a view. Closes #610 * Fixed `partial()` collection object support. Previously only anything with `.length` would work. When `.length` is present one must still be aware of holes, however now `{ collection: {foo: 'bar'}}` is valid, exposes `keyInCollection` and `keysInCollection`. * Performance improved with better view caching * Removed `request` and `response` locals * Changed; errorHandler page title is now `Express` instead of `Connect` 2.2.0 / 2011-03-30 ================== * Added `app.lookup.VERB()`, ex `app.lookup.put('/user/:id')`. Closes #606 * Added `app.match.VERB()`, ex `app.match.put('/user/12')`. Closes #606 * Added `app.VERB(path)` as alias of `app.lookup.VERB()`. * Dependency `connect >= 1.2.0` 2.1.1 / 2011-03-29 ================== * Added; expose `err.view` object when failing to locate a view * Fixed `res.partial()` call `next(err)` when no callback is given [reported by aheckmann] * Fixed; `res.send(undefined)` responds with 204 [aheckmann] 2.1.0 / 2011-03-24 ================== * Added `<root>/_?<name>` partial lookup support. Closes #447 * Added `request`, `response`, and `app` local variables * Added `settings` local variable, containing the app's settings * Added `req.flash()` exception if `req.session` is not available * Added `res.send(bool)` support (json response) * Fixed stylus example for latest version * Fixed; wrap try/catch around `res.render()` 2.0.0 / 2011-03-17 ================== * Fixed up index view path alternative. * Changed; `res.locals()` without object returns the locals 2.0.0rc3 / 2011-03-17 ================== * Added `res.locals(obj)` to compliment `res.local(key, val)` * Added `res.partial()` callback support * Fixed recursive error reporting issue in `res.render()` 2.0.0rc2 / 2011-03-17 ================== * Changed; `partial()` "locals" are now optional * Fixed `SlowBuffer` support. Closes #584 [reported by tyrda01] * Fixed .filename view engine option [reported by drudge] * Fixed blog example * Fixed `{req,res}.app` reference when mounting [Ben Weaver] 2.0.0rc / 2011-03-14 ================== * Fixed; expose `HTTPSServer` constructor * Fixed express(1) default test charset. Closes #579 [reported by secoif] * Fixed; default charset to utf-8 instead of utf8 for lame IE [reported by NickP] 2.0.0beta3 / 2011-03-09 ================== * Added support for `res.contentType()` literal The original `res.contentType('.json')`, `res.contentType('application/json')`, and `res.contentType('json')` will work now. * Added `res.render()` status option support back * Added charset option for `res.render()` * Added `.charset` support (via connect 1.0.4) * Added view resolution hints when in development and a lookup fails * Added layout lookup support relative to the page view. For example while rendering `./views/user/index.jade` if you create `./views/user/layout.jade` it will be used in favour of the root layout. * Fixed `res.redirect()`. RFC states absolute url [reported by unlink] * Fixed; default `res.send()` string charset to utf8 * Removed `Partial` constructor (not currently used) 2.0.0beta2 / 2011-03-07 ================== * Added res.render() `.locals` support back to aid in migration process * Fixed flash example 2.0.0beta / 2011-03-03 ================== * Added HTTPS support * Added `res.cookie()` maxAge support * Added `req.header()` _Referrer_ / _Referer_ special-case, either works * Added mount support for `res.redirect()`, now respects the mount-point * Added `union()` util, taking place of `merge(clone())` combo * Added stylus support to express(1) generated app * Added secret to session middleware used in examples and generated app * Added `res.local(name, val)` for progressive view locals * Added default param support to `req.param(name, default)` * Added `app.disabled()` and `app.enabled()` * Added `app.register()` support for omitting leading ".", either works * Added `res.partial()`, using the same interface as `partial()` within a view. Closes #539 * Added `app.param()` to map route params to async/sync logic * Added; aliased `app.helpers()` as `app.locals()`. Closes #481 * Added extname with no leading "." support to `res.contentType()` * Added `cache views` setting, defaulting to enabled in "production" env * Added index file partial resolution, eg: partial('user') may try _views/user/index.jade_. * Added `req.accepts()` support for extensions * Changed; `res.download()` and `res.sendfile()` now utilize Connect's static file server `connect.static.send()`. * Changed; replaced `connect.utils.mime()` with npm _mime_ module * Changed; allow `req.query` to be pre-defined (via middleware or other parent * Changed view partial resolution, now relative to parent view * Changed view engine signature. no longer `engine.render(str, options, callback)`, now `engine.compile(str, options) -> Function`, the returned function accepts `fn(locals)`. * Fixed `req.param()` bug returning Array.prototype methods. Closes #552 * Fixed; using `Stream#pipe()` instead of `sys.pump()` in `res.sendfile()` * Fixed; using _qs_ module instead of _querystring_ * Fixed; strip unsafe chars from jsonp callbacks * Removed "stream threshold" setting 1.0.8 / 2011-03-01 ================== * Allow `req.query` to be pre-defined (via middleware or other parent app) * "connect": ">= 0.5.0 < 1.0.0". Closes #547 * Removed the long deprecated __EXPRESS_ENV__ support 1.0.7 / 2011-02-07 ================== * Fixed `render()` setting inheritance. Mounted apps would not inherit "view engine" 1.0.6 / 2011-02-07 ================== * Fixed `view engine` setting bug when period is in dirname 1.0.5 / 2011-02-05 ================== * Added secret to generated app `session()` call 1.0.4 / 2011-02-05 ================== * Added `qs` dependency to _package.json_ * Fixed namespaced `require()`s for latest connect support 1.0.3 / 2011-01-13 ================== * Remove unsafe characters from JSONP callback names [Ryan Grove] 1.0.2 / 2011-01-10 ================== * Removed nested require, using `connect.router` 1.0.1 / 2010-12-29 ================== * Fixed for middleware stacked via `createServer()` previously the `foo` middleware passed to `createServer(foo)` would not have access to Express methods such as `res.send()` or props like `req.query` etc. 1.0.0 / 2010-11-16 ================== * Added; deduce partial object names from the last segment. For example by default `partial('forum/post', postObject)` will give you the _post_ object, providing a meaningful default. * Added http status code string representation to `res.redirect()` body * Added; `res.redirect()` supporting _text/plain_ and _text/html_ via __Accept__. * Added `req.is()` to aid in content negotiation * Added partial local inheritance [suggested by masylum]. Closes #102 providing access to parent template locals. * Added _-s, --session[s]_ flag to express(1) to add session related middleware * Added _--template_ flag to express(1) to specify the template engine to use. * Added _--css_ flag to express(1) to specify the stylesheet engine to use (or just plain css by default). * Added `app.all()` support [thanks aheckmann] * Added partial direct object support. You may now `partial('user', user)` providing the "user" local, vs previously `partial('user', { object: user })`. * Added _route-separation_ example since many people question ways to do this with CommonJS modules. Also view the _blog_ example for an alternative. * Performance; caching view path derived partial object names * Fixed partial local inheritance precedence. [reported by Nick Poulden] Closes #454 * Fixed jsonp support; _text/javascript_ as per mailinglist discussion 1.0.0rc4 / 2010-10-14 ================== * Added _NODE_ENV_ support, _EXPRESS_ENV_ is deprecated and will be removed in 1.0.0 * Added route-middleware support (very helpful, see the [docs](http://expressjs.com/guide.html#Route-Middleware)) * Added _jsonp callback_ setting to enable/disable jsonp autowrapping [Dav Glass] * Added callback query check on response.send to autowrap JSON objects for simple webservice implementations [Dav Glass] * Added `partial()` support for array-like collections. Closes #434 * Added support for swappable querystring parsers * Added session usage docs. Closes #443 * Added dynamic helper caching. Closes #439 [suggested by maritz] * Added authentication example * Added basic Range support to `res.sendfile()` (and `res.download()` etc) * Changed; `express(1)` generated app using 2 spaces instead of 4 * Default env to "development" again [aheckmann] * Removed _context_ option is no more, use "scope" * Fixed; exposing _./support_ libs to examples so they can run without installs * Fixed mvc example 1.0.0rc3 / 2010-09-20 ================== * Added confirmation for `express(1)` app generation. Closes #391 * Added extending of flash formatters via `app.flashFormatters` * Added flash formatter support. Closes #411 * Added streaming support to `res.sendfile()` using `sys.pump()` when >= "stream threshold" * Added _stream threshold_ setting for `res.sendfile()` * Added `res.send()` __HEAD__ support * Added `res.clearCookie()` * Added `res.cookie()` * Added `res.render()` headers option * Added `res.redirect()` response bodies * Added `res.render()` status option support. Closes #425 [thanks aheckmann] * Fixed `res.sendfile()` responding with 403 on malicious path * Fixed `res.download()` bug; when an error occurs remove _Content-Disposition_ * Fixed; mounted apps settings now inherit from parent app [aheckmann] * Fixed; stripping Content-Length / Content-Type when 204 * Fixed `res.send()` 204. Closes #419 * Fixed multiple _Set-Cookie_ headers via `res.header()`. Closes #402 * Fixed bug messing with error handlers when `listenFD()` is called instead of `listen()`. [thanks guillermo] 1.0.0rc2 / 2010-08-17 ================== * Added `app.register()` for template engine mapping. Closes #390 * Added `res.render()` callback support as second argument (no options) * Added callback support to `res.download()` * Added callback support for `res.sendfile()` * Added support for middleware access via `express.middlewareName()` vs `connect.middlewareName()` * Added "partials" setting to docs * Added default expresso tests to `express(1)` generated app. Closes #384 * Fixed `res.sendfile()` error handling, defer via `next()` * Fixed `res.render()` callback when a layout is used [thanks guillermo] * Fixed; `make install` creating ~/.node_libraries when not present * Fixed issue preventing error handlers from being defined anywhere. Closes #387 1.0.0rc / 2010-07-28 ================== * Added mounted hook. Closes #369 * Added connect dependency to _package.json_ * Removed "reload views" setting and support code development env never caches, production always caches. * Removed _param_ in route callbacks, signature is now simply (req, res, next), previously (req, res, params, next). Use _req.params_ for path captures, _req.query_ for GET params. * Fixed "home" setting * Fixed middleware/router precedence issue. Closes #366 * Fixed; _configure()_ callbacks called immediately. Closes #368 1.0.0beta2 / 2010-07-23 ================== * Added more examples * Added; exporting `Server` constructor * Added `Server#helpers()` for view locals * Added `Server#dynamicHelpers()` for dynamic view locals. Closes #349 * Added support for absolute view paths * Added; _home_ setting defaults to `Server#route` for mounted apps. Closes #363 * Added Guillermo Rauch to the contributor list * Added support for "as" for non-collection partials. Closes #341 * Fixed _install.sh_, ensuring _~/.node_libraries_ exists. Closes #362 [thanks jf] * Fixed `res.render()` exceptions, now passed to `next()` when no callback is given [thanks guillermo] * Fixed instanceof `Array` checks, now `Array.isArray()` * Fixed express(1) expansion of public dirs. Closes #348 * Fixed middleware precedence. Closes #345 * Fixed view watcher, now async [thanks aheckmann] 1.0.0beta / 2010-07-15 ================== * Re-write - much faster - much lighter - Check [ExpressJS.com](http://expressjs.com) for migration guide and updated docs 0.14.0 / 2010-06-15 ================== * Utilize relative requires * Added Static bufferSize option [aheckmann] * Fixed caching of view and partial subdirectories [aheckmann] * Fixed mime.type() comments now that ".ext" is not supported * Updated haml submodule * Updated class submodule * Removed bin/express 0.13.0 / 2010-06-01 ================== * Added node v0.1.97 compatibility * Added support for deleting cookies via Request#cookie('key', null) * Updated haml submodule * Fixed not-found page, now using using charset utf-8 * Fixed show-exceptions page, now using using charset utf-8 * Fixed view support due to fs.readFile Buffers * Changed; mime.type() no longer accepts ".type" due to node extname() changes 0.12.0 / 2010-05-22 ================== * Added node v0.1.96 compatibility * Added view `helpers` export which act as additional local variables * Updated haml submodule * Changed ETag; removed inode, modified time only * Fixed LF to CRLF for setting multiple cookies * Fixed cookie complation; values are now urlencoded * Fixed cookies parsing; accepts quoted values and url escaped cookies 0.11.0 / 2010-05-06 ================== * Added support for layouts using different engines - this.render('page.html.haml', { layout: 'super-cool-layout.html.ejs' }) - this.render('page.html.haml', { layout: 'foo' }) // assumes 'foo.html.haml' - this.render('page.html.haml', { layout: false }) // no layout * Updated ext submodule * Updated haml submodule * Fixed EJS partial support by passing along the context. Issue #307 0.10.1 / 2010-05-03 ================== * Fixed binary uploads. 0.10.0 / 2010-04-30 ================== * Added charset support via Request#charset (automatically assigned to 'UTF-8' when respond()'s encoding is set to 'utf8' or 'utf-8'. * Added "encoding" option to Request#render(). Closes #299 * Added "dump exceptions" setting, which is enabled by default. * Added simple ejs template engine support * Added error reponse support for text/plain, application/json. Closes #297 * Added callback function param to Request#error() * Added Request#sendHead() * Added Request#stream() * Added support for Request#respond(304, null) for empty response bodies * Added ETag support to Request#sendfile() * Added options to Request#sendfile(), passed to fs.createReadStream() * Added filename arg to Request#download() * Performance enhanced due to pre-reversing plugins so that plugins.reverse() is not called on each request * Performance enhanced by preventing several calls to toLowerCase() in Router#match() * Changed; Request#sendfile() now streams * Changed; Renamed Request#halt() to Request#respond(). Closes #289 * Changed; Using sys.inspect() instead of JSON.encode() for error output * Changed; run() returns the http.Server instance. Closes #298 * Changed; Defaulting Server#host to null (INADDR_ANY) * Changed; Logger "common" format scale of 0.4f * Removed Logger "request" format * Fixed; Catching ENOENT in view caching, preventing error when "views/partials" is not found * Fixed several issues with http client * Fixed Logger Content-Length output * Fixed bug preventing Opera from retaining the generated session id. Closes #292 0.9.0 / 2010-04-14 ================== * Added DSL level error() route support * Added DSL level notFound() route support * Added Request#error() * Added Request#notFound() * Added Request#render() callback function. Closes #258 * Added "max upload size" setting * Added "magic" variables to collection partials (\_\_index\_\_, \_\_length\_\_, \_\_isFirst\_\_, \_\_isLast\_\_). Closes #254 * Added [haml.js](http://github.com/visionmedia/haml.js) submodule; removed haml-js * Added callback function support to Request#halt() as 3rd/4th arg * Added preprocessing of route param wildcards using param(). Closes #251 * Added view partial support (with collections etc) * Fixed bug preventing falsey params (such as ?page=0). Closes #286 * Fixed setting of multiple cookies. Closes #199 * Changed; view naming convention is now NAME.TYPE.ENGINE (for example page.html.haml) * Changed; session cookie is now httpOnly * Changed; Request is no longer global * Changed; Event is no longer global * Changed; "sys" module is no longer global * Changed; moved Request#download to Static plugin where it belongs * Changed; Request instance created before body parsing. Closes #262 * Changed; Pre-caching views in memory when "cache view contents" is enabled. Closes #253 * Changed; Pre-caching view partials in memory when "cache view partials" is enabled * Updated support to node --version 0.1.90 * Updated dependencies * Removed set("session cookie") in favour of use(Session, { cookie: { ... }}) * Removed utils.mixin(); use Object#mergeDeep() 0.8.0 / 2010-03-19 ================== * Added coffeescript example app. Closes #242 * Changed; cache api now async friendly. Closes #240 * Removed deprecated 'express/static' support. Use 'express/plugins/static' 0.7.6 / 2010-03-19 ================== * Added Request#isXHR. Closes #229 * Added `make install` (for the executable) * Added `express` executable for setting up simple app templates * Added "GET /public/*" to Static plugin, defaulting to <root>/public * Added Static plugin * Fixed; Request#render() only calls cache.get() once * Fixed; Namespacing View caches with "view:" * Fixed; Namespacing Static caches with "static:" * Fixed; Both example apps now use the Static plugin * Fixed set("views"). Closes #239 * Fixed missing space for combined log format * Deprecated Request#sendfile() and 'express/static' * Removed Server#running 0.7.5 / 2010-03-16 ================== * Added Request#flash() support without args, now returns all flashes * Updated ext submodule 0.7.4 / 2010-03-16 ================== * Fixed session reaper * Changed; class.js replacing js-oo Class implementation (quite a bit faster, no browser cruft) 0.7.3 / 2010-03-16 ================== * Added package.json * Fixed requiring of haml / sass due to kiwi removal 0.7.2 / 2010-03-16 ================== * Fixed GIT submodules (HAH!) 0.7.1 / 2010-03-16 ================== * Changed; Express now using submodules again until a PM is adopted * Changed; chat example using millisecond conversions from ext 0.7.0 / 2010-03-15 ================== * Added Request#pass() support (finds the next matching route, or the given path) * Added Logger plugin (default "common" format replaces CommonLogger) * Removed Profiler plugin * Removed CommonLogger plugin 0.6.0 / 2010-03-11 ================== * Added seed.yml for kiwi package management support * Added HTTP client query string support when method is GET. Closes #205 * Added support for arbitrary view engines. For example "foo.engine.html" will now require('engine'), the exports from this module are cached after the first require(). * Added async plugin support * Removed usage of RESTful route funcs as http client get() etc, use http.get() and friends * Removed custom exceptions 0.5.0 / 2010-03-10 ================== * Added ext dependency (library of js extensions) * Removed extname() / basename() utils. Use path module * Removed toArray() util. Use arguments.values * Removed escapeRegexp() util. Use RegExp.escape() * Removed process.mixin() dependency. Use utils.mixin() * Removed Collection * Removed ElementCollection * Shameless self promotion of ebook "Advanced JavaScript" (http://dev-mag.com) ;) 0.4.0 / 2010-02-11 ================== * Added flash() example to sample upload app * Added high level restful http client module (express/http) * Changed; RESTful route functions double as HTTP clients. Closes #69 * Changed; throwing error when routes are added at runtime * Changed; defaulting render() context to the current Request. Closes #197 * Updated haml submodule 0.3.0 / 2010-02-11 ================== * Updated haml / sass submodules. Closes #200 * Added flash message support. Closes #64 * Added accepts() now allows multiple args. fixes #117 * Added support for plugins to halt. Closes #189 * Added alternate layout support. Closes #119 * Removed Route#run(). Closes #188 * Fixed broken specs due to use(Cookie) missing 0.2.1 / 2010-02-05 ================== * Added "plot" format option for Profiler (for gnuplot processing) * Added request number to Profiler plugin * Fixed binary encoding for multi-part file uploads, was previously defaulting to UTF8 * Fixed issue with routes not firing when not files are present. Closes #184 * Fixed process.Promise -> events.Promise 0.2.0 / 2010-02-03 ================== * Added parseParam() support for name[] etc. (allows for file inputs with "multiple" attr) Closes #180 * Added Both Cache and Session option "reapInterval" may be "reapEvery". Closes #174 * Added expiration support to cache api with reaper. Closes #133 * Added cache Store.Memory#reap() * Added Cache; cache api now uses first class Cache instances * Added abstract session Store. Closes #172 * Changed; cache Memory.Store#get() utilizing Collection * Renamed MemoryStore -> Store.Memory * Fixed use() of the same plugin several time will always use latest options. Closes #176 0.1.0 / 2010-02-03 ================== * Changed; Hooks (before / after) pass request as arg as well as evaluated in their context * Updated node support to 0.1.27 Closes #169 * Updated dirname(__filename) -> __dirname * Updated libxmljs support to v0.2.0 * Added session support with memory store / reaping * Added quick uid() helper * Added multi-part upload support * Added Sass.js support / submodule * Added production env caching view contents and static files * Added static file caching. Closes #136 * Added cache plugin with memory stores * Added support to StaticFile so that it works with non-textual files. * Removed dirname() helper * Removed several globals (now their modules must be required) 0.0.2 / 2010-01-10 ================== * Added view benchmarks; currently haml vs ejs * Added Request#attachment() specs. Closes #116 * Added use of node's parseQuery() util. Closes #123 * Added `make init` for submodules * Updated Haml * Updated sample chat app to show messages on load * Updated libxmljs parseString -> parseHtmlString * Fixed `make init` to work with older versions of git * Fixed specs can now run independant specs for those who cant build deps. Closes #127 * Fixed issues introduced by the node url module changes. Closes 126. * Fixed two assertions failing due to Collection#keys() returning strings * Fixed faulty Collection#toArray() spec due to keys() returning strings * Fixed `make test` now builds libxmljs.node before testing 0.0.1 / 2010-01-03 ================== * Initial release
{ "content_hash": "d78d98c1efd44f7d937e0d41240d2628", "timestamp": "", "source": "github", "line_count": 1071, "max_line_length": 177, "avg_line_length": 35.74416433239963, "alnum_prop": 0.6662400083590199, "repo_name": "laugga/memories.laugga.com", "id": "57bf9ade97de6660a729216f231d9be3830b3e5d", "size": "38283", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/node_modules/express/History.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8472" }, { "name": "CoffeeScript", "bytes": "872" }, { "name": "JavaScript", "bytes": "842094" }, { "name": "Shell", "bytes": "1124" } ], "symlink_target": "" }
<?php namespace System\Web\Mvc; class CollectionModelBinderAttribute extends ModelBinder { protected $model; public function __construct($paramName, $model){ $this->paramName = $paramName; $this->model = $model; } public function bind(\System\Web\Mvc\ModelBindingContext $modelBindingContext){ $collection = \System\Std\Obj::toObject($modelBindingContext->getObjectName(), array()); $post = $modelBindingContext->getRequest()->getPost()->toArray(); $tmp = array(); foreach($post as $key => $array){ if(is_array($array)){ if(strpos($key, '->') > -1){ list($object, $field) = explode('->', $key, 2); if($object == $this->paramName){ $key = $field; } } foreach($array as $idx=> $value){ $tmp[$idx][$key] = $value; } } } foreach($tmp as $item){ $collection->add(\System\Std\Obj::toObject($this->model, $item)); } return $collection; } }
{ "content_hash": "bbd9963c08c8fc81ab3fc40ca5c16e32", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 96, "avg_line_length": 31.473684210526315, "alnum_prop": 0.4765886287625418, "repo_name": "mercuryphp/framework", "id": "abc339c2adb03a9d0772c915b74f8e11e1b930c1", "size": "1196", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "System/Web/Mvc/CollectionModelBinderAttribute.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "285175" } ], "symlink_target": "" }
from .random_article import *
{ "content_hash": "244e0d34c4dca3823be76a359265952b", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 29, "avg_line_length": 30, "alnum_prop": 0.7666666666666667, "repo_name": "Naereen/cuisine", "id": "b59a6a03a193acf519225f4f9771ddd002d994fb", "size": "30", "binary": false, "copies": "78", "ref": "refs/heads/master", "path": "plugins/random_article/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "108439" }, { "name": "HTML", "bytes": "16416" }, { "name": "Makefile", "bytes": "4071" }, { "name": "Python", "bytes": "111371" }, { "name": "Shell", "bytes": "2537" } ], "symlink_target": "" }
% This file is part of AceRules. % Copyright 2008-2012, Tobias Kuhn, http://www.tkuhn.ch % % AceRules is free software: you can redistribute it and/or modify it under the terms of the GNU % Lesser General Public License as published by the Free Software Foundation, either version 3 of % the License, or (at your option) any later version. % % AceRules is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even % the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser % General Public License for more details. % % You should have received a copy of the GNU Lesser General Public License along with AceRules. If % not, see http://www.gnu.org/licenses/. :- module(meta_preprocess, [ meta_preprocess/4 % +Codes, -Text, -LabelMap, -Overrides ]). :- use_module(ape('parser/tokenizer')). :- use_module(ape('logger/error_logger')). :- use_module('../utils'). :- use_module('../list_utils'). /** <module> Meta preprocessor Processes the meta-structures of a rule definition, i.e. labels and overrides-statements. @author Tobias Kuhn @version 2007-02-07 */ %% meta_preprocess(+Codes, -PlainText, -LabelMap, -Overrides) % % Splits the input text (Codes) into a map of labels (LabelMap maps labels to sentence numbers), % a set of override-statements (Overrides), and the remaining text (PlainText). meta_preprocess(Codes, PlainText, [0-''|LabelMap], Overrides) :- clear_messages, tokenize(Codes, Tokens), !, (Tokens = [] -> throw(ar_error('parser.meta-preprocess.EmptyProgram', 'The program is empty.')) ; true ), split(Tokens, SentenceLists), extract_meta_info(SentenceLists, 1, PlainSentences, LabelMap, Overrides), check_overrides(Overrides, LabelMap), concat_tokens(PlainSentences, PlainText), !. %% split(+Tokens, -SentenceLists) % % Splits a list of tokens (Tokens) into a list of sentences (SentenceLists) % where each sentence itself is represented as a list of tokens. split([], []). split(Tokens, Sentences) :- get_sentence(Tokens, [], Sentence, RestTokens), split(RestTokens, RestSentences), add_sentence(Sentence, RestSentences, Sentences). add_sentence([], Sentences, Sentences) :- !. add_sentence(Sentence, Sentences, [Sentence|Sentences]). %% get_sentence(+Tokens, +AccTokens, -Sentence, -RestTokens) % % Returns the tokens from the beginning of the list Tokens upto the first % occurence of a full stop '.'. This is stored in Sentence. AccTokens contains % the accumulated tokens that are already processed. RestTokens returns the rest % of the tokens that are beyond the first full stop. get_sentence(['<p>'|RestTokens], Sentence, Sentence, RestTokens) :- !. get_sentence(['.'|RestTokens], AccSentence, Sentence, RestTokens) :- !, append(AccSentence, ['.'], Sentence). get_sentence(['?'|_], AccSentence, _, _) :- concat_tokens(AccSentence, AccSentenceAtom), concat_list(['Queries are not allowed: "', AccSentenceAtom, '?"'], ErrorMessage), throw(ar_error('parser.meta-preprocess.ContainsQuery', ErrorMessage)). get_sentence([T|RestTokens1], AccSentence1, Sentence, RestTokens2) :- append(AccSentence1, [T], AccSentence2), get_sentence(RestTokens1, AccSentence2, Sentence, RestTokens2). get_sentence([], _, _, _) :- throw(ar_error('parser.meta-preprocess.NoFullStopAtEnd', 'The program must end with a full stop.')). %% extract_meta_info(+SentLists, +StartNumber, -PlainSent, -LabelMap, -Overrides) % % extract_meta_info([], _, [], [], []). extract_meta_info(SentLists, N, [PlainSentAtom|PlainSentRest], [N-Label|LabelMapRest], Overrides) :- SentLists = [[Label, ':'|PlainSentTokens]|SentListsRest], valid_label(Label), !, concat_tokens(PlainSentTokens, PlainSentAtom), NP is N + 1, extract_meta_info(SentListsRest, NP, PlainSentRest, LabelMapRest, Overrides). extract_meta_info(SentLists, N, PlainSent, LabelMap, Overrides) :- SentLists = [[Label1, 'overrides', Label2, '.']|SentListsRest], !, Overrides = [overrides(Label1, Label2)|OverridesRest], extract_meta_info(SentListsRest, N, PlainSent, LabelMap, OverridesRest). extract_meta_info(SentLists, N, [PlainSentAtom|PlainSentRest], [N-''|LabelMapRest], Overrides) :- SentLists = [PlainSentTokens|SentListsRest], concat_tokens(PlainSentTokens, PlainSentAtom), NP is N + 1, extract_meta_info(SentListsRest, NP, PlainSentRest, LabelMapRest, Overrides). check_overrides([], _). check_overrides([overrides(Label1, Label2)|Rest], LabelMap) :- (\+ member(_-Label1, LabelMap) -> concat_list(['The label "', Label1, '" does not exist.'], Message), throw(ar_error('parser.meta-preprocess.InexistentLabel', Message)) ; true ), (\+ member(_-Label2, LabelMap) -> concat_list(['The label "', Label2, '" does not exist.'], Message), throw(ar_error('parser.meta-preprocess.InexistentLabel', Message)) ; true ), !, check_overrides(Rest, LabelMap). valid_label(Label) :- atom_codes(Label, [First|_]), First >= 65, % "A" First =< 90. % "Z"
{ "content_hash": "4175dd25c7587c981288d96dac82d49e", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 104, "avg_line_length": 33.758389261744966, "alnum_prop": 0.7073558648111332, "repo_name": "TeamSPoon/logicmoo_workspace", "id": "523fd2393b37da1ae0a265b7fde8fc1431569203", "size": "5030", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "packs_sys/logicmoo_nlu/ext/AceRules/engine/parser/meta_preprocess.pl", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "342" }, { "name": "C", "bytes": "1" }, { "name": "C++", "bytes": "1" }, { "name": "CSS", "bytes": "126627" }, { "name": "HTML", "bytes": "839172" }, { "name": "Java", "bytes": "11116" }, { "name": "JavaScript", "bytes": "238700" }, { "name": "PHP", "bytes": "42253" }, { "name": "Perl 6", "bytes": "23" }, { "name": "Prolog", "bytes": "440882" }, { "name": "PureBasic", "bytes": "1334" }, { "name": "Rich Text Format", "bytes": "3436542" }, { "name": "Roff", "bytes": "42" }, { "name": "Shell", "bytes": "61603" }, { "name": "TeX", "bytes": "99504" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Text; using System.Web; namespace StravaConnector { /// <summary> /// Represents a Strava segment. /// </summary> public sealed class Segment { /// <summary> /// Represents climb category type. /// <para> /// See https://strava.zendesk.com/entries/20945952-what-are-segments for details. /// </para> /// </summary> public enum ClimbCategoryType { /// <summary> /// No climb category. /// </summary> NoCategory, /// <summary> /// The hardest category, beyond categorization. /// </summary> CategoryHc, /// <summary> /// Second hardest category. /// </summary> Category1, /// <summary> /// Third hardest category. /// </summary> Category2, /// <summary> /// Fourth hardest category. /// </summary> Category3, /// <summary> /// Easiest category. /// </summary> Category4 } /// <summary> /// Maximum number of search results that can be retrieved in one request. /// </summary> private const int ResultCount = 50; #region Properties /// <summary> /// The id of the Segment. /// </summary> public long Id { get; private set;} /// <summary> /// The name of the Segment. /// </summary> public string Name { get; private set;} /// <summary> /// Length of the Segment, in meters. /// </summary> public double Distance { get; private set;} /// <summary> /// Elevation gain of the Segment, in meters. /// </summary> public double ElevationGain { get; private set;} /// <summary> /// Highest point of the Segment, in meters. /// </summary> public double ElevationHigh { get; private set;} /// <summary> /// Lowest point of the Segment, in meters. /// </summary> public double ElevationLow { get; private set;} /// <summary> /// Average gradient of the Segment. /// TODO: determine unit! /// </summary> public double AverageGradient { get; private set;} /// <summary> /// The climb category of the Segment. /// </summary> public ClimbCategoryType ClimbCategory { get; private set; } #endregion /// <summary> /// Creates a new Segment from a dynamic. /// </summary> /// <param name="stravaSegment"></param> internal Segment(dynamic stravaSegment) { Id = stravaSegment.id; Name = stravaSegment.name; Distance = (double)stravaSegment.distance; ElevationGain = (double)stravaSegment.elevationGain; ElevationHigh = (double)stravaSegment.elevationHigh; ElevationLow = (double)stravaSegment.elevationLow; AverageGradient = (double)stravaSegment.averageGrade; ClimbCategory = ToClimbCategory(stravaSegment.climbCategory); } /// <summary> /// Retrieves a Segment by id. /// </summary> /// <param name="id"></param> /// <returns>The Segment.</returns> public static Segment ById(long id) { var stravaSegmentResponse = StravaApi.Call(string.Format("segments/{0}", id)); if (stravaSegmentResponse == null) return null; return new Segment(stravaSegmentResponse.segment); } /// <summary> /// Retrieves SegmentEfforts based on search criteria. /// </summary> /// <param name="offset">Offset in search results.</param> /// <param name="count">Number of results to retrieve.</param> /// <param name="best">Request best efforts per athlete sorted by elapsed time ascending -- may not work as expected due to Strava bugs.</param> /// <param name="athleteId">Athlete id restriction, null for no restriction.</param> /// <param name="athleteName">Athlete name restriction, null for no restriction.</param> /// <param name="startDate">Start date restriction, null for no restriction.</param> /// <param name="endDate">End date restriction, null for no restriction.</param> /// <param name="clubId">Club id restriction, null for no restriction.</param> /// <param name="startId">Request efforts with an Id greater than or equal to the startId.</param> /// <returns>A list of SegmentEffort objects.</returns> public List<SegmentEffort> GetEfforts(long offset, long count, bool best = false, long? athleteId = null, string athleteName = null, DateTime? startDate = null, DateTime? endDate = null, long? clubId = null, long? startId = null) { // build the query var queryBuilder = new StringBuilder(); if (best) queryBuilder.Append("best=true&"); if (athleteId.HasValue) queryBuilder.AppendFormat("athleteId={0}&", athleteId.Value); if (athleteName != null) queryBuilder.AppendFormat("athleteName={0}&", HttpUtility.UrlEncode(athleteName)); if (startDate.HasValue) queryBuilder.AppendFormat("startDate={0}&", startDate.Value.ToString("yyyy'-'MM'-'dd")); if (endDate.HasValue) queryBuilder.AppendFormat("endDate={0}&", endDate.Value.ToString("yyyy'-'MM'-'dd")); if (clubId.HasValue) queryBuilder.AppendFormat("clubId={0}&", clubId.Value); if (startId.HasValue) queryBuilder.AppendFormat("startId={0}&", startId.Value); var restriction = queryBuilder.ToString(); var results = new List<SegmentEffort>(); var tempOffset = offset; while (count > 0) { var stravaSegmentEffortSearchResponse = StravaApi.Call(string.Format("segments/{0}/efforts?{1}offset={2}", Id, restriction, tempOffset)); if (stravaSegmentEffortSearchResponse == null) return results; foreach (var stravaSegmentEffort in stravaSegmentEffortSearchResponse.efforts) { var segmentEffort = new SegmentEffort(stravaSegmentEffort, Id); results.Add(segmentEffort); count--; if (count == 0) break; } if (stravaSegmentEffortSearchResponse.efforts.Count < ResultCount) break; tempOffset += ResultCount; } return results; } /// <summary> /// Maps a string to a ClimbCategoryType. /// </summary> /// <param name="climbCategory"></param> /// <returns>A ClimbCategoryType.</returns> private static ClimbCategoryType ToClimbCategory(string climbCategory) { switch (climbCategory) { case "HC": return ClimbCategoryType.CategoryHc; case "1": return ClimbCategoryType.Category1; case "2": return ClimbCategoryType.Category2; case "3": return ClimbCategoryType.Category3; case "4": return ClimbCategoryType.Category4; default: // including "NC" return ClimbCategoryType.NoCategory; } } } }
{ "content_hash": "8454a4f0c97a3cccea898bc554da9fe3", "timestamp": "", "source": "github", "line_count": 217, "max_line_length": 231, "avg_line_length": 29.382488479262673, "alnum_prop": 0.6700125470514429, "repo_name": "arthurpitman/strava-connector", "id": "7721c9733b978d0f2d7c8aee23ff91c414fdd3fd", "size": "7000", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Segment.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "41273" } ], "symlink_target": "" }
/* Generated By:JavaCC: Do not edit this line. Token.java Version 6.1 */ /* JavaCCOptions:TOKEN_EXTENDS=,KEEP_LINE_COLUMN=true,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ /* * * This file is part of Java 1.8 parser and Abstract Syntax Tree. * * Java 1.8 parser and Abstract Syntax Tree is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * You should have received a copy of the GNU Lesser General Public License * along with Java 1.8 parser and Abstract Syntax Tree. If not, see <http://www.gnu.org/licenses/>. */ package com.github.javaparser; /** * Describes the input token stream. */ public class Token implements java.io.Serializable { /** * The version identifier for this Serializable class. * Increment only if the <i>serialized</i> form of the * class changes. */ private static final long serialVersionUID = 1L; /** * An integer that describes the kind of this token. This numbering * system is determined by JavaCCParser, and a table of these numbers is * stored in the file ...Constants.java. */ public int kind; /** The line number of the first character of this Token. */ public int beginLine; /** The column number of the first character of this Token. */ public int beginColumn; /** The line number of the last character of this Token. */ public int endLine; /** The column number of the last character of this Token. */ public int endColumn; /** * The string image of the token. */ public String image; /** * A reference to the next regular (non-special) token from the input * stream. If this is the last token from the input stream, or if the * token manager has not read tokens beyond this one, this field is * set to null. This is true only if this token is also a regular * token. Otherwise, see below for a description of the contents of * this field. */ public Token next; /** * This field is used to access special tokens that occur prior to this * token, but after the immediately preceding regular (non-special) token. * If there are no such special tokens, this field is set to null. * When there are more than one such special token, this field refers * to the last of these special tokens, which in turn refers to the next * previous special token through its specialToken field, and so on * until the first special token (whose specialToken field is null). * The next fields of special tokens refer to other special tokens that * immediately follow it (without an intervening regular token). If there * is no such token, this field is null. */ public Token specialToken; /** * An optional attribute value of the Token. * Tokens which are not used as syntactic sugar will often contain * meaningful values that will be used later on by the compiler or * interpreter. This attribute value is often different from the image. * Any subclass of Token that actually wants to return a non-null value can * override this method as appropriate. */ public Object getValue() { return null; } /** * No-argument constructor */ public Token() {} /** * Constructs a new token for the specified Image. */ public Token(int kind) { this(kind, null); } /** * Constructs a new token for the specified Image and Kind. */ public Token(int kind, String image) { this.kind = kind; this.image = image; } /** * Returns the image. */ public String toString() { return image; } /** * Returns a new Token object, by default. However, if you want, you * can create and return subclass objects based on the value of ofKind. * Simply add the cases to the switch for all those special cases. * For example, if you have a subclass of Token called IDToken that * you want to create if ofKind is ID, simply add something like : * * case MyParserConstants.ID : return new IDToken(ofKind, image); * * to the following switch statement. Then you can cast matchedToken * variable to the appropriate type and use sit in your lexical actions. */ public static Token newToken(int ofKind, String image) { switch(ofKind) { default : return new Token(ofKind, image); } } public static Token newToken(int ofKind) { return newToken(ofKind, null); } } /* JavaCC - OriginalChecksum=fd43051db65fcdc22df39a61d81bf7a4 (do not edit this line) */
{ "content_hash": "41a8c9aedd605ead5cd84a571e123011", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 100, "avg_line_length": 32.41958041958042, "alnum_prop": 0.6956427955133736, "repo_name": "xdrop/java-symbol-solver", "id": "2731d04279724c63ddfe42684f9f0c6801ac16b9", "size": "4636", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "java-symbol-solver-core/src/test/resources/javaparser_new_src/javaparser-generated-sources/com/github/javaparser/Token.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "3072729" }, { "name": "Shell", "bytes": "4811" } ], "symlink_target": "" }
module Azure::Web::Mgmt::V2020_09_01 module Models # # Backup description. # class BackupItem < ProxyOnlyResource include MsRestAzure # @return [Integer] Id of the backup. attr_accessor :backup_id # @return [String] SAS URL for the storage account container which # contains this backup. attr_accessor :storage_account_url # @return [String] Name of the blob which contains data for this backup. attr_accessor :blob_name # @return [String] Name of this backup. attr_accessor :backup_item_name # @return [BackupItemStatus] Backup status. Possible values include: # 'InProgress', 'Failed', 'Succeeded', 'TimedOut', 'Created', 'Skipped', # 'PartiallySucceeded', 'DeleteInProgress', 'DeleteFailed', 'Deleted' attr_accessor :status # @return [Integer] Size of the backup in bytes. attr_accessor :size_in_bytes # @return [DateTime] Timestamp of the backup creation. attr_accessor :created # @return [String] Details regarding this backup. Might contain an error # message. attr_accessor :log # @return [Array<DatabaseBackupSetting>] List of databases included in # the backup. attr_accessor :databases # @return [Boolean] True if this backup has been created due to a # schedule being triggered. attr_accessor :scheduled # @return [DateTime] Timestamp of a last restore operation which used # this backup. attr_accessor :last_restore_time_stamp # @return [DateTime] Timestamp when this backup finished. attr_accessor :finished_time_stamp # @return [String] Unique correlation identifier. Please use this along # with the timestamp while communicating with Azure support. attr_accessor :correlation_id # @return [Integer] Size of the original web app which has been backed # up. attr_accessor :website_size_in_bytes # # Mapper for BackupItem class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'BackupItem', type: { name: 'Composite', class_name: 'BackupItem', model_properties: { id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'id', type: { name: 'String' } }, name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'name', type: { name: 'String' } }, kind: { client_side_validation: true, required: false, serialized_name: 'kind', type: { name: 'String' } }, type: { client_side_validation: true, required: false, read_only: true, serialized_name: 'type', type: { name: 'String' } }, system_data: { client_side_validation: true, required: false, serialized_name: 'systemData', type: { name: 'Composite', class_name: 'SystemData' } }, backup_id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.id', type: { name: 'Number' } }, storage_account_url: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.storageAccountUrl', type: { name: 'String' } }, blob_name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.blobName', type: { name: 'String' } }, backup_item_name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.name', type: { name: 'String' } }, status: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.status', type: { name: 'Enum', module: 'BackupItemStatus' } }, size_in_bytes: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.sizeInBytes', type: { name: 'Number' } }, created: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.created', type: { name: 'DateTime' } }, log: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.log', type: { name: 'String' } }, databases: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.databases', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'DatabaseBackupSettingElementType', type: { name: 'Composite', class_name: 'DatabaseBackupSetting' } } } }, scheduled: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.scheduled', type: { name: 'Boolean' } }, last_restore_time_stamp: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.lastRestoreTimeStamp', type: { name: 'DateTime' } }, finished_time_stamp: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.finishedTimeStamp', type: { name: 'DateTime' } }, correlation_id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.correlationId', type: { name: 'String' } }, website_size_in_bytes: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.websiteSizeInBytes', type: { name: 'Number' } } } } } end end end end
{ "content_hash": "67efebf1255956cb44ff5d0a85ee83f0", "timestamp": "", "source": "github", "line_count": 261, "max_line_length": 78, "avg_line_length": 31.704980842911876, "alnum_prop": 0.44157099697885194, "repo_name": "Azure/azure-sdk-for-ruby", "id": "8d411a850dc80a31e5335f24c259f3e818a3c549", "size": "8439", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "management/azure_mgmt_web/lib/2020-09-01/generated/azure_mgmt_web/models/backup_item.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "345216400" }, { "name": "Shell", "bytes": "305" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "4bfb8ac6873fc3818627502285fe058f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "8fccb1ec1e9b2cd8cce53f678f889fbe75eb1bfe", "size": "172", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Bossiaea/Bossiaea rigida/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
Service Directory is a platform for discovering, publishing, and connecting services. It offers customers a single place to register and discover their services in a consistent and reliable way, regardless of their environment. ## Description These samples show how to use the [Service Directory API](https://cloud.google.com/service-directory/) ## Build and Run 1. **Enable API** Enable the Service Directory API on your project 1. **Install and Initialize Cloud SDK** Follow instructions from the available [quickstarts](https://cloud.google.com/sdk/docs/quickstarts) 1. **Clone the repo** ``` $ git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples $ cd ruby-docs-samples/servicedirectory ``` 1. **Install Dependencies** via [Bundler](https://bundler.io/) ``` $ bundle install ``` 1. **Set Environment Variables** ``` $ export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID" ``` 1. **Run Samples** ``` Usage: bundle exec ruby servicedirectory.rb [command] [arguments] Commands: create_namespace <location> <namespace> delete_namespace <location> <namespace> create_service <location> <namespace> <service> delete_service <location> <namespace> <service> create_endpoint <location> <namespace> <service> <endpoint> delete_endpoint <location> <namespace> <service> <endpoint> resolve_service <location> <namespace> <service> Environment variables: GOOGLE_CLOUD_PROJECT must be set to your Google Cloud Project ID ``` ## Contributing Changes * See [CONTRIBUTING.md](https://github.com/GoogleCloudPlatform/ruby-docs-samples/blob/master/CONTRIBUTING.md) ## Licensing * See [LICENSE](https://github.com/GoogleCloudPlatform/ruby-docs-samples/blob/master/LICENSE)
{ "content_hash": "013470c87b6051d2289386253cf1a730", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 106, "avg_line_length": 27.924242424242426, "alnum_prop": 0.6945198046663049, "repo_name": "dazuma/google-cloud-ruby", "id": "5e3abfe6219b1d3d505bbd5d57fc0c45f4f2cef7", "size": "1864", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "google-cloud-service_directory/samples/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "23930" }, { "name": "CSS", "bytes": "1422" }, { "name": "DIGITAL Command Language", "bytes": "2216" }, { "name": "Go", "bytes": "1321" }, { "name": "HTML", "bytes": "66414" }, { "name": "JavaScript", "bytes": "1862" }, { "name": "Ruby", "bytes": "103941624" }, { "name": "Shell", "bytes": "19653" } ], "symlink_target": "" }
/** * */ package com.kushal.factoryMethod; /** * @author kushal * */ public class MD5EncryptorFactory extends AbstractEncryptorFactory { /* * (non-Javadoc) * * @see com.kushal.factoryMethod.AbstractEncryptorFactory#getEncryptionAlgorithm() */ @Override public IEncryptionProduct getEncryptionAlgorithm() { return new MD5HashingAlgo(); } }
{ "content_hash": "d929bf283216d83312e608c1e18eb6c4", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 84, "avg_line_length": 16.90909090909091, "alnum_prop": 0.6989247311827957, "repo_name": "kushal-r/MyWorkspace", "id": "97747edd4aaed4e1b42f42c5a870c695206aee33", "size": "372", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SystemDesign/Patterns/src/com/kushal/factoryMethod/MD5EncryptorFactory.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "335751" }, { "name": "Python", "bytes": "1189" }, { "name": "Vim script", "bytes": "19512" } ], "symlink_target": "" }
package com.google.gerrit.pgm; import static com.google.gerrit.server.schema.DataSourceProvider.Context.MULTI_USER; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.gerrit.common.Die; import com.google.gerrit.lifecycle.LifecycleManager; import com.google.gerrit.lucene.LuceneIndexModule; import com.google.gerrit.pgm.util.BatchProgramModule; import com.google.gerrit.pgm.util.SiteProgram; import com.google.gerrit.pgm.util.ThreadLimiter; import com.google.gerrit.reviewdb.client.Change; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.server.config.GerritServerConfig; import com.google.gerrit.server.git.ScanningChangeCacheImpl; import com.google.gerrit.server.index.ChangeIndex; import com.google.gerrit.server.index.ChangeSchemas; import com.google.gerrit.server.index.IndexCollection; import com.google.gerrit.server.index.IndexModule; import com.google.gerrit.server.index.IndexModule.IndexType; import com.google.gerrit.server.index.SiteIndexer; import com.google.gerrit.solr.SolrIndexModule; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Module; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.ProgressMonitor; import org.eclipse.jgit.lib.TextProgressMonitor; import org.eclipse.jgit.util.io.NullOutputStream; import org.kohsuke.args4j.Option; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; public class Reindex extends SiteProgram { @Option(name = "--threads", usage = "Number of threads to use for indexing") private int threads = Runtime.getRuntime().availableProcessors(); @Option(name = "--schema-version", usage = "Schema version to reindex; default is most recent version") private Integer version; @Option(name = "--output", usage = "Prefix for output; path for local disk index, or prefix for remote index") private String outputBase; @Option(name = "--verbose", usage = "Output debug information for each change") private boolean verbose; @Option(name = "--dry-run", usage = "Dry run: don't write anything to index") private boolean dryRun; private Injector dbInjector; private Injector sysInjector; private Config globalConfig; private ChangeIndex index; @Override public int run() throws Exception { mustHaveValidSite(); dbInjector = createDbInjector(MULTI_USER); globalConfig = dbInjector.getInstance(Key.get(Config.class, GerritServerConfig.class)); threads = ThreadLimiter.limitThreads(dbInjector, threads); checkNotSlaveMode(); disableLuceneAutomaticCommit(); disableChangeCache(); if (version == null) { version = ChangeSchemas.getLatest().getVersion(); } LifecycleManager dbManager = new LifecycleManager(); dbManager.add(dbInjector); dbManager.start(); sysInjector = createSysInjector(); LifecycleManager sysManager = new LifecycleManager(); sysManager.add(sysInjector); sysManager.start(); index = sysInjector.getInstance(IndexCollection.class).getSearchIndex(); int result = 0; try { index.markReady(false); index.deleteAll(); result = indexAll(); index.markReady(true); } catch (Exception e) { throw die(e.getMessage(), e); } sysManager.stop(); dbManager.stop(); return result; } private void checkNotSlaveMode() throws Die { if (globalConfig.getBoolean("container", "slave", false)) { throw die("Cannot run reindex in slave mode"); } } private Injector createSysInjector() { List<Module> modules = Lists.newArrayList(); Module changeIndexModule; switch (IndexModule.getIndexType(dbInjector)) { case LUCENE: changeIndexModule = new LuceneIndexModule(version, threads, outputBase); break; case SOLR: changeIndexModule = new SolrIndexModule(false, threads, outputBase); break; default: throw new IllegalStateException("unsupported index.type"); } modules.add(changeIndexModule); // Scan changes from git instead of relying on the secondary index, as we // will have just deleted the old (possibly corrupt) index. modules.add(ScanningChangeCacheImpl.module()); modules.add(dbInjector.getInstance(BatchProgramModule.class)); return dbInjector.createChildInjector(modules); } private void disableLuceneAutomaticCommit() { if (IndexModule.getIndexType(dbInjector) == IndexType.LUCENE) { globalConfig.setLong("index", "changes_open", "commitWithin", -1); globalConfig.setLong("index", "changes_closed", "commitWithin", -1); } } private void disableChangeCache() { globalConfig.setLong("cache", "changes", "maximumWeight", 0); } private int indexAll() throws Exception { ReviewDb db = sysInjector.getInstance(ReviewDb.class); ProgressMonitor pm = new TextProgressMonitor(); pm.start(1); pm.beginTask("Collecting projects", ProgressMonitor.UNKNOWN); Set<Project.NameKey> projects = Sets.newTreeSet(); int changeCount = 0; try { for (Change change : db.changes().all()) { changeCount++; if (projects.add(change.getProject())) { pm.update(1); } } } finally { db.close(); } pm.endTask(); SiteIndexer batchIndexer = sysInjector.getInstance(SiteIndexer.class); SiteIndexer.Result result = batchIndexer.setNumChanges(changeCount) .setProgressOut(System.err) .setVerboseOut(verbose ? System.out : NullOutputStream.INSTANCE) .indexAll(index, projects); int n = result.doneCount() + result.failedCount(); double t = result.elapsed(TimeUnit.MILLISECONDS) / 1000d; System.out.format("Reindexed %d changes in %.01fs (%.01f/s)\n", n, t, n/t); return result.success() ? 0 : 1; } }
{ "content_hash": "d4f83f163108eb90d493fb9d537276e7", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 112, "avg_line_length": 35.40718562874252, "alnum_prop": 0.7211229494334517, "repo_name": "NextGenIntelligence/gerrit", "id": "44f80f27a1cef366a543e2628bb632fe000f28f2", "size": "6522", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "gerrit-pgm/src/main/java/com/google/gerrit/pgm/Reindex.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "48936" }, { "name": "GAP", "bytes": "4119" }, { "name": "Go", "bytes": "1865" }, { "name": "Groff", "bytes": "28221" }, { "name": "HTML", "bytes": "70171" }, { "name": "Java", "bytes": "8681238" }, { "name": "JavaScript", "bytes": "1590" }, { "name": "Makefile", "bytes": "1313" }, { "name": "PLpgSQL", "bytes": "4462" }, { "name": "Perl", "bytes": "9943" }, { "name": "Prolog", "bytes": "17711" }, { "name": "Python", "bytes": "7074" }, { "name": "Shell", "bytes": "47588" } ], "symlink_target": "" }
package pet // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the generate command import ( "errors" "net/url" golangswaggerpaths "path" "github.com/go-openapi/swag" ) // PetListURL generates an URL for the pet list operation type PetListURL struct { Status []string _basePath string // avoid unkeyed usage _ struct{} } // WithBasePath sets the base path for this url builder, only required when it's different from the // base path specified in the swagger spec. // When the value of the base path is an empty string func (o *PetListURL) WithBasePath(bp string) *PetListURL { o.SetBasePath(bp) return o } // SetBasePath sets the base path for this url builder, only required when it's different from the // base path specified in the swagger spec. // When the value of the base path is an empty string func (o *PetListURL) SetBasePath(bp string) { o._basePath = bp } // Build a url path and query string func (o *PetListURL) Build() (*url.URL, error) { var _result url.URL var _path = "/pet" _basePath := o._basePath if _basePath == "" { _basePath = "/api/v2" } _result.Path = golangswaggerpaths.Join(_basePath, _path) qs := make(url.Values) var statusIR []string for _, statusI := range o.Status { statusIS := statusI if statusIS != "" { statusIR = append(statusIR, statusIS) } } status := swag.JoinByFormat(statusIR, "multi") for _, qsv := range status { qs.Add("status", qsv) } _result.RawQuery = qs.Encode() return &_result, nil } // Must is a helper function to panic when the url builder returns an error func (o *PetListURL) Must(u *url.URL, err error) *url.URL { if err != nil { panic(err) } if u == nil { panic("url can't be nil") } return u } // String returns the string representation of the path with query string func (o *PetListURL) String() string { return o.Must(o.Build()).String() } // BuildFull builds a full url with scheme, host, path and query string func (o *PetListURL) BuildFull(scheme, host string) (*url.URL, error) { if scheme == "" { return nil, errors.New("scheme is required for a full url on PetListURL") } if host == "" { return nil, errors.New("host is required for a full url on PetListURL") } base, err := o.Build() if err != nil { return nil, err } base.Scheme = scheme base.Host = host return base, nil } // StringFull returns the string representation of a complete url func (o *PetListURL) StringFull(scheme, host string) string { return o.Must(o.BuildFull(scheme, host)).String() }
{ "content_hash": "6b61df5aea4b25dd27766c0b94d51343", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 99, "avg_line_length": 23.55045871559633, "alnum_prop": 0.6918582002337359, "repo_name": "go-swagger/go-swagger", "id": "13a8cf868ed41b9f3441b37af495fd278411bfe4", "size": "2614", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/contributed-templates/stratoscale/restapi/operations/pet/pet_list_urlbuilder.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "791" }, { "name": "Dockerfile", "bytes": "969" }, { "name": "Go", "bytes": "2433376" }, { "name": "PowerShell", "bytes": "287" }, { "name": "Shell", "bytes": "159997" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <title></title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="css/style.css" rel="stylesheet"> </head> <body> <script data-main="js/main" src="./bower_components/requirejs/require.js"></script> </body> </html>
{ "content_hash": "89ef1215c962657e9376b6cb3637e1ff", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 91, "avg_line_length": 30.25, "alnum_prop": 0.5840220385674931, "repo_name": "samithks/design-patterns", "id": "dbcc312613e587aba279e9520505a2db0f5af540", "size": "363", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "JavaScript/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "363" }, { "name": "JavaScript", "bytes": "1578" } ], "symlink_target": "" }
using namespace boost; const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds const QString BITCOIN_IPC_PREFIX("nestorcoin:"); // // Create a name that is unique for: // testnet / non-testnet // data directory // static QString ipcServerName() { QString name("BitcoinQt"); // Append a simple hash of the datadir // Note that GetDataDir(true) returns a different path // for -testnet versus main net QString ddir(GetDataDir(true).string().c_str()); name.append(QString::number(qHash(ddir))); return name; } // // This stores payment requests received before // the main GUI window is up and ready to ask the user // to send payment. // static QStringList savedPaymentRequests; // // Sending to the server is done synchronously, at startup. // If the server isn't already running, startup continues, // and the items in savedPaymentRequest will be handled // when uiReady() is called. // bool PaymentServer::ipcSendCommandLine() { bool fResult = false; const QStringList& args = qApp->arguments(); for (int i = 1; i < args.size(); i++) { if (!args[i].startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) continue; savedPaymentRequests.append(args[i]); } foreach (const QString& arg, savedPaymentRequests) { QLocalSocket* socket = new QLocalSocket(); socket->connectToServer(ipcServerName(), QIODevice::WriteOnly); if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT)) return false; QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_0); out << arg; out.device()->seek(0); socket->write(block); socket->flush(); socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT); socket->disconnectFromServer(); delete socket; fResult = true; } return fResult; } PaymentServer::PaymentServer(QApplication* parent) : QObject(parent), saveURIs(true) { // Install global event filter to catch QFileOpenEvents on the mac (sent when you click bitcoin: links) parent->installEventFilter(this); QString name = ipcServerName(); // Clean up old socket leftover from a crash: QLocalServer::removeServer(name); uriServer = new QLocalServer(this); if (!uriServer->listen(name)) qDebug() << tr("Cannot start nestorcoin: click-to-pay handler"); else connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection())); } bool PaymentServer::eventFilter(QObject *object, QEvent *event) { // clicking on bitcoin: URLs creates FileOpen events on the Mac: if (event->type() == QEvent::FileOpen) { QFileOpenEvent* fileEvent = static_cast<QFileOpenEvent*>(event); if (!fileEvent->url().isEmpty()) { if (saveURIs) // Before main window is ready: savedPaymentRequests.append(fileEvent->url().toString()); else emit receivedURI(fileEvent->url().toString()); return true; } } return false; } void PaymentServer::uiReady() { saveURIs = false; foreach (const QString& s, savedPaymentRequests) emit receivedURI(s); savedPaymentRequests.clear(); } void PaymentServer::handleURIConnection() { QLocalSocket *clientConnection = uriServer->nextPendingConnection(); while (clientConnection->bytesAvailable() < (int)sizeof(quint32)) clientConnection->waitForReadyRead(); connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater())); QDataStream in(clientConnection); in.setVersion(QDataStream::Qt_4_0); if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) { return; } QString message; in >> message; if (saveURIs) savedPaymentRequests.append(message); else emit receivedURI(message); }
{ "content_hash": "54d057a46259853b297708bc3ad221fd", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 107, "avg_line_length": 28.72463768115942, "alnum_prop": 0.6589303733602422, "repo_name": "Nestorcoin/nestorcoin", "id": "149593702e4c0a3f603484bb06717b0dbbdbe567", "size": "4509", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qt/paymentserver.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "32413" }, { "name": "C++", "bytes": "2606637" }, { "name": "CSS", "bytes": "1127" }, { "name": "Groff", "bytes": "18284" }, { "name": "HTML", "bytes": "50621" }, { "name": "Makefile", "bytes": "13915" }, { "name": "NSIS", "bytes": "5996" }, { "name": "Objective-C", "bytes": "1052" }, { "name": "Objective-C++", "bytes": "5864" }, { "name": "Python", "bytes": "69724" }, { "name": "QMake", "bytes": "14761" }, { "name": "Shell", "bytes": "16854" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "e18f26e5908742f36071e7704fa2c556", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "65397803da8cb3ff2e2ce273f20e725e93817626", "size": "177", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Thymelaeaceae/Stellera/Stellera himalayensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
namespace AdventureWorks.Repository.Main { using System; using System.Collections.Generic; using System.Linq.Expressions; public interface IRepository<T> { IList<T> SearchFor(Expression<Func<T, bool>> predicate); IList<T> GetAll(); T GetById(int id); } }
{ "content_hash": "357a4eb02fa9741f18dde401ad7d9484", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 64, "avg_line_length": 23.384615384615383, "alnum_prop": 0.6513157894736842, "repo_name": "krzysztofkolek/AdventureWorksAPI", "id": "f8e95a87b6a634ea4f10ec468e4fe154a1a3e177", "size": "306", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Repository/Main/IRepository.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "1482286" }, { "name": "HTML", "bytes": "1500" } ], "symlink_target": "" }
static NSString *const AMConfigurationLayoutsKey = @"layouts"; // The key to reference the modifier flags intended to be used for a specific // command. This key is optionally present. If ommitted the default value is // used. // // Valid strings are defined below. Any other values are an assertion error. static NSString *const AMConfigurationCommandModKey = @"mod"; // The key to reference the keyboard character intended to be used for a // specific command. This key is optionally present. If ommitted the default // value is used. static NSString *const AMConfigurationCommandKeyKey = @"key"; // Valid strings that can be used in configuration for command modifiers. static NSString *const AMConfigurationMod1String = @"mod1"; static NSString *const AMConfigurationMod2String = @"mod2"; static NSString *const AMConfigurationScreens = @"screens"; // Command strings that reference possible window management commands. They are // optionally present in the configuration file. If any is ommitted the default // is used. // // Note: This technically allows for commands having the same key code and // flags. The behavior in that case is not well defined. We may want this to // be an assertion error. static NSString *const AMConfigurationCommandCycleLayoutForwardKey = @"cycle-layout"; static NSString *const AMConfigurationCommandCycleLayoutBackwardKey = @"cycle-layout-backward"; static NSString *const AMConfigurationCommandShrinkMainKey = @"shrink-main"; static NSString *const AMConfigurationCommandExpandMainKey = @"expand-main"; static NSString *const AMConfigurationCommandIncreaseMainKey = @"increase-main"; static NSString *const AMConfigurationCommandDecreaseMainKey = @"decrease-main"; static NSString *const AMConfigurationCommandFocusCCWKey = @"focus-ccw"; static NSString *const AMConfigurationCommandFocusCWKey = @"focus-cw"; static NSString *const AMConfigurationCommandSwapScreenCCWKey = @"swap-screen-ccw"; static NSString *const AMConfigurationCommandSwapScreenCWKey = @"swap-screen-cw"; static NSString *const AMConfigurationCommandSwapCCWKey = @"swap-ccw"; static NSString *const AMConfigurationCommandSwapCWKey = @"swap-cw"; static NSString *const AMConfigurationCommandSwapMainKey = @"swap-main"; static NSString *const AMConfigurationCommandThrowSpacePrefixKey = @"throw-space"; static NSString *const AMConfigurationCommandFocusScreenPrefixKey = @"focus-screen"; static NSString *const AMConfigurationCommandThrowScreenPrefixKey = @"throw-screen"; static NSString *const AMConfigurationCommandToggleFloatKey = @"toggle-float"; static NSString *const AMConfigurationCommandDisplayCurrentLayoutKey = @"display-current-layout"; static NSString *const AMConfigurationCommandToggleTilingKey = @"toggle-tiling"; // Key to reference an array of application bundle identifiers whose windows // should always be floating by default. static NSString *const AMConfigurationFloatingBundleIdentifiers = @"floating"; static NSString *const AMConfigurationIgnoreMenuBar = @"ignore-menu-bar"; static NSString *const AMConfigurationFloatSmallWindows = @"float-small-windows"; static NSString *const AMConfigurationMouseFollowsFocus = @"mouse-follows-focus"; static NSString *const AMConfigurationFocusFollowsMouse = @"focus-follows-mouse"; static NSString *const AMConfigurationEnablesLayoutHUD = @"enables-layout-hud"; static NSString *const AMConfigurationEnablesLayoutHUDOnSpaceChange = @"enables-layout-hud-on-space-change"; static NSString *const AMConfigurationUseCanaryBuild = @"use-canary-build"; @interface AMConfiguration () @property (nonatomic, copy) NSDictionary *configuration; @property (nonatomic, copy) NSDictionary *defaultConfiguration; @property (nonatomic, assign) AMModifierFlags modifier1; @property (nonatomic, assign) AMModifierFlags modifier2; @property (nonatomic, assign) NSInteger screens; @end @implementation AMConfiguration #pragma mark Lifecycle + (AMConfiguration *)sharedConfiguration { static AMConfiguration *sharedConfiguration; @synchronized (AMConfiguration.class) { if (!sharedConfiguration) sharedConfiguration = [[AMConfiguration alloc] init]; return sharedConfiguration; } } - (id)init { self = [super init]; if (self) { self.tilingEnabled = YES; } return self; } #pragma mark Configuration Loading - (AMModifierFlags)modifierFlagsForStrings:(NSArray *)modifierStrings { AMModifierFlags flags = 0; for (NSString *modifierString in modifierStrings) { if ([modifierString isEqualToString:@"option"]) flags = flags | NSAlternateKeyMask; else if ([modifierString isEqualToString:@"shift"]) flags = flags | NSShiftKeyMask; else if ([modifierString isEqualToString:@"control"]) flags = flags | NSControlKeyMask; else if ([modifierString isEqualToString:@"command"]) flags = flags | NSCommandKeyMask; else DDLogError(@"Unrecognized modifier string: %@", modifierString); } return flags; } + (Class)layoutClassForString:(NSString *)layoutString { if ([layoutString isEqualToString:@"tall"]) return [AMTallLayout class]; if ([layoutString isEqualToString:@"wide"]) return [AMWideLayout class]; if ([layoutString isEqualToString:@"fullscreen"]) return [AMFullscreenLayout class]; if ([layoutString isEqualToString:@"column"]) return [AMColumnLayout class]; if ([layoutString isEqualToString:@"row"]) return [AMRowLayout class]; if ([layoutString isEqualToString:@"floating"]) return [AMFloatingLayout class]; if ([layoutString isEqualToString:@"widescreen-tall"]) return [AMWidescreenTallLayout class]; return nil; } + (NSString *)stringForLayoutClass:(Class)layoutClass { if (layoutClass == [AMTallLayout class]) return @"tall"; if (layoutClass == [AMWideLayout class]) return @"wide"; if (layoutClass == [AMFullscreenLayout class]) return @"fullscreen"; if (layoutClass == [AMColumnLayout class]) return @"column"; if (layoutClass == [AMRowLayout class]) return @"row"; if (layoutClass == [AMFloatingLayout class]) return @"floating"; if (layoutClass == [AMWidescreenTallLayout class]) return @"widescreen-tall"; return nil; } - (void)loadConfiguration { [self loadConfigurationFile]; NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; for (NSString *defaultsKey in @[ AMConfigurationLayoutsKey, AMConfigurationFloatingBundleIdentifiers, AMConfigurationIgnoreMenuBar, AMConfigurationFloatSmallWindows, AMConfigurationMouseFollowsFocus, AMConfigurationFocusFollowsMouse, AMConfigurationEnablesLayoutHUD, AMConfigurationEnablesLayoutHUDOnSpaceChange, AMConfigurationUseCanaryBuild ]) { id value = self.configuration[defaultsKey]; id defaultValue = self.defaultConfiguration[defaultsKey]; if (value || (defaultValue && ![userDefaults objectForKey:defaultsKey])) { [userDefaults setObject:value ?: defaultValue forKey:defaultsKey]; } } } - (void)loadConfigurationFile { NSString *amethystConfigPath = [NSHomeDirectory() stringByAppendingPathComponent:@".amethyst"]; NSString *defaultAmethystConfigPath = [[NSBundle mainBundle] pathForResource:@"default" ofType:@"amethyst"]; NSData *data; NSError *error; NSDictionary *configuration; if ([[NSFileManager defaultManager] fileExistsAtPath:amethystConfigPath isDirectory:NO]) { data = [NSData dataWithContentsOfFile:amethystConfigPath]; if (data) { configuration = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; if (error) { DDLogError(@"error loading configuration: %@", error); NSString *message = [NSString stringWithFormat:@"There was an error trying to load your .amethyst configuration. Going to use default configuration. %@", error.localizedDescription]; NSRunAlertPanel(@"Error loading configuration", message, @"OK", nil, nil); } else { self.configuration = configuration; } } } error = nil; data = [NSData dataWithContentsOfFile:defaultAmethystConfigPath]; configuration = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; if (error) { DDLogError(@"error loading default configuration: %@", error); NSRunAlertPanel(@"Error loading default configuration", @"There was an error when trying to load the default configuration. Amethyst may not function correctly.", @"OK", nil, nil); return; } self.defaultConfiguration = configuration; self.modifier1 = [self modifierFlagsForStrings:self.configuration[AMConfigurationMod1String] ?: self.defaultConfiguration[AMConfigurationMod1String]]; self.modifier2 = [self modifierFlagsForStrings:self.configuration[AMConfigurationMod2String] ?: self.defaultConfiguration[AMConfigurationMod2String]]; self.screens = [(self.configuration[AMConfigurationScreens] ?: self.defaultConfiguration[AMConfigurationScreens]) integerValue]; } - (NSString *)constructLayoutKeyString:(NSString *)layoutString { return [NSString stringWithFormat:@"select-%@-layout", layoutString]; } #pragma mark Hot Key Mapping - (AMModifierFlags)modifierFlagsForModifierString:(NSString *)modifierString { if ([modifierString isEqualToString:@"mod1"]) return self.modifier1; if ([modifierString isEqualToString:@"mod2"]) return self.modifier2; DDLogError(@"Unknown modifier string: %@", modifierString); return self.modifier1; } - (void)constructCommandWithHotKeyManager:(AMHotKeyManager *)hotKeyManager commandKey:(NSString *)commandKey handler:(AMHotKeyHandler)handler { BOOL override = NO; NSDictionary *command = self.configuration[commandKey]; if (command) { override = YES; } else { command = self.defaultConfiguration[commandKey]; } NSString *commandKeyString = command[AMConfigurationCommandKeyKey]; NSString *commandModifierString = command[AMConfigurationCommandModKey]; AMModifierFlags commandFlags; if ([commandModifierString isEqualToString:@"mod1"]) { commandFlags = self.modifier1; } else if ([commandModifierString isEqualToString:@"mod2"]) { commandFlags = self.modifier2; } else { DDLogError(@"Unknown modifier string: %@", commandModifierString); return; } [hotKeyManager registerHotKeyWithKeyString:commandKeyString modifiers:commandFlags handler:handler defaultsKey:commandKey override:override]; } - (void)setUpWithHotKeyManager:(AMHotKeyManager *)hotKeyManager windowManager:(AMWindowManager *)windowManager { [self constructCommandWithHotKeyManager:hotKeyManager commandKey:AMConfigurationCommandCycleLayoutForwardKey handler:^{ [windowManager.focusedScreenManager cycleLayoutForward]; }]; [self constructCommandWithHotKeyManager:hotKeyManager commandKey:AMConfigurationCommandCycleLayoutBackwardKey handler:^{ [windowManager.focusedScreenManager cycleLayoutBackward]; }]; [self constructCommandWithHotKeyManager:hotKeyManager commandKey:AMConfigurationCommandShrinkMainKey handler:^{ [[windowManager focusedScreenManager] updateCurrentLayout:^(AMLayout *layout) { [layout shrinkMainPane]; }]; }]; [self constructCommandWithHotKeyManager:hotKeyManager commandKey:AMConfigurationCommandExpandMainKey handler:^{ [[windowManager focusedScreenManager] updateCurrentLayout:^(AMLayout *layout) { [layout expandMainPane]; }]; }]; [self constructCommandWithHotKeyManager:hotKeyManager commandKey:AMConfigurationCommandIncreaseMainKey handler:^{ [[windowManager focusedScreenManager] updateCurrentLayout:^(AMLayout *layout) { [layout increaseMainPaneCount]; }]; }]; [self constructCommandWithHotKeyManager:hotKeyManager commandKey:AMConfigurationCommandDecreaseMainKey handler:^{ [[windowManager focusedScreenManager] updateCurrentLayout:^(AMLayout *layout) { [layout decreaseMainPaneCount]; }]; }]; [self constructCommandWithHotKeyManager:hotKeyManager commandKey:AMConfigurationCommandFocusCCWKey handler:^{ [windowManager moveFocusCounterClockwise]; }]; [self constructCommandWithHotKeyManager:hotKeyManager commandKey:AMConfigurationCommandFocusCWKey handler:^{ [windowManager moveFocusClockwise]; }]; [self constructCommandWithHotKeyManager:hotKeyManager commandKey:AMConfigurationCommandSwapScreenCCWKey handler:^{ [windowManager swapFocusedWindowScreenCounterClockwise]; }]; [self constructCommandWithHotKeyManager:hotKeyManager commandKey:AMConfigurationCommandSwapScreenCWKey handler:^{ [windowManager swapFocusedWindowScreenClockwise]; }]; [self constructCommandWithHotKeyManager:hotKeyManager commandKey:AMConfigurationCommandSwapCCWKey handler:^{ [windowManager swapFocusedWindowCounterClockwise]; }]; [self constructCommandWithHotKeyManager:hotKeyManager commandKey:AMConfigurationCommandSwapCWKey handler:^{ [windowManager swapFocusedWindowClockwise]; }]; [self constructCommandWithHotKeyManager:hotKeyManager commandKey:AMConfigurationCommandSwapMainKey handler:^{ [windowManager swapFocusedWindowToMain]; }]; [self constructCommandWithHotKeyManager:hotKeyManager commandKey:AMConfigurationCommandDisplayCurrentLayoutKey handler:^{ [windowManager displayCurrentLayout]; }]; for (NSUInteger screenNumber = 1; screenNumber <= self.screens; ++screenNumber) { NSString *focusCommandKey = [AMConfigurationCommandFocusScreenPrefixKey stringByAppendingFormat:@"-%d", (unsigned int)screenNumber]; NSString *throwCommandKey = [AMConfigurationCommandThrowScreenPrefixKey stringByAppendingFormat:@"-%d", (unsigned int)screenNumber]; [self constructCommandWithHotKeyManager:hotKeyManager commandKey:focusCommandKey handler:^{ [windowManager focusScreenAtIndex:screenNumber]; }]; [self constructCommandWithHotKeyManager:hotKeyManager commandKey:throwCommandKey handler:^{ [windowManager throwToScreenAtIndex:screenNumber]; }]; } for (NSUInteger spaceNumber = 1; spaceNumber < 10; ++spaceNumber) { NSString *commandKey = [AMConfigurationCommandThrowSpacePrefixKey stringByAppendingFormat:@"-%d", (unsigned int)spaceNumber]; [self constructCommandWithHotKeyManager:hotKeyManager commandKey:commandKey handler:^{ [windowManager pushFocusedWindowToSpace:spaceNumber]; }]; } [self constructCommandWithHotKeyManager:hotKeyManager commandKey:AMConfigurationCommandToggleFloatKey handler:^{ [windowManager toggleFloatForFocusedWindow]; }]; [self constructCommandWithHotKeyManager:hotKeyManager commandKey:AMConfigurationCommandToggleTilingKey handler:^{ [AMConfiguration sharedConfiguration].tilingEnabled = ![AMConfiguration sharedConfiguration].tilingEnabled; [windowManager markAllScreensForReflow]; }]; NSArray *layoutStrings = self.configuration[AMConfigurationLayoutsKey] ?: self.defaultConfiguration[AMConfigurationLayoutsKey]; for (NSString *layoutString in layoutStrings) { Class layoutClass = [self.class layoutClassForString:layoutString]; if (!layoutClass) { continue; } [self constructCommandWithHotKeyManager:hotKeyManager commandKey:[self constructLayoutKeyString:layoutString] handler:^{ [[windowManager focusedScreenManager] selectLayout:layoutClass]; }]; } } #pragma mark Public Methods - (NSArray *)layouts { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSArray *layoutStrings = [userDefaults arrayForKey:AMConfigurationLayoutsKey]; NSMutableArray *layouts = [NSMutableArray array]; for (NSString *layoutString in layoutStrings) { Class layoutClass = [self.class layoutClassForString:layoutString]; if (!layoutClass) { DDLogError(@"Unrecognized layout string: %@", layoutString); continue; } [layouts addObject:layoutClass]; } return layouts; } - (NSArray *)layoutStrings { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; return [userDefaults arrayForKey:AMConfigurationLayoutsKey] ?: @[]; } - (void)setLayoutStrings:(NSArray *)layoutStrings { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; [userDefaults setObject:layoutStrings forKey:AMConfigurationLayoutsKey]; } - (NSArray *)availableLayoutStrings { return [[[@[ [AMTallLayout class], [AMWideLayout class], [AMFullscreenLayout class], [AMColumnLayout class], [AMRowLayout class], [AMFloatingLayout class], [AMWidescreenTallLayout class] ] rac_sequence] map:^ NSString * (Class layoutClass) { return [self.class stringForLayoutClass:layoutClass]; }] array]; } - (BOOL)runningApplicationShouldFloat:(NSRunningApplication *)runningApplication { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSArray *floatingBundleIdentifiers = [userDefaults arrayForKey:AMConfigurationFloatingBundleIdentifiers]; if (!floatingBundleIdentifiers) { return NO; } return [floatingBundleIdentifiers containsObject:runningApplication.bundleIdentifier]; } - (BOOL)ignoreMenuBar { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; return [userDefaults boolForKey:AMConfigurationIgnoreMenuBar]; } - (BOOL)floatSmallWindows { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; return [userDefaults boolForKey:AMConfigurationFloatSmallWindows]; } - (BOOL)mouseFollowsFocus { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; return [userDefaults boolForKey:AMConfigurationMouseFollowsFocus]; } - (BOOL)focusFollowsMouse { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; return [userDefaults boolForKey:AMConfigurationFocusFollowsMouse]; } - (BOOL)enablesLayoutHUD { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; return [userDefaults boolForKey:AMConfigurationEnablesLayoutHUD]; } - (BOOL)enablesLayoutHUDOnSpaceChange { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; return [userDefaults boolForKey:AMConfigurationEnablesLayoutHUDOnSpaceChange]; } - (BOOL)useCanaryBuild { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; return [userDefaults boolForKey:AMConfigurationUseCanaryBuild]; } - (NSArray *)floatingBundleIdentifiers { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; return [userDefaults arrayForKey:AMConfigurationFloatingBundleIdentifiers] ?: @[]; } - (void)setFloatingBundleIdentifiers:(NSArray *)floatingBundleIdentifiers { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; [userDefaults setObject:floatingBundleIdentifiers ?: @[] forKey:AMConfigurationFloatingBundleIdentifiers]; } - (NSArray *)hotKeyNameToDefaultsKey { NSMutableArray *hotKeyNameToDefaultsKey = [NSMutableArray arrayWithCapacity:30]; [hotKeyNameToDefaultsKey addObject:@[@"Cycle layout forward", AMConfigurationCommandCycleLayoutForwardKey]]; [hotKeyNameToDefaultsKey addObject:@[@"Cycle layout backwards", AMConfigurationCommandCycleLayoutBackwardKey]]; [hotKeyNameToDefaultsKey addObject:@[@"Shrink main pane", AMConfigurationCommandShrinkMainKey]]; [hotKeyNameToDefaultsKey addObject:@[@"Expand main pane", AMConfigurationCommandExpandMainKey]]; [hotKeyNameToDefaultsKey addObject:@[@"Increase main pane count", AMConfigurationCommandIncreaseMainKey]]; [hotKeyNameToDefaultsKey addObject:@[@"Decrease main pane count", AMConfigurationCommandDecreaseMainKey]]; [hotKeyNameToDefaultsKey addObject:@[@"Move focus counter clockwise", AMConfigurationCommandFocusCCWKey]]; [hotKeyNameToDefaultsKey addObject:@[@"Move focus clockwise", AMConfigurationCommandFocusCWKey]]; [hotKeyNameToDefaultsKey addObject:@[@"Swap focused window to counter clockwise screen", AMConfigurationCommandSwapScreenCCWKey]]; [hotKeyNameToDefaultsKey addObject:@[@"Swap focused window to clockwise screen", AMConfigurationCommandSwapScreenCWKey]]; [hotKeyNameToDefaultsKey addObject:@[@"Swap focused window counter clockwise", AMConfigurationCommandSwapCCWKey]]; [hotKeyNameToDefaultsKey addObject:@[@"Swap focused window clockwise", AMConfigurationCommandSwapCWKey]]; [hotKeyNameToDefaultsKey addObject:@[@"Swap focused window with main window", AMConfigurationCommandSwapMainKey]]; for (NSUInteger spaceNumber = 1; spaceNumber < 10; ++spaceNumber) { NSString *name = [NSString stringWithFormat:@"Throw focused window to space %@", @(spaceNumber)]; [hotKeyNameToDefaultsKey addObject:@[name, [AMConfigurationCommandThrowSpacePrefixKey stringByAppendingFormat:@"-%@", @(spaceNumber)]]]; } for (NSUInteger screenNumber = 1; screenNumber <= 3; ++screenNumber) { NSString *focusCommandName = [NSString stringWithFormat:@"Focus screen %@", @(screenNumber)]; NSString *throwCommandName = [NSString stringWithFormat:@"Throw focused window to screen %@", @(screenNumber)]; NSString *focusCommandKey = [AMConfigurationCommandFocusScreenPrefixKey stringByAppendingFormat:@"-%@", @(screenNumber)]; NSString *throwCommandKey = [AMConfigurationCommandThrowScreenPrefixKey stringByAppendingFormat:@"-%@", @(screenNumber)]; [hotKeyNameToDefaultsKey addObject:@[focusCommandName, focusCommandKey]]; [hotKeyNameToDefaultsKey addObject:@[throwCommandName, throwCommandKey]]; } [hotKeyNameToDefaultsKey addObject:@[@"Toggle float for focused window", AMConfigurationCommandToggleFloatKey]]; [hotKeyNameToDefaultsKey addObject:@[@"Display current layout", AMConfigurationCommandDisplayCurrentLayoutKey]]; [hotKeyNameToDefaultsKey addObject:@[@"Toggle global tiling", AMConfigurationCommandToggleTilingKey]]; for (NSString *layoutString in self.availableLayoutStrings) { NSString *commandName = [NSString stringWithFormat:@"Select %@ layout", layoutString]; NSString *commandKey = [NSString stringWithFormat:@"select-%@-layout", layoutString]; [hotKeyNameToDefaultsKey addObject:@[commandName, commandKey]]; } return hotKeyNameToDefaultsKey; } @end
{ "content_hash": "b3b73217e1592744b41264f7988a4982", "timestamp": "", "source": "github", "line_count": 472, "max_line_length": 198, "avg_line_length": 48.4978813559322, "alnum_prop": 0.7491153728539601, "repo_name": "m4rw3r/Amethyst", "id": "4863e5ae0e8ee9f0ad7f4ac616db31eb632e1622", "size": "23436", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Amethyst/AMConfiguration.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "150205" }, { "name": "Ruby", "bytes": "568" }, { "name": "Shell", "bytes": "256" } ], "symlink_target": "" }
import {inject, TestBed} from '@angular/core/testing'; import {WidgetService} from './widget.service'; import {Response, ResponseOptions, ResponseType, Http} from '@angular/http'; import {Dashboard} from './dashboard'; import {WidgetConfig} from './widget-config'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/of'; class FakeWidgetHttp { public get(url: string): Observable<Response> { switch (url) { case '/mock/api/dashboards/test/widgets/all': return this.getUnpagedWidgets(); case '/mock/widgets/error': return this.getWidgetsWithError(); case '/mock/data': return this.getWidgetData(); case '/mock/data/error': return this.getWidgetDataWithError(); default: throw new Error('unmocked url: ' + url); } } private getUnpagedWidgets() { const body = { '_embedded': { 'widgetConfigResourceList': [{ 'title': 'dev', 'type': 'platform-status', 'lastModified': 1474140249062, 'sourceConfigs': [{ 'id': 'version', 'type': 'urlSource', 'interval': 10000, 'configData': {'url': 'https://putsreq.com/eT3fqDqHnnNKureYOuOf'} }, { 'id': 'status', 'type': 'urlSource', 'interval': 10000, 'configData': {'url': 'https://putsreq.com/eT3fqDqHnnNKureYOuOf'} }], '_links': { 'self': {'href': '/mock/api/dashboards/test/widgets/57dd98597e21e57c76718be6'}, 'dashboard': {'href': '/mock/api/dashboards/test'}, 'data': {'href': '/mock/api/dashboards/test/widgets/57dd98597e21e57c76718be6/data'} } }, { 'title': 'test', 'type': 'platform-status', 'lastModified': 1474140249140, 'sourceConfigs': [{ 'id': 'version', 'type': 'urlSource', 'interval': 10000, 'configData': {'url': 'https://putsreq.com/uh7LA812il8FBDXBjTaB'} }, { 'id': 'status', 'type': 'urlSource', 'interval': 10000, 'configData': {'url': 'https://putsreq.com/uh7LA812il8FBDXBjTaB'} }], '_links': { 'self': {'href': '/mock/api/dashboards/test/widgets/57dd98597e21e57c76718be7'}, 'dashboard': {'href': '/mock/api/dashboards/test'}, 'data': {'href': '/mock/api/dashboards/test/widgets/57dd98597e21e57c76718be7/data'} } }, { 'title': 'prod', 'type': 'platform-status', 'lastModified': 1474140249062, 'sourceConfigs': [{ 'id': 'version', 'type': 'urlSource', 'interval': 10000, 'configData': {'url': 'https://putsreq.com/eT3fqDqHnnNKureYOuOe'} }, { 'id': 'status', 'type': 'urlSource', 'interval': 10000, 'configData': {'url': 'https://putsreq.com/eT3fqDqHnnNKureYOuOe'} }], '_links': { 'self': {'href': '/mock/api/dashboards/test/widgets/57dd98597e21e57c76718be5'}, 'dashboard': {'href': '/mock/api/dashboards/test'}, 'data': {'href': '/mock/api/dashboards/test/widgets/57dd98597e21e57c76718be5/data'} } }] }, '_links': { 'self': {'href': '/mock/api/dashboards/test/widgets/all'} } }; return this.createFakeResponse('/mock/api/dashboards/test/widgets/all', body); } private createFakeResponse(url: string, body: any, status = 200): Observable<Response> { const responseOptionsArgs = { body: body, status: status, statusText: 'OK', url: url, type: ResponseType.Basic }; return Observable.of(new Response(new ResponseOptions(responseOptionsArgs))); } public getWidgetsWithError(): Observable<Response> { return this.createFakeResponse('/mock/widgets/error', {}, 500); } public getWidgetData(): Observable<Response> { const body: any = { 'sourceData': [{ 'id': '57dd991e6690b0f6fdc47cb3', 'widgetId': '57dd98a27e21e57c76718bed', 'sourceId': 'status', 'data': {'content': 'operable', 'status': 200} }, { 'id': '57dd99216690b0f6fdc47cbf', 'widgetId': '57dd98a27e21e57c76718bed', 'sourceId': 'version', 'data': {'content': '1.0.3', 'status': 200} }], '_links': {'widget': {'href': '/mock/api/dashboards/test/widgets/57dd98a27e21e57c76718bed'}} }; return this.createFakeResponse('/mock/widgets/data', body); } public getWidgetDataWithError(): Observable<Response> { return this.createFakeResponse('/mock/data/error', {}, 500); } } const dashboard = new Dashboard(3, 'Testing', 'test', 'test reports', '/mock/api/dashboards/test/widgets/all'); describe('Service: Widget', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ {provide: Http, useClass: FakeWidgetHttp}, WidgetService ] }); } ); it('should create an instance', inject([WidgetService], (service: WidgetService) => { expect(service).toBeTruthy(); })); it('getWidgets() returns a list of widget configs', inject([WidgetService], (service: WidgetService) => { const widgetConfigs = service.getWidgets(dashboard); expect(widgetConfigs).toBeTruthy(); })); it('getWidgets() returns a list of three widget configs', inject([WidgetService], (service: WidgetService) => { service.getWidgets(dashboard).subscribe(widgetConfigs => { expect(widgetConfigs.length).toEqual(3); }); })); it('getWidgets()[0] returns the first widget config', inject([WidgetService], (service: WidgetService) => { service.getWidgets(dashboard).subscribe(widgetConfigs => { expect(widgetConfigs[0].title).toEqual('dev'); expect(widgetConfigs[0].type).toEqual('platform-status'); expect(widgetConfigs[0].dataLink).toEqual('/mock/api/dashboards/test/widgets/57dd98597e21e57c76718be6/data'); }); })); it('getWidgetData() returns an untyped object containing two widget data objects', inject([WidgetService], (service: WidgetService) => { const widgetConfig = new WidgetConfig('platform-status', 'dev', '/mock/data'); service.getWidgetData(widgetConfig).subscribe(data => { expect(data.length).toEqual(2); }); })); it('getWidgetData() returns an untyped object containing widget display data', inject([WidgetService], (service: WidgetService) => { const widgetConfig = new WidgetConfig('platform-status', 'dev', '/mock/data'); service.getWidgetData(widgetConfig).subscribe(data => { expect(data[0].sourceId).toEqual('status'); expect(data[1].sourceId).toEqual('version'); }); })); });
{ "content_hash": "6049e062f799bb3b5024d5d9f207a70d", "timestamp": "", "source": "github", "line_count": 196, "max_line_length": 115, "avg_line_length": 35.076530612244895, "alnum_prop": 0.5909818181818182, "repo_name": "reflectoring/infiniboard", "id": "1d54d01449b7d2388a82976f5ee1ead5678d1a51", "size": "6875", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dashy/src/app/dashboard/shared/widget.service.spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "40058" }, { "name": "Dockerfile", "bytes": "600" }, { "name": "HTML", "bytes": "8198" }, { "name": "Java", "bytes": "123009" }, { "name": "JavaScript", "bytes": "2741" }, { "name": "Shell", "bytes": "2693" }, { "name": "TypeScript", "bytes": "52666" } ], "symlink_target": "" }
let addEmp41 = (employees) => { employees.push( {id:41, name: 'Jerome McCarthy'} ) return employees; }; export {addEmp41};
{ "content_hash": "dcae477112370168569c501049e9f1b6", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 40, "avg_line_length": 18, "alnum_prop": 0.5833333333333334, "repo_name": "dharapvj/learning-webpack2", "id": "751a7f35a500e771824165929205ee7e46a76a91", "size": "144", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "gen/step-02/e41.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3898" }, { "name": "HTML", "bytes": "17451" }, { "name": "JavaScript", "bytes": "142444" }, { "name": "TypeScript", "bytes": "360" } ], "symlink_target": "" }
#include "platform-posix.h" #include "openthread/types.h" #include "openthread/platform/misc.h" void otPlatReset(otInstance *aInstance) { // This function does nothing on the Posix platform. (void)aInstance; } otPlatResetReason otPlatGetResetReason(otInstance *aInstance) { (void)aInstance; return kPlatResetReason_PowerOn; }
{ "content_hash": "e40cdf2128d610262b9ad859e49be79f", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 61, "avg_line_length": 19.27777777777778, "alnum_prop": 0.7492795389048992, "repo_name": "Zolertia/openthread", "id": "4201f13577f3ce8af7c5ca3273037bd76477d1d3", "size": "1955", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "examples/platforms/posix/misc.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "10128" }, { "name": "C", "bytes": "402107" }, { "name": "C#", "bytes": "18077" }, { "name": "C++", "bytes": "2749034" }, { "name": "M4", "bytes": "32692" }, { "name": "Makefile", "bytes": "70609" }, { "name": "Python", "bytes": "1010387" }, { "name": "Shell", "bytes": "14997" } ], "symlink_target": "" }
#ifndef _UTMP_H # error "Never include <bits/utmp.h> directly; use <utmp.h> instead." #endif #include <paths.h> #include <sys/time.h> #include <sys/types.h> #include <bits/wordsize.h> #define UT_LINESIZE 32 #define UT_NAMESIZE 32 #define UT_HOSTSIZE 256 /* The structure describing an entry in the database of previous logins. */ struct lastlog { #if __WORDSIZE == 32 int64_t ll_time; #else __time_t ll_time; #endif char ll_line[UT_LINESIZE]; char ll_host[UT_HOSTSIZE]; }; /* The structure describing the status of a terminated process. This type is used in `struct utmp' below. */ struct exit_status { short int e_termination; /* Process termination status. */ short int e_exit; /* Process exit status. */ }; /* The structure describing an entry in the user accounting database. */ struct utmp { short int ut_type; /* Type of login. */ pid_t ut_pid; /* Process ID of login process. */ char ut_line[UT_LINESIZE] __attribute_nonstring__; /* Devicename. */ char ut_id[4] __attribute_nonstring__; /* Inittab ID. */ char ut_user[UT_NAMESIZE] __attribute_nonstring__; /* Username. */ char ut_host[UT_HOSTSIZE] __attribute_nonstring__; /* Hostname for remote login. */ struct exit_status ut_exit; /* Exit status of a process marked as DEAD_PROCESS. */ /* The ut_session and ut_tv fields must be the same size when compiled 32- and 64-bit. This allows data files and shared memory to be shared between 32- and 64-bit applications. */ #if __WORDSIZE == 32 int64_t ut_session; /* Session ID, used for windowing. */ struct { int64_t tv_sec; /* Seconds. */ int64_t tv_usec; /* Microseconds. */ } ut_tv; /* Time entry was made. */ #else long int ut_session; /* Session ID, used for windowing. */ struct timeval ut_tv; /* Time entry was made. */ #endif int32_t ut_addr_v6[4]; /* Internet address of remote host. */ char __glibc_reserved[20]; /* Reserved for future use. */ }; /* Backwards compatibility hacks. */ #define ut_name ut_user #ifndef _NO_UT_TIME /* We have a problem here: `ut_time' is also used otherwise. Define _NO_UT_TIME if the compiler complains. */ # define ut_time ut_tv.tv_sec #endif #define ut_xtime ut_tv.tv_sec #define ut_addr ut_addr_v6[0] /* Values for the `ut_type' field of a `struct utmp'. */ #define EMPTY 0 /* No valid user accounting information. */ #define RUN_LVL 1 /* The system's runlevel. */ #define BOOT_TIME 2 /* Time of system boot. */ #define NEW_TIME 3 /* Time after system clock changed. */ #define OLD_TIME 4 /* Time when system clock changed. */ #define INIT_PROCESS 5 /* Process spawned by the init process. */ #define LOGIN_PROCESS 6 /* Session leader of a logged in user. */ #define USER_PROCESS 7 /* Normal process. */ #define DEAD_PROCESS 8 /* Terminated process. */ #define ACCOUNTING 9 /* Old Linux name for the EMPTY type. */ #define UT_UNKNOWN EMPTY /* Tell the user that we have a modern system with UT_HOST, UT_PID, UT_TYPE, UT_ID and UT_TV fields. */ #define _HAVE_UT_TYPE 1 #define _HAVE_UT_PID 1 #define _HAVE_UT_ID 1 #define _HAVE_UT_TV 1 #define _HAVE_UT_HOST 1
{ "content_hash": "c2047a082a286d8dfcd361be7a0b9ea5", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 73, "avg_line_length": 28.8018018018018, "alnum_prop": 0.6609321238661245, "repo_name": "andrewrk/zig", "id": "75bef50c8a8d47a95eb5ddc132472e793c470ae5", "size": "4063", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/libc/include/s390x-linux-gnu/bits/utmp.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "654659" }, { "name": "C++", "bytes": "1974638" }, { "name": "CMake", "bytes": "15525" } ], "symlink_target": "" }
@interface LGSideMenuBorderView : UIView @property (assign, nonatomic) UIRectCorner roundedCorners; @property (assign, nonatomic) CGFloat cornerRadius; @property (strong, nonatomic, nullable) UIColor *strokeColor; @property (assign, nonatomic) CGFloat strokeWidth; @property (strong, nonatomic, nullable) UIColor *shadowColor; @property (assign, nonatomic) CGFloat shadowBlur; @end
{ "content_hash": "9f8b4251b31bbe6b31c9c1c164a682bf", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 61, "avg_line_length": 38.4, "alnum_prop": 0.8020833333333334, "repo_name": "dvlproad/CommonLibrary", "id": "b9212e0346553f8b6d76d7fab61873907df236b4", "size": "1710", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "CJStandardProjectDemo/Pods/LGSideMenuController/LGSideMenuController/LGSideMenuBorderView.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "156436" } ], "symlink_target": "" }
======= Sorting ======= Basic sort ========== Order a table by the :code:`last_name` column: .. code-block:: python new_table = table.order_by('last_name') Multicolumn sort ================ Because Python's internal sorting works natively with arrays, we can implement multi-column sort by returning an array from the key function. .. code-block:: python new_table = table.order_by(lambda row: [row['last_name'], row['first_name']) This table will now be ordered by :code:`last_name`, then :code:`first_name`. Randomizing order ================= .. code-block:: python import random new_table = table.order_by(lambda row: random.random())
{ "content_hash": "654e67dd6654ac67ac839be3373680aa", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 141, "avg_line_length": 19.705882352941178, "alnum_prop": 0.6447761194029851, "repo_name": "captainsafia/agate", "id": "065bc84dc451352c20ee5e4f316fe7f37f50d623", "size": "670", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/cookbook/sorting.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "148944" } ], "symlink_target": "" }
<!DOCTYPE html> <html class="reftest-wait"> <!-- Test: if output has a custom error, it should not be affected by :-moz-ui-valid pseudo-class. --> <link rel='stylesheet' type='text/css' href='style.css'> <body onload="document.getElementById('b').setCustomValidity('foo'); document.documentElement.className='';"> <output class='notvalid' id='b'>foo</output> </body> </html>
{ "content_hash": "644b4022260aea7586752293315af7e9", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 111, "avg_line_length": 44.44444444444444, "alnum_prop": 0.665, "repo_name": "sergecodd/FireFox-OS", "id": "83e824350fccce5f9eff090ff53aa170bed6b0d0", "size": "400", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "B2G/gecko/layout/reftests/css-ui-valid/output/output-invalid.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "443" }, { "name": "ApacheConf", "bytes": "85" }, { "name": "Assembly", "bytes": "5123438" }, { "name": "Awk", "bytes": "46481" }, { "name": "Batchfile", "bytes": "56250" }, { "name": "C", "bytes": "101720951" }, { "name": "C#", "bytes": "38531" }, { "name": "C++", "bytes": "148896543" }, { "name": "CMake", "bytes": "23541" }, { "name": "CSS", "bytes": "2758664" }, { "name": "DIGITAL Command Language", "bytes": "56757" }, { "name": "Emacs Lisp", "bytes": "12694" }, { "name": "Erlang", "bytes": "889" }, { "name": "FLUX", "bytes": "34449" }, { "name": "GLSL", "bytes": "26344" }, { "name": "Gnuplot", "bytes": "710" }, { "name": "Groff", "bytes": "447012" }, { "name": "HTML", "bytes": "43343468" }, { "name": "IDL", "bytes": "1455122" }, { "name": "Java", "bytes": "43261012" }, { "name": "JavaScript", "bytes": "46646658" }, { "name": "Lex", "bytes": "38358" }, { "name": "Logos", "bytes": "21054" }, { "name": "Makefile", "bytes": "2733844" }, { "name": "Matlab", "bytes": "67316" }, { "name": "Max", "bytes": "3698" }, { "name": "NSIS", "bytes": "421625" }, { "name": "Objective-C", "bytes": "877657" }, { "name": "Objective-C++", "bytes": "737713" }, { "name": "PHP", "bytes": "17415" }, { "name": "Pascal", "bytes": "6780" }, { "name": "Perl", "bytes": "1153180" }, { "name": "Perl6", "bytes": "1255" }, { "name": "PostScript", "bytes": "1139" }, { "name": "PowerShell", "bytes": "8252" }, { "name": "Protocol Buffer", "bytes": "26553" }, { "name": "Python", "bytes": "8453201" }, { "name": "Ragel in Ruby Host", "bytes": "3481" }, { "name": "Ruby", "bytes": "5116" }, { "name": "Scilab", "bytes": "7" }, { "name": "Shell", "bytes": "3383832" }, { "name": "SourcePawn", "bytes": "23661" }, { "name": "TeX", "bytes": "879606" }, { "name": "WebIDL", "bytes": "1902" }, { "name": "XSLT", "bytes": "13134" }, { "name": "Yacc", "bytes": "112744" } ], "symlink_target": "" }
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model app\modules\ac\models\Session */ $this->title = 'Create Session'; $this->params['breadcrumbs'][] = ['label' => 'Sessions', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="content-wrapper"> <div class="content-heading"> Session Create <small>You sure you need to do this?</small> </div> <div class="row"> <div class="col-xs-12"> <div class="support-default-index"> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div> </div> </div> </div>
{ "content_hash": "23c945920043a00c6c209a8491a575c2", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 77, "avg_line_length": 20.8, "alnum_prop": 0.5528846153846154, "repo_name": "nihilco/NF2", "id": "ce93a41ede0ffe10abefb907e0dc81cdefa74e46", "size": "624", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/ac/views/sessions/create.php", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1030" }, { "name": "CSS", "bytes": "1364" }, { "name": "PHP", "bytes": "1112741" } ], "symlink_target": "" }
/** * The package for the task's tests: * 6.8. Removing duplicates in an array. * * @author Alex Proshak (olexandr_proshak@ukr.net) */ package ru.job4j.task8;
{ "content_hash": "1606a0faa3ae4572d1863c69d8be891b", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 50, "avg_line_length": 23.285714285714285, "alnum_prop": 0.6871165644171779, "repo_name": "OleksandrProshak/Alexandr_Proshak", "id": "a9138b120531570c6c2419be2eb2ca12499e0dfe", "size": "163", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Level_Trainee/Part_001_Base_Syntax/6_Arrays/src/test/java/ru/job4j/task8/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "307351" } ], "symlink_target": "" }
package me.iwf.photopicker; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import java.util.ArrayList; /** * Created by Donglua on 16/6/25. * Builder class to ease Intent setup. */ public class PhotoPreview { public final static int REQUEST_CODE = 666; public final static String EXTRA_CURRENT_ITEM = "current_item"; public final static String EXTRA_PHOTOS = "photos"; public final static String EXTRA_SHOW_DELETE = "show_delete"; public static PhotoPreviewBuilder builder() { return new PhotoPreviewBuilder(); } public static class PhotoPreviewBuilder { private Bundle mPreviewOptionsBundle; private Intent mPreviewIntent; public PhotoPreviewBuilder() { mPreviewOptionsBundle = new Bundle(); mPreviewIntent = new Intent(); } /** * Send the Intent from an Activity with a custom request code * * @param activity Activity to receive result * @param requestCode requestCode for result */ public void start(@NonNull Activity activity, int requestCode) { activity.startActivityForResult(getIntent(activity), requestCode); } /** * Send the Intent with a custom request code * * @param fragment Fragment to receive result * @param requestCode requestCode for result */ public void start(@NonNull Context context, @NonNull android.support.v4.app.Fragment fragment, int requestCode) { fragment.startActivityForResult(getIntent(context), requestCode); } /** * Send the Intent with a custom request code * * @param fragment Fragment to receive result */ public void start(@NonNull Context context, @NonNull android.support.v4.app.Fragment fragment) { fragment.startActivityForResult(getIntent(context), REQUEST_CODE); } /** * Send the crop Intent from an Activity * * @param activity Activity to receive result */ public void start(@NonNull Activity activity) { start(activity, REQUEST_CODE); } /** * Get Intent to start {@link PhotoPickerActivity} * * @return Intent for {@link PhotoPickerActivity} */ public Intent getIntent(@NonNull Context context) { mPreviewIntent.setClass(context, PhotoPagerActivity.class); mPreviewIntent.putExtras(mPreviewOptionsBundle); return mPreviewIntent; } public PhotoPreviewBuilder setPhotos(ArrayList<String> photoPaths) { mPreviewOptionsBundle.putStringArrayList(EXTRA_PHOTOS, photoPaths); return this; } public PhotoPreviewBuilder setCurrentItem(int currentItem) { mPreviewOptionsBundle.putInt(EXTRA_CURRENT_ITEM, currentItem); return this; } public PhotoPreviewBuilder setShowDeleteButton(boolean showDeleteButton) { mPreviewOptionsBundle.putBoolean(EXTRA_SHOW_DELETE, showDeleteButton); return this; } } }
{ "content_hash": "b40e634c15c567f83698ae44d147b503", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 117, "avg_line_length": 29.752475247524753, "alnum_prop": 0.7024958402662229, "repo_name": "donglua/PhotoPicker", "id": "adb5131b07a25eeb3cf6890111e1506f5c537587", "size": "3005", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "PhotoPicker/src/main/java/me/iwf/photopicker/PhotoPreview.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "114945" }, { "name": "Shell", "bytes": "464" } ], "symlink_target": "" }
Custom Database Tables ======================= Agents are allowed to write their own custom output into the database during simulations. The interface for recording this data is accessible through the agent's :term:`context`. Data may be logged via the Context::NewDatum function: .. code-block:: c++ MyReactor::Tick() { ... double monthly_water = ...; double monthly_op_cost = ...; context()->NewDatum("MyReactorData") ->AddVal("AgentID", id()) ->AddVal("Time", context()->time()) ->AddVal("WaterUsage", monthl_water) ->AddVal("OperatingCost", monthly_op_cost) ->Record(); ... } This would create a table in the output database named "MyReactorData". The table would get a new row entry every time step with four columns named "AgentID", "Time", "WaterUsage" and "OperatingCost". ``AddVal`` calls can be chained any number of times for an arbitrary number of columns. ``Record`` must be called once for each datum after all values have been added. Any custom tables created in this manner will appear in the output database alongside the |cyclus| core tables. Because there may be several agent instances of a single agent class, tables should generally include a column that adds their ID; and for similar reasons, it is often desirable to include the simulation time as a column in these tables: .. code-block:: c++ context()->NewDatum("MyReactorData") ->AddVal("AgentID", id()) ->AddVal("Time", context()->time()) ->AddVal(... ... Datums with the same table name must have the same schema (e.g. same field names and value types). It is the responsibility of the developer to enforce this in their code. .. warning:: Database formats only support a finite number of datum value-types. Do not add values to database tables that are not supported by the backend(s) in use. For information on which c++ types the backends support, you can check :doc:`here <dbtypes>`. .. note:: If you require a datatype that isn't currently supported, please ask the kernel developers and they will help as soon as possible. Table Data Shapes ------------------ All added values can optionally take a `std::vector<int>*` shape argument that is used as maximum dimensions for the value being added. The :doc:`dbtypes` page lists the rank of the shape of different C++ types. A ``std::vector<std::string>`` has rank two - the first shape element being the length of the vector, the second element being the length of each string in the vector. When the shape argument is ommitted, the default is to treat all elements in the value as variable-length. An entry of `-1` in the shape vector indicates variable length also. It is an error to pass in a shape vector with the wrong rank (number of elements) for that type. An example of using the shape vector follows: .. code-block:: c++ std::vector<std::string> colors; colors.push_back("green"); colors.push_back("blue"); colors.push_back("chartreuse"); std::vector<int> shape; // this should usually be a class member variable shape->push_back(5); // maximum number of elements in the color vector shape->push_back(8); // maximum character length of each color context()->NewDatum("DecorPreferences") ->AddVal("AgentID", id()) ->AddVal("Time", context()->time()) ->AddVal("FavoritColors", colors, shape) ->Record(); In the example above, the "chartreuse" color is longer than the 8 characters specified in the shape. So it will be truncated to "chartreu" in the database. Shape vectors should generally be stored as class member variables to avoid excessive memory [de]allocation and should be set correctly from construction to destruction of your agent. Reserved Table Names --------------------- The |cyclus| kernel creates several of its own tables. The names of these tables are reserved, and you are responsible to avoid using them for custom table names. The reserved table names are (all case combos upper and lower): * all names starting with the prefixes: * Cyclus * Agent * VL\ _ * Pair * String * Vector * Map * List * Set * Blob * Resources * Products * Transactions * Info * Finish * InputFiles * Prototypes * Recipes * Snapshots * MaterialInfo * Compositions * NextIds * ResCreators * CommodPriority .. warning:: Table names may only contain alphanumeric characters and underscores and must not start with a number.
{ "content_hash": "dd0949af7e9b1fffcd87548bb04ac697", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 85, "avg_line_length": 34.38059701492537, "alnum_prop": 0.688951595398307, "repo_name": "rwcarlsen/cyclus.github.com", "id": "5063f70c1f19b7bbb8ea8657b25aefd04bd98ee0", "size": "4608", "binary": false, "copies": "3", "ref": "refs/heads/source", "path": "source/arche/custom_tables.rst", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "4576" }, { "name": "HTML", "bytes": "2692" }, { "name": "JavaScript", "bytes": "8501" }, { "name": "Makefile", "bytes": "9197" }, { "name": "Python", "bytes": "144751" }, { "name": "TeX", "bytes": "13885" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_29) on Mon Nov 26 17:21:43 MSK 2012 --> <TITLE> Uses of Class org.apache.poi.hpsf.UnexpectedPropertySetTypeException (POI API Documentation) </TITLE> <META NAME="date" CONTENT="2012-11-26"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.poi.hpsf.UnexpectedPropertySetTypeException (POI API Documentation)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/poi/hpsf/UnexpectedPropertySetTypeException.html" title="class in org.apache.poi.hpsf"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/poi/hpsf/\class-useUnexpectedPropertySetTypeException.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="UnexpectedPropertySetTypeException.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.poi.hpsf.UnexpectedPropertySetTypeException</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../org/apache/poi/hpsf/UnexpectedPropertySetTypeException.html" title="class in org.apache.poi.hpsf">UnexpectedPropertySetTypeException</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.poi.hpsf"><B>org.apache.poi.hpsf</B></A></TD> <TD><div>&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.poi.hpsf"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../org/apache/poi/hpsf/UnexpectedPropertySetTypeException.html" title="class in org.apache.poi.hpsf">UnexpectedPropertySetTypeException</A> in <A HREF="../../../../../org/apache/poi/hpsf/package-summary.html">org.apache.poi.hpsf</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Constructors in <A HREF="../../../../../org/apache/poi/hpsf/package-summary.html">org.apache.poi.hpsf</A> that throw <A HREF="../../../../../org/apache/poi/hpsf/UnexpectedPropertySetTypeException.html" title="class in org.apache.poi.hpsf">UnexpectedPropertySetTypeException</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../org/apache/poi/hpsf/DocumentSummaryInformation.html#DocumentSummaryInformation(org.apache.poi.hpsf.PropertySet)">DocumentSummaryInformation</A></B>(<A HREF="../../../../../org/apache/poi/hpsf/PropertySet.html" title="class in org.apache.poi.hpsf">PropertySet</A>&nbsp;ps)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Creates a <A HREF="../../../../../org/apache/poi/hpsf/DocumentSummaryInformation.html" title="class in org.apache.poi.hpsf"><CODE>DocumentSummaryInformation</CODE></A> from a given <A HREF="../../../../../org/apache/poi/hpsf/PropertySet.html" title="class in org.apache.poi.hpsf"><CODE>PropertySet</CODE></A>.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../org/apache/poi/hpsf/SummaryInformation.html#SummaryInformation(org.apache.poi.hpsf.PropertySet)">SummaryInformation</A></B>(<A HREF="../../../../../org/apache/poi/hpsf/PropertySet.html" title="class in org.apache.poi.hpsf">PropertySet</A>&nbsp;ps)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Creates a <A HREF="../../../../../org/apache/poi/hpsf/SummaryInformation.html" title="class in org.apache.poi.hpsf"><CODE>SummaryInformation</CODE></A> from a given <A HREF="../../../../../org/apache/poi/hpsf/PropertySet.html" title="class in org.apache.poi.hpsf"><CODE>PropertySet</CODE></A>.</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/poi/hpsf/UnexpectedPropertySetTypeException.html" title="class in org.apache.poi.hpsf"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/poi/hpsf/\class-useUnexpectedPropertySetTypeException.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="UnexpectedPropertySetTypeException.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright 2012 The Apache Software Foundation or its licensors, as applicable.</i> </BODY> </HTML>
{ "content_hash": "37c8b71636e059723d9e5d5a0301ee6d", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 358, "avg_line_length": 49.5531914893617, "alnum_prop": 0.6292400171747531, "repo_name": "HRKN2245/CameraSunmoku", "id": "a4fc8a12f8324d031779bf78aac6f55eb572c523", "size": "9316", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ExtractSample/poi-3.9/docs/apidocs/org/apache/poi/hpsf/class-use/UnexpectedPropertySetTypeException.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "16091" }, { "name": "Java", "bytes": "126912" } ], "symlink_target": "" }
package com.dianping.cat.transaction; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.Assert; import org.junit.Test; import org.unidal.helper.Files; import com.dianping.cat.core.dal.Graph; import com.dianping.cat.transaction.Handler.DetailOrder; import com.dianping.cat.transaction.Handler.SummaryOrder; import com.dianping.cat.transaction.model.entity.TransactionReport; import com.dianping.cat.transaction.model.transform.DefaultSaxParser; import com.dianping.cat.transaction.task.TransactionGraphCreator; public class TransactionGraphCreatorTest { @Test public void testSplitReportToGraphs() throws Exception { TransactionGraphCreator creator = new TransactionGraphCreator(); String xml = Files.forIO().readFrom(getClass().getResourceAsStream("BaseTransactionReportForGraph.xml"), "utf-8"); TransactionReport report = DefaultSaxParser.parse(xml); List<Graph> graphs = creator.splitReportToGraphs(report.getStartTime(), report.getDomain(), "transaction", report); Map<String, Range> realResult = new HashMap<String, Range>(); Map<String, Range> excepectedResult = buildExcepetedResult(); buildRealResult(graphs, realResult); Assert.assertEquals(excepectedResult.size(),realResult.size()); for (String str : realResult.keySet()) { Range realRange = realResult.get(str); Range exceptedRange = excepectedResult.get(str); assertStr(realRange.total, exceptedRange.total); assertStr(realRange.fail, exceptedRange.fail); assertStr(realRange.sum, exceptedRange.sum); } } private void assertStr(String expected, String real) { String[] expecteds = expected.split(","); String[] reals = real.split(","); Assert.assertEquals(expecteds.length, reals.length); for (int i = 0; i < expecteds.length; i++) { Assert.assertEquals(Double.parseDouble(expecteds[i]), Double.parseDouble(reals[i])); } } private Map<String, Range> buildExcepetedResult() throws Exception { Map<String, Range> result = new HashMap<String, Range>(); String contents = Files.forIO().readFrom(getClass().getResourceAsStream("TransactionGraphResult"), "utf-8"); String[] lines = contents.split("\n"); for (String line : lines) { String[] tabs = line.split("\t"); if (tabs.length > 3) { Range range = new Range(); range.total = tabs[1]; range.sum = tabs[2]; range.fail = tabs[3]; result.put(tabs[0], range); } } return result; } private void buildRealResult(List<Graph> graphs, Map<String, Range> realResult) { for (Graph graph : graphs) { String ip = graph.getIp(); String summaryContent = graph.getSummaryContent(); String lines[] = summaryContent.split("\n"); for (String line : lines) { String records[] = line.split("\t"); String type = records[0]; Range range = new Range(); range.total = records[SummaryOrder.TOTAL_COUNT.ordinal()]; range.fail = records[SummaryOrder.FAILURE_COUNT.ordinal()]; range.sum = records[SummaryOrder.SUM.ordinal()]; String key = ip + ':' + type; realResult.put(key, range); } String detailContent = graph.getDetailContent(); lines = detailContent.split("\n"); for (String line : lines) { String records[] = line.split("\t"); String type = records[0]; String name = records[1]; Range range = new Range(); range.total = records[DetailOrder.TOTAL_COUNT.ordinal()]; range.fail = records[DetailOrder.FAILURE_COUNT.ordinal()]; range.sum = records[DetailOrder.SUM.ordinal()]; realResult.put(ip + ':' + type + ':' + name, range); } } } private static class Range { public String total; public String fail; public String sum; } }
{ "content_hash": "cc87457958155fe49ee3d1a138b03a37", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 117, "avg_line_length": 33.788990825688074, "alnum_prop": 0.710019006244909, "repo_name": "unidal/cat", "id": "df7efaefabb16f7e145fd2f41bf00749e3393f49", "size": "3683", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "report-transaction/src/test/java/com/dianping/cat/transaction/TransactionGraphCreatorTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "11263" }, { "name": "CSS", "bytes": "1550279" }, { "name": "HTML", "bytes": "11727" }, { "name": "Java", "bytes": "4182790" }, { "name": "JavaScript", "bytes": "3067745" }, { "name": "Python", "bytes": "11726" }, { "name": "Shell", "bytes": "33894" } ], "symlink_target": "" }