repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
merhawifissehaye/dreamfactory-configured
|
resources/views/emails/invite.blade.php
|
912
|
@extends('emails.layout')
{{--
This is an email blade for resetting password
The following view data is required:
$contentHeader The callout/header of the email's body
$firstName The name of the recipient.
$link The password reset link.
$code The reset code.
$instanceName Name of the DreamFactory Instance.
--}}
@section('contentBody')
<div style="padding: 10px;">
<p>
Hi {{ $firstName }},
</p>
<div>
You have been invited to the DreamFactory Instance of {{ $instanceName }}. Go to the following url, enter the code below, and set your password to confirm your account.<br/>
<br/>
{{ $link }}
<br/><br/>
Confirmation Code: {{ $code }}<br/>
</div>
<p>
<cite>-- The Dream Team</cite>
</p>
</div>
@stop
|
apache-2.0
|
mackeprm/cuneiform
|
cuneiform-core/src/main/java/de/huberlin/wbi/cuneiform/core/cre/TicketReadyMsg.java
|
2394
|
/*******************************************************************************
* In the Hi-WAY project we propose a novel approach of executing scientific
* workflows processing Big Data, as found in NGS applications, on distributed
* computational infrastructures. The Hi-WAY software stack comprises the func-
* tional workflow language Cuneiform as well as the Hi-WAY ApplicationMaster
* for Apache Hadoop 2.x (YARN).
*
* List of Contributors:
*
* Jörgen Brandt (HU Berlin)
* Marc Bux (HU Berlin)
* Ulf Leser (HU Berlin)
*
* Jörgen Brandt is funded by the European Commission through the BiobankCloud
* project. Marc Bux is funded by the Deutsche Forschungsgemeinschaft through
* research training group SOAMED (GRK 1651).
*
* Copyright 2014 Humboldt-Universität zu Berlin
*
* 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 de.huberlin.wbi.cuneiform.core.cre;
import java.util.UUID;
import de.huberlin.wbi.cuneiform.core.actormodel.Actor;
import de.huberlin.wbi.cuneiform.core.actormodel.Message;
import de.huberlin.wbi.cuneiform.core.semanticmodel.Ticket;
public class TicketReadyMsg extends Message {
private final UUID queryId;
private final Ticket ticket;
public TicketReadyMsg( Actor sender, UUID queryId, Ticket ticket ) {
super( sender );
if( ticket == null )
throw new NullPointerException( "Ticket set must not be null." );
if( queryId == null )
throw new NullPointerException( "Run ID must not be null." );
this.queryId = queryId;
this.ticket = ticket;
}
public UUID getQueryId() {
return queryId;
}
public Ticket getTicket() {
return ticket;
}
@Override
public String toString() {
return "{ ticketReady, \""+queryId+"\", "+ticket.getTicketId()+", \""+ticket.toString().replace( '\n', ' ' )+"\" }";
}
}
|
apache-2.0
|
ReactiveX/RxJava
|
src/main/java/io/reactivex/rxjava3/observers/BaseTestConsumer.java
|
22394
|
/*
* Copyright (c) 2016-present, RxJava Contributors.
*
* 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 io.reactivex.rxjava3.observers;
import java.util.*;
import java.util.concurrent.*;
import io.reactivex.rxjava3.annotations.*;
import io.reactivex.rxjava3.exceptions.CompositeException;
import io.reactivex.rxjava3.functions.Predicate;
import io.reactivex.rxjava3.internal.functions.Functions;
import io.reactivex.rxjava3.internal.util.*;
/**
* Base class with shared infrastructure to support
* {@link io.reactivex.rxjava3.subscribers.TestSubscriber TestSubscriber} and {@link TestObserver}.
* @param <T> the value type consumed
* @param <U> the subclass of this {@code BaseTestConsumer}
*/
public abstract class BaseTestConsumer<T, U extends BaseTestConsumer<T, U>> {
/** The latch that indicates an onError or onComplete has been called. */
protected final CountDownLatch done;
/** The list of values received. */
protected final List<T> values;
/** The list of errors received. */
protected final List<Throwable> errors;
/** The number of completions. */
protected long completions;
/** The last thread seen by the observer. */
protected Thread lastThread;
protected boolean checkSubscriptionOnce;
/**
* The optional tag associated with this test consumer.
* @since 2.0.7
*/
protected CharSequence tag;
/**
* Indicates that one of the {@code awaitX} method has timed out.
* @since 2.0.7
*/
protected boolean timeout;
/**
* Constructs a {@code BaseTestConsumer} with {@code CountDownLatch} set to 1.
*/
public BaseTestConsumer() {
this.values = new VolatileSizeArrayList<>();
this.errors = new VolatileSizeArrayList<>();
this.done = new CountDownLatch(1);
}
/**
* Returns a shared list of received {@code onNext} values or the single {@code onSuccess} value.
* <p>
* Note that accessing the items via certain methods of the {@link List}
* interface while the upstream is still actively emitting
* more items may result in a {@code ConcurrentModificationException}.
* <p>
* The {@link List#size()} method will return the number of items
* already received by this {@code TestObserver}/{@code TestSubscriber} in a thread-safe
* manner that can be read via {@link List#get(int)}) method
* (index range of 0 to {@code List.size() - 1}).
* <p>
* A view of the returned List can be created via {@link List#subList(int, int)}
* by using the bounds 0 (inclusive) to {@link List#size()} (exclusive) which,
* when accessed in a read-only fashion, should be also thread-safe and not throw any
* {@code ConcurrentModificationException}.
* @return a list of received onNext values
*/
@NonNull
public final List<T> values() {
return values;
}
/**
* Fail with the given message and add the sequence of errors as suppressed ones.
* <p>Note this is deliberately the only fail method. Most of the times an assertion
* would fail but it is possible it was due to an exception somewhere. This construct
* will capture those potential errors and report it along with the original failure.
*
* @param message the message to use
* @return AssertionError the prepared AssertionError instance
*/
@NonNull
protected final AssertionError fail(@NonNull String message) {
StringBuilder b = new StringBuilder(64 + message.length());
b.append(message);
b.append(" (")
.append("latch = ").append(done.getCount()).append(", ")
.append("values = ").append(values.size()).append(", ")
.append("errors = ").append(errors.size()).append(", ")
.append("completions = ").append(completions)
;
if (timeout) {
b.append(", timeout!");
}
if (isDisposed()) {
b.append(", disposed!");
}
CharSequence tag = this.tag;
if (tag != null) {
b.append(", tag = ")
.append(tag);
}
b
.append(')')
;
AssertionError ae = new AssertionError(b.toString());
if (!errors.isEmpty()) {
if (errors.size() == 1) {
ae.initCause(errors.get(0));
} else {
CompositeException ce = new CompositeException(errors);
ae.initCause(ce);
}
}
return ae;
}
/**
* Awaits until this {@code TestObserver}/{@code TestSubscriber} receives an {@code onError} or {@code onComplete} events.
* @return this
* @throws InterruptedException if the current thread is interrupted while waiting
*/
@SuppressWarnings("unchecked")
@NonNull
public final U await() throws InterruptedException {
if (done.getCount() == 0) {
return (U)this;
}
done.await();
return (U)this;
}
/**
* Awaits the specified amount of time or until this {@code TestObserver}/{@code TestSubscriber}
* receives an {@code onError} or {@code onComplete} events, whichever happens first.
* @param time the waiting time
* @param unit the time unit of the waiting time
* @return true if the {@code TestObserver}/{@code TestSubscriber} terminated, false if timeout happened
* @throws InterruptedException if the current thread is interrupted while waiting
*/
public final boolean await(long time, @NonNull TimeUnit unit) throws InterruptedException {
boolean d = done.getCount() == 0 || (done.await(time, unit));
timeout = !d;
return d;
}
// assertion methods
/**
* Assert that this {@code TestObserver}/{@code TestSubscriber} received exactly one {@code onComplete} event.
* @return this
*/
@SuppressWarnings("unchecked")
@NonNull
public final U assertComplete() {
long c = completions;
if (c == 0) {
throw fail("Not completed");
} else
if (c > 1) {
throw fail("Multiple completions: " + c);
}
return (U)this;
}
/**
* Assert that this {@code TestObserver}/{@code TestSubscriber} has not received an {@code onComplete} event.
* @return this
*/
@SuppressWarnings("unchecked")
@NonNull
public final U assertNotComplete() {
long c = completions;
if (c == 1) {
throw fail("Completed!");
} else
if (c > 1) {
throw fail("Multiple completions: " + c);
}
return (U)this;
}
/**
* Assert that this {@code TestObserver}/{@code TestSubscriber} has not received an {@code onError} event.
* @return this
*/
@SuppressWarnings("unchecked")
@NonNull
public final U assertNoErrors() {
int s = errors.size();
if (s != 0) {
throw fail("Error(s) present: " + errors);
}
return (U)this;
}
/**
* Assert that this {@code TestObserver}/{@code TestSubscriber} received exactly the specified {@code onError} event value.
*
* <p>The comparison is performed via {@link Objects#equals(Object, Object)}; since most exceptions don't
* implement equals(), this assertion may fail. Use the {@link #assertError(Class)}
* overload to test against the class of an error instead of an instance of an error
* or {@link #assertError(Predicate)} to test with different condition.
* @param error the error to check
* @return this
* @see #assertError(Class)
* @see #assertError(Predicate)
*/
@NonNull
public final U assertError(@NonNull Throwable error) {
return assertError(Functions.equalsWith(error), true);
}
/**
* Asserts that this {@code TestObserver}/{@code TestSubscriber} received exactly one {@code onError} event which is an
* instance of the specified {@code errorClass} {@link Class}.
* @param errorClass the error {@code Class} to expect
* @return this
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@NonNull
public final U assertError(@NonNull Class<? extends Throwable> errorClass) {
return (U)assertError((Predicate)Functions.isInstanceOf(errorClass), true);
}
/**
* Asserts that this {@code TestObserver}/{@code TestSubscriber} received exactly one {@code onError} event for which
* the provided predicate returns {@code true}.
* @param errorPredicate
* the predicate that receives the error {@link Throwable}
* and should return {@code true} for expected errors.
* @return this
*/
@NonNull
public final U assertError(@NonNull Predicate<Throwable> errorPredicate) {
return assertError(errorPredicate, false);
}
@SuppressWarnings("unchecked")
@NonNull
private U assertError(@NonNull Predicate<Throwable> errorPredicate, boolean exact) {
int s = errors.size();
if (s == 0) {
throw fail("No errors");
}
boolean found = false;
for (Throwable e : errors) {
try {
if (errorPredicate.test(e)) {
found = true;
break;
}
} catch (Throwable ex) {
throw ExceptionHelper.wrapOrThrow(ex);
}
}
if (found) {
if (s != 1) {
if (exact) {
throw fail("Error present but other errors as well");
}
throw fail("One error passed the predicate but other errors are present as well");
}
} else {
if (exact) {
throw fail("Error not present");
}
throw fail("No error(s) passed the predicate");
}
return (U)this;
}
/**
* Assert that this {@code TestObserver}/{@code TestSubscriber} received exactly one {@code onNext} value which is equal to
* the given value with respect to {@link Objects#equals(Object, Object)}.
* @param value the value to expect
* @return this
*/
@SuppressWarnings("unchecked")
@NonNull
public final U assertValue(@NonNull T value) {
int s = values.size();
if (s != 1) {
throw fail("\nexpected: " + valueAndClass(value) + "\ngot: " + values);
}
T v = values.get(0);
if (!Objects.equals(value, v)) {
throw fail("\nexpected: " + valueAndClass(value) + "\ngot: " + valueAndClass(v));
}
return (U)this;
}
/**
* Asserts that this {@code TestObserver}/{@code TestSubscriber} received exactly one {@code onNext} value for which
* the provided predicate returns {@code true}.
* @param valuePredicate
* the predicate that receives the {@code onNext} value
* and should return {@code true} for the expected value.
* @return this
*/
@SuppressWarnings("unchecked")
@NonNull
public final U assertValue(@NonNull Predicate<T> valuePredicate) {
assertValueAt(0, valuePredicate);
if (values.size() > 1) {
throw fail("The first value passed the predicate but this consumer received more than one value");
}
return (U)this;
}
/**
* Asserts that this {@code TestObserver}/{@code TestSubscriber} received an {@code onNext} value at the given index
* which is equal to the given value with respect to {@code null}-safe {@link Objects#equals(Object, Object)}.
* <p>History: 2.1.3 - experimental
* @param index the position to assert on
* @param value the value to expect
* @return this
* @since 2.2
*/
@SuppressWarnings("unchecked")
@NonNull
public final U assertValueAt(int index, @NonNull T value) {
int s = values.size();
if (s == 0) {
throw fail("No values");
}
if (index < 0 || index >= s) {
throw fail("Index " + index + " is out of range [0, " + s + ")");
}
T v = values.get(index);
if (!Objects.equals(value, v)) {
throw fail("\nexpected: " + valueAndClass(value) + "\ngot: " + valueAndClass(v)
+ "; Value at position " + index + " differ");
}
return (U)this;
}
/**
* Asserts that this {@code TestObserver}/{@code TestSubscriber} received an {@code onNext} value at the given index
* for the provided predicate returns {@code true}.
* @param index the position to assert on
* @param valuePredicate
* the predicate that receives the {@code onNext} value
* and should return {@code true} for the expected value.
* @return this
*/
@SuppressWarnings("unchecked")
@NonNull
public final U assertValueAt(int index, @NonNull Predicate<T> valuePredicate) {
int s = values.size();
if (s == 0) {
throw fail("No values");
}
if (index < 0 || index >= s) {
throw fail("Index " + index + " is out of range [0, " + s + ")");
}
boolean found = false;
T v = values.get(index);
try {
if (valuePredicate.test(v)) {
found = true;
}
} catch (Throwable ex) {
throw ExceptionHelper.wrapOrThrow(ex);
}
if (!found) {
throw fail("Value " + valueAndClass(v) + " at position " + index + " did not pass the predicate");
}
return (U)this;
}
/**
* Appends the class name to a non-{@code null} value or returns {@code "null"}.
* @param o the object
* @return the string representation
*/
@NonNull
public static String valueAndClass(@Nullable Object o) {
if (o != null) {
return o + " (class: " + o.getClass().getSimpleName() + ")";
}
return "null";
}
/**
* Assert that this {@code TestObserver}/{@code TestSubscriber} received the specified number {@code onNext} events.
* @param count the expected number of {@code onNext} events
* @return this
*/
@SuppressWarnings("unchecked")
@NonNull
public final U assertValueCount(int count) {
int s = values.size();
if (s != count) {
throw fail("\nexpected: " + count + "\ngot: " + s + "; Value counts differ");
}
return (U)this;
}
/**
* Assert that this {@code TestObserver}/{@code TestSubscriber} has not received any {@code onNext} events.
* @return this
*/
@NonNull
public final U assertNoValues() {
return assertValueCount(0);
}
/**
* Assert that the {@code TestObserver}/{@code TestSubscriber} received only the specified values in the specified order.
* @param values the values expected
* @return this
*/
@SuppressWarnings("unchecked")
@SafeVarargs
@NonNull
public final U assertValues(@NonNull T... values) {
int s = this.values.size();
if (s != values.length) {
throw fail("\nexpected: " + values.length + " " + Arrays.toString(values)
+ "\ngot: " + s + " " + this.values + "; Value count differs");
}
for (int i = 0; i < s; i++) {
T v = this.values.get(i);
T u = values[i];
if (!Objects.equals(u, v)) {
throw fail("\nexpected: " + valueAndClass(u) + "\ngot: " + valueAndClass(v)
+ "; Value at position " + i + " differ");
}
}
return (U)this;
}
/**
* Assert that the {@code TestObserver}/{@code TestSubscriber} received only the specified values in the specified order without terminating.
* <p>History: 2.1.4 - experimental
* @param values the values expected
* @return this
* @since 2.2
*/
@SafeVarargs
@NonNull
public final U assertValuesOnly(@NonNull T... values) {
return assertSubscribed()
.assertValues(values)
.assertNoErrors()
.assertNotComplete();
}
/**
* Assert that the {@code TestObserver}/{@code TestSubscriber} received only the specified sequence of values in the same order.
* @param sequence the sequence of expected values in order
* @return this
*/
@SuppressWarnings("unchecked")
@NonNull
public final U assertValueSequence(@NonNull Iterable<? extends T> sequence) {
int i = 0;
Iterator<T> actualIterator = values.iterator();
Iterator<? extends T> expectedIterator = sequence.iterator();
boolean actualNext;
boolean expectedNext;
for (;;) {
expectedNext = expectedIterator.hasNext();
actualNext = actualIterator.hasNext();
if (!actualNext || !expectedNext) {
break;
}
T u = expectedIterator.next();
T v = actualIterator.next();
if (!Objects.equals(u, v)) {
throw fail("\nexpected: " + valueAndClass(u) + "\ngot: " + valueAndClass(v)
+ "; Value at position " + i + " differ");
}
i++;
}
if (actualNext) {
throw fail("More values received than expected (" + i + ")");
}
if (expectedNext) {
throw fail("Fewer values received than expected (" + i + ")");
}
return (U)this;
}
/**
* Assert that the {@code onSubscribe} method was called exactly once.
* @return this
*/
@NonNull
protected abstract U assertSubscribed();
/**
* Assert that the upstream signaled the specified values in order and
* completed normally.
* @param values the expected values, asserted in order
* @return this
* @see #assertFailure(Class, Object...)
*/
@SafeVarargs
@NonNull
public final U assertResult(@NonNull T... values) {
return assertSubscribed()
.assertValues(values)
.assertNoErrors()
.assertComplete();
}
/**
* Assert that the upstream signaled the specified values in order
* and then failed with a specific class or subclass of {@link Throwable}.
* @param error the expected exception (parent) {@link Class}
* @param values the expected values, asserted in order
* @return this
*/
@SafeVarargs
@NonNull
public final U assertFailure(@NonNull Class<? extends Throwable> error, @NonNull T... values) {
return assertSubscribed()
.assertValues(values)
.assertError(error)
.assertNotComplete();
}
/**
* Awaits until the internal latch is counted down.
* <p>If the wait times out or gets interrupted, the {@code TestObserver}/{@code TestSubscriber} is cancelled.
* @param time the waiting time
* @param unit the time unit of the waiting time
* @return this
* @throws RuntimeException wrapping an {@link InterruptedException} if the wait is interrupted
*/
@SuppressWarnings("unchecked")
@NonNull
public final U awaitDone(long time, @NonNull TimeUnit unit) {
try {
if (!done.await(time, unit)) {
timeout = true;
dispose();
}
} catch (InterruptedException ex) {
dispose();
throw ExceptionHelper.wrapOrThrow(ex);
}
return (U)this;
}
/**
* Assert that the {@code TestObserver}/{@code TestSubscriber} has received a
* {@link io.reactivex.rxjava3.disposables.Disposable Disposable}/{@link org.reactivestreams.Subscription Subscription}
* via {@code onSubscribe} but no other events.
* @return this
*/
@NonNull
public final U assertEmpty() {
return assertSubscribed()
.assertNoValues()
.assertNoErrors()
.assertNotComplete();
}
/**
* Set the tag displayed along with an assertion failure's
* other state information.
* <p>History: 2.0.7 - experimental
* @param tag the string to display ({@code null} won't print any tag)
* @return this
* @since 2.1
*/
@SuppressWarnings("unchecked")
@NonNull
public final U withTag(@Nullable CharSequence tag) {
this.tag = tag;
return (U)this;
}
/**
* Await until the {@code TestObserver}/{@code TestSubscriber} receives the given
* number of items or terminates by sleeping 10 milliseconds at a time
* up to 5000 milliseconds of timeout.
* <p>History: 2.0.7 - experimental
* @param atLeast the number of items expected at least
* @return this
* @since 2.1
*/
@SuppressWarnings("unchecked")
@NonNull
public final U awaitCount(int atLeast) {
long start = System.currentTimeMillis();
long timeoutMillis = 5000;
for (;;) {
if (System.currentTimeMillis() - start >= timeoutMillis) {
timeout = true;
break;
}
if (done.getCount() == 0L) {
break;
}
if (values.size() >= atLeast) {
break;
}
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
return (U)this;
}
/**
* Returns true if this test consumer was cancelled/disposed.
* @return true if this test consumer was cancelled/disposed.
*/
protected abstract boolean isDisposed();
/**
* Cancel/dispose this test consumer.
*/
protected abstract void dispose();
}
|
apache-2.0
|
Sage/carbon
|
src/components/tabs/__internal__/tab-title/index.d.ts
|
39
|
export { default } from "./tab-title";
|
apache-2.0
|
MICommunity/psi-jami
|
jami-core/src/main/java/psidev/psi/mi/jami/datasource/InteractionEvidenceSource.java
|
532
|
package psidev.psi.mi.jami.datasource;
import psidev.psi.mi.jami.model.InteractionEvidence;
/**
* A Data source of interaction evidences.
* It gives full access to all the interactions using Iterator or the full collection.
* It can also give information about the size of the dataSource
*
* @author Marine Dumousseau ([email protected])
* @version $Id$
* @since <pre>08/11/13</pre>
*/
public interface InteractionEvidenceSource<T extends InteractionEvidence> extends InteractionEvidenceStream<T>, InteractionSource<T> {
}
|
apache-2.0
|
bigbugbb/PrayerPartner
|
app/src/main/java/com/bigbug/android/pp/sync/EventFeedbackApi.java
|
2202
|
package com.bigbug.android.pp.sync;
import android.content.Context;
import com.bigbug.android.pp.Config;
import java.util.List;
import static com.bigbug.android.pp.util.LogUtils.makeLogTag;
public class EventFeedbackApi {
private static final String TAG = makeLogTag(EventFeedbackApi.class);
private static final String PARAMETER_EVENT_CODE = "code";
private static final String PARAMETER_API_KEY = "apikey";
private static final String PARAMETER_SESSION_ID = "objectid";
private static final String PARAMETER_SURVEY_ID = "surveyId";
private static final String PARAMETER_REGISTRANT_ID = "registrantKey";
private final Context mContext;
private final String mUrl;
public EventFeedbackApi(Context context) {
mContext = context;
mUrl = Config.FEEDBACK_URL;
}
/**
* Posts a session to the event server.
*
* @param sessionId The ID of the session that was reviewed.
* @return whether or not updating succeeded
*/
public boolean sendSessionToServer(String sessionId, List<String> questions) {
// BasicHttpClient httpClient = new BasicHttpClient();
// httpClient.addHeader(PARAMETER_EVENT_CODE, Config.FEEDBACK_API_CODE);
// httpClient.addHeader(PARAMETER_API_KEY, Config.FEEDBACK_API_KEY);
//
// ParameterMap parameterMap = httpClient.newParams();
// parameterMap.add(PARAMETER_SESSION_ID, sessionId);
// parameterMap.add(PARAMETER_SURVEY_ID, Config.FEEDBACK_SURVEY_ID);
// parameterMap.add(PARAMETER_REGISTRANT_ID, Config.FEEDBACK_DUMMY_REGISTRANT_ID);
// int i = 1;
// for (String question : questions) {
// parameterMap.add("q" + i, question);
// i++;
// }
//
// HttpResponse response = httpClient.get(mUrl, parameterMap);
//
// if (response != null && response.getStatus() == HttpURLConnection.HTTP_OK) {
// LOGD(TAG, "Server returned HTTP_OK, so session posting was successful.");
// return true;
// } else {
// LOGE(TAG, "Error posting session: HTTP status " + response.getStatus());
// return false;
// }
return false;
}
}
|
apache-2.0
|
firejack-open/Firejack-Platform
|
platform/src/main/webapp/js/net/firejack/platform/core/validation/MessageLevel.js
|
1875
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
Ext.namespace('OPF.core.validation');
Ext.define('OPF.core.validation.MessageLevel', {
constructor: function(level, css, cfg) {
cfg = cfg || {};
OPF.core.validation.MessageLevel.superclass.constructor.call(this, cfg);
this.level = level;
this.css = css;
},
getLevel: function() {
return this.level;
},
getCSS: function() {
return this.css;
}
});
OPF.core.validation.MessageLevel.TRACE = new OPF.core.validation.MessageLevel('TRACE', 'msg-trace');
OPF.core.validation.MessageLevel.DEBUG = new OPF.core.validation.MessageLevel('DEBUG', 'msg-debug');
OPF.core.validation.MessageLevel.INFO = new OPF.core.validation.MessageLevel('INFO', 'msg-info');
OPF.core.validation.MessageLevel.WARN = new OPF.core.validation.MessageLevel('WARN', 'msg-warn');
OPF.core.validation.MessageLevel.ERROR = new OPF.core.validation.MessageLevel('ERROR', 'msg-error');
OPF.core.validation.MessageLevel.FATAL = new OPF.core.validation.MessageLevel('FATAL', 'msg-fatal');
|
apache-2.0
|
dimonahack/dimonahack.com
|
templates/gallery.html
|
627
|
{% extends "_layout.html" %}
{% block title %}גלריה{% endblock %}
{% block head %}
{{ super() }}
<link rel="stylesheet" type="text/css" href="/static/vendor/Facebook-Album-Browser/src/jquery.fb.albumbrowser.css" />
<script type="text/javascript" src="/static/vendor/Facebook-Album-Browser/src/jquery.fb.albumbrowser.js"></script>
{% endblock %}
{% block content %}
<div class="fb-album-container"></div>
<script type="text/javascript">
$(document).ready(function () {
$(".fb-album-container").FacebookAlbumBrowser({
account: "DimonaHack"
});
});
</script>
{% endblock %}
|
apache-2.0
|
mikosik/jsolid
|
src/junit/com/perunlabs/jsolid/TransformApiTest.java
|
1021
|
package com.perunlabs.jsolid;
import static com.perunlabs.jsolid.JSolid.cuboid;
import static com.perunlabs.jsolid.JSolid.degrees;
import static com.perunlabs.jsolid.JSolid.x;
import static com.perunlabs.jsolid.JSolid.y;
import static org.testory.Testory.any;
import static org.testory.Testory.given;
import static org.testory.Testory.spy;
import static org.testory.Testory.thenCalledNever;
import static org.testory.Testory.when;
import org.junit.Test;
import com.perunlabs.jsolid.d3.Matrix4;
import com.perunlabs.jsolid.d3.Vector3;
public class TransformApiTest {
private Matrix4 matrix;
private Matrix4 matrix2;
@Test
public void matrix_transforms_are_multiplied_and_result_matrix_is_applied() throws Exception {
given(matrix = spy(x().rotateMatrix(degrees(90))));
given(matrix2 = spy(y().rotateMatrix(degrees(90))));
when(cuboid(1, 2, 3).apply(matrix).apply(matrix).vertexes());
thenCalledNever(matrix).mul(any(Vector3.class));
thenCalledNever(matrix2).mul(any(Vector3.class));
}
}
|
apache-2.0
|
ederign/uberfire
|
uberfire-extensions/uberfire-wires/uberfire-wires-webapp/src/main/java/org/uberfire/ext/wires/shared/preferences/bean/MyPreference.java
|
2269
|
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.uberfire.ext.wires.shared.preferences.bean;
import org.uberfire.preferences.shared.PropertyFormType;
import org.uberfire.preferences.shared.annotations.Property;
import org.uberfire.preferences.shared.annotations.WorkbenchPreference;
import org.uberfire.preferences.shared.bean.BasePreference;
@WorkbenchPreference(identifier = "MyPreference",
bundleKey = "MyPreference.Label")
public class MyPreference implements BasePreference<MyPreference> {
@Property(bundleKey = "MyPreference.Text")
String text;
@Property(formType = PropertyFormType.BOOLEAN, bundleKey = "MyPreference.SendReports")
boolean sendReports;
@Property(formType = PropertyFormType.COLOR, bundleKey = "MyPreference.BackgroundColor")
String backgroundColor;
@Property(formType = PropertyFormType.NATURAL_NUMBER, bundleKey = "MyPreference.Age")
int age;
@Property(formType = PropertyFormType.SECRET_TEXT, bundleKey = "MyPreference.Password")
String password;
@Property(bundleKey = "MyPreference.MyInnerPreference")
MyInnerPreference myInnerPreference;
@Property(shared = true, bundleKey = "MyPreference.MySharedPreference")
MySharedPreference mySharedPreference;
@Override
public MyPreference defaultValue(final MyPreference defaultValue) {
defaultValue.text = "text";
defaultValue.sendReports = true;
defaultValue.backgroundColor = "ABCDEF";
defaultValue.age = 27;
defaultValue.password = "password";
defaultValue.myInnerPreference.text = "text";
defaultValue.mySharedPreference.text = "text";
return defaultValue;
}
}
|
apache-2.0
|
SimY4/xpath-to-xml
|
xpath-to-json-gson/src/jmh/java/com/github/simy4/xpath/GsonJsonBuilderBenchmark.java
|
1179
|
package com.github.simy4.xpath;
import com.github.simy4.xpath.fixtures.FixtureAccessor;
import com.google.gson.JsonObject;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import javax.xml.xpath.XPathExpressionException;
@BenchmarkMode(Mode.Throughput)
@State(Scope.Benchmark)
public class GsonJsonBuilderBenchmark {
@Param({ "attr", "simple", "special" })
public String fixtureName;
private FixtureAccessor fixtureAccessor;
@Setup
public void setUp() {
fixtureAccessor = new FixtureAccessor(fixtureName, "json");
}
@Benchmark
public void shouldBuildDocumentFromSetOfXPaths(Blackhole blackhole) throws XPathExpressionException {
var xmlProperties = fixtureAccessor.getXmlProperties();
blackhole.consume(new XmlBuilder()
.putAll(xmlProperties.keySet())
.build(new JsonObject()));
}
}
|
apache-2.0
|
qintengfei/ionic-site
|
_site/docs/nightly/api/service/$ionicScrollDelegate/index.html
|
42494
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Ionic makes it incredibly easy to build beautiful and interactive mobile apps using HTML5 and AngularJS.">
<meta name="keywords" content="html5,javascript,mobile,drifty,ionic,hybrid,phonegap,cordova,native,ios,android,angularjs">
<meta name="author" content="Drifty">
<meta property="og:image" content="http://ionicframework.com/img/ionic-logo-blog.png"/>
<!-- version /docs/nightly should not be indexed -->
<meta name="robots" content="noindex">
<title>$ionicScrollDelegate - Service in module ionic - Ionic Framework</title>
<link href="/css/site.css?12" rel="stylesheet">
<!--<script src="//cdn.optimizely.com/js/595530035.js"></script>-->
<script type="text/javascript">var _sf_startpt=(new Date()).getTime()</script>
<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', 'UA-44023830-1', 'ionicframework.com');
ga('send', 'pageview');
</script>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body class="docs docs-page docs-api">
<nav class="navbar navbar-default horizontal-gradient" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle button ionic" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<i class="icon ion-navicon"></i>
</button>
<a class="navbar-brand" href="/">
<img src="/img/ionic-logo-white.svg" width="123" height="43" alt="Ionic Framework">
</a>
<a href="http://blog.ionic.io/announcing-ionic-1-0/" target="_blank">
<img src="/img/ionic1-tag.png" alt="Ionic 1.0 is out!" width="28" height="32" style="margin-left: 140px; margin-top:22px; display:block">
</a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a class="getting-started-nav nav-link" href="/getting-started/">Getting Started</a></li>
<li><a class="docs-nav nav-link" href="/docs/">Docs</a></li>
<li><a class="nav-link" href="http://ionic.io/support">Support</a></li>
<li><a class="blog-nav nav-link" href="http://blog.ionic.io/">Blog <span id="blog-badge">1</span></a></li>
<li><a class="nav-link" href="http://forum.ionicframework.com/">Forum</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle nav-link " data-toggle="dropdown" role="button" aria-expanded="false">More <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<div class="arrow-up"></div>
<li><a class="products-nav nav-link" href="http://ionic.io/">Ionic.io</a></li>
<li><a class="examples-nav nav-link" href="http://showcase.ionicframework.com/">Showcase</a></li>
<li><a class="nav-link" href="http://jobs.ionic.io/">Job Board</a></li>
<li><a class="nav-link" href="http://market.ionic.io/">Market</a></li>
<li><a class="nav-link" href="http://ionicworldwide.herokuapp.com/">Ionic Worldwide</a></li>
<li><a class="nav-link" href="http://play.ionic.io/">Playground</a></li>
<li><a class="nav-link" href="http://creator.ionic.io/">Creator</a></li>
<li><a class="nav-link" href="http://shop.ionic.io/">Shop</a></li>
<!--<li><a class="nav-link" href="http://ngcordova.com/">ngCordova</a></li>-->
</ul>
</li>
</ul>
</div>
</div>
</nav>
<div class="header horizontal-gradient">
<div class="container">
<h3>$ionicScrollDelegate</h3>
<h4>Service in module ionic</h4>
</div>
<div class="news">
<div class="container">
<div class="row">
<div class="col-sm-8 news-col">
<div class="picker">
<select onchange="window.location.href=this.options[this.selectedIndex].value">
<option
value="/docs/nightly/api/service/$ionicScrollDelegate/"
selected>
nightly
</option>
<option
value="/docs/api/service/$ionicScrollDelegate/"
>
1.1.0 (latest)
</option>
<option
value="/docs/1.0.1/api/service/$ionicScrollDelegate/"
>
1.0.1
</option>
<option
value="/docs/1.0.0/api/service/$ionicScrollDelegate/"
>
1.0.0
</option>
<option
value="/docs/1.0.0-rc.5/api/service/$ionicScrollDelegate/"
>
1.0.0-rc.5
</option>
<option
value="/docs/1.0.0-rc.4/api/service/$ionicScrollDelegate/"
>
1.0.0-rc.4
</option>
<option
value="/docs/1.0.0-rc.3/api/service/$ionicScrollDelegate/"
>
1.0.0-rc.3
</option>
<option
value="/docs/1.0.0-rc.2/api/service/$ionicScrollDelegate/"
>
1.0.0-rc.2
</option>
<option
value="/docs/1.0.0-rc.1/api/service/$ionicScrollDelegate/"
>
1.0.0-rc.1
</option>
<option
value="/docs/1.0.0-rc.0/api/service/$ionicScrollDelegate/"
>
1.0.0-rc.0
</option>
<option
value="/docs/1.0.0-beta.14/api/service/$ionicScrollDelegate/"
>
1.0.0-beta.14
</option>
<option
value="/docs/1.0.0-beta.13/api/service/$ionicScrollDelegate/"
>
1.0.0-beta.13
</option>
<option
value="/docs/1.0.0-beta.12/api/service/$ionicScrollDelegate/"
>
1.0.0-beta.12
</option>
<option
value="/docs/1.0.0-beta.11/api/service/$ionicScrollDelegate/"
>
1.0.0-beta.11
</option>
<option
value="/docs/1.0.0-beta.10/api/service/$ionicScrollDelegate/"
>
1.0.0-beta.10
</option>
</select>
</div>
</div>
<div class="col-sm-4 search-col">
<div class="search-bar">
<span class="search-icon ionic"><i class="ion-ios7-search-strong"></i></span>
<input type="search" id="search-input" value="Search">
</div>
</div>
</div>
</div>
</div>
</div>
<div id="search-results" class="search-results" style="display:none">
<div class="container">
<div class="search-section search-api">
<h4>JavaScript</h4>
<ul id="results-api"></ul>
</div>
<div class="search-section search-css">
<h4>CSS</h4>
<ul id="results-css"></ul>
</div>
<div class="search-section search-content">
<h4>Resources</h4>
<ul id="results-content"></ul>
</div>
</div>
</div>
<div class="container content-container">
<div class="row">
<div class="col-md-2 col-sm-3 aside-menu">
<div>
<ul class="nav left-menu">
<li class="menu-title">
<a href="/docs/overview/">Overview</a>
</li>
</ul>
<ul class="nav left-menu">
<li class="menu-title">
<a href="/docs/components/">CSS</a>
</li>
</ul>
<ul class="nav left-menu">
<li class="menu-title">
<a href="/docs/platform-customization/">Platform Customization</a>
</li>
</ul>
<!-- Docs: JavaScript -->
<ul class="nav left-menu active-menu">
<li class="menu-title">
<a href="/docs/nightly/api/">
JavaScript
</a>
</li>
<!-- Action Sheet -->
<li class="menu-section">
<a href="/docs/nightly/api/service/$ionicActionSheet/" class="api-section">
Action Sheet
</a>
<ul>
<li>
<a href="/docs/nightly/api/service/$ionicActionSheet/">
$ionicActionSheet
</a>
</li>
</ul>
</li>
<!-- Backdrop -->
<li class="menu-section">
<a href="/docs/nightly/api/service/$ionicBackdrop/" class="api-section">
Backdrop
</a>
<ul>
<li>
<a href="/docs/nightly/api/service/$ionicBackdrop/">
$ionicBackdrop
</a>
</li>
</ul>
</li>
<!-- Content -->
<li class="menu-section">
<a href="/docs/nightly/api/directive/ionContent/" class="api-section">
Content
</a>
<ul>
<li>
<a href="/docs/nightly/api/directive/ionContent/">
ion-content
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionRefresher/">
ion-refresher
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionPane/">
ion-pane
</a>
</li>
</ul>
</li>
<!-- Form Inputs -->
<li class="menu-section">
<a href="/docs/nightly/api/directive/ionCheckbox/" class="api-section">
Form Inputs
</a>
<ul>
<li>
<a href="/docs/nightly/api/directive/ionCheckbox/">
ion-checkbox
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionRadio/">
ion-radio
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionToggle/">
ion-toggle
</a>
</li>
</ul>
</li>
<!-- Gesture and Events -->
<li class="menu-section">
<a href="/docs/nightly/api/directive/onHold/" class="api-section">
Gestures and Events
</a>
<ul>
<li>
<a href="/docs/nightly/api/directive/onHold/">
on-hold
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/onTap/">
on-tap
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/onDoubleTap/">
on-double-tap
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/onTouch/">
on-touch
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/onRelease/">
on-release
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/onDrag/">
on-drag
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/onDragUp/">
on-drag-up
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/onDragRight/">
on-drag-right
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/onDragDown/">
on-drag-down
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/onDragLeft/">
on-drag-left
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/onSwipe/">
on-swipe
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/onSwipeUp/">
on-swipe-up
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/onSwipeRight/">
on-swipe-right
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/onSwipeDown/">
on-swipe-down
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/onSwipeLeft/">
on-swipe-left
</a>
</li>
<li>
<a href="/docs/nightly/api/service/$ionicGesture/">
$ionicGesture
</a>
</li>
</ul>
</li>
<!-- Headers/Footers -->
<li class="menu-section">
<a href="/docs/nightly/api/directive/ionHeaderBar/" class="api-section">
Headers/Footers
</a>
<ul>
<li>
<a href="/docs/nightly/api/directive/ionHeaderBar/">
ion-header-bar
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionFooterBar/">
ion-footer-bar
</a>
</li>
</ul>
</li>
<!-- Keyboard -->
<li class="menu-section">
<a href="/docs/nightly/api/page/keyboard/" class="api-section">
Keyboard
</a>
<ul>
<li>
<a href="/docs/nightly/api/page/keyboard/">
Keyboard
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/keyboardAttach/">
keyboard-attach
</a>
</li>
</ul>
</li>
<!-- Lists -->
<li class="menu-section">
<a href="/docs/nightly/api/directive/ionList/" class="api-section">
Lists
</a>
<ul>
<li>
<a href="/docs/nightly/api/directive/ionList/">
ion-list
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionItem/">
ion-item
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionDeleteButton/">
ion-delete-button
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionReorderButton/">
ion-reorder-button
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionOptionButton/">
ion-option-button
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/collectionRepeat/">
collection-repeat
</a>
</li>
<li>
<a href="/docs/nightly/api/service/$ionicListDelegate/">
$ionicListDelegate
</a>
</li>
</ul>
</li>
<!-- Loading -->
<li class="menu-section">
<a href="/docs/nightly/api/service/$ionicLoading/" class="api-section">
Loading
</a>
<ul>
<li>
<a href="/docs/nightly/api/service/$ionicLoading/">
$ionicLoading
</a>
</li>
</ul>
<ul>
<li>
<a href="/docs/nightly/api/object/$ionicLoadingConfig/">
$ionicLoadingConfig
</a>
</li>
</ul>
</li>
<!-- Modal -->
<li class="menu-section">
<a href="/docs/nightly/api/service/$ionicModal/" class="api-section">
Modal
</a>
<ul>
<li>
<a href="/docs/nightly/api/service/$ionicModal/">
$ionicModal
</a>
</li>
<li>
<a href="/docs/nightly/api/controller/ionicModal/">
ionicModal
</a>
</li>
</ul>
</li>
<!-- Navigation -->
<li class="menu-section">
<a href="/docs/nightly/api/directive/ionNavView/" class="api-section">
Navigation
</a>
<ul>
<li>
<a href="/docs/nightly/api/directive/ionNavView/">
ion-nav-view
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionView/">
ion-view
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionNavBar/">
ion-nav-bar
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionNavBackButton/">
ion-nav-back-button
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionNavButtons/">
ion-nav-buttons
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionNavTitle/">
ion-nav-title
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/navTransition/">
nav-transition
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/navDirection/">
nav-direction
</a>
</li>
<li>
<a href="/docs/nightly/api/service/$ionicNavBarDelegate/">
$ionicNavBarDelegate
</a>
</li>
<li>
<a href="/docs/nightly/api/service/$ionicHistory/">
$ionicHistory
</a>
</li>
</ul>
</li>
<!-- Platform -->
<li class="menu-section">
<a href="/docs/nightly/api/service/$ionicPlatform/" class="api-section">
Platform
</a>
<ul>
<li>
<a href="/docs/nightly/api/service/$ionicPlatform/">
$ionicPlatform
</a>
</li>
</ul>
</li>
<!-- Popover -->
<li class="menu-section">
<a href="/docs/nightly/api/service/$ionicPopover/" class="api-section">
Popover
</a>
<ul>
<li>
<a href="/docs/nightly/api/service/$ionicPopover/">
$ionicPopover
</a>
</li>
<li>
<a href="/docs/nightly/api/controller/ionicPopover/">
ionicPopover
</a>
</li>
</ul>
</li>
<!-- Popup -->
<li class="menu-section">
<a href="/docs/nightly/api/service/$ionicPopup/" class="api-section">
Popup
</a>
<ul>
<li>
<a href="/docs/nightly/api/service/$ionicPopup/">
$ionicPopup
</a>
</li>
</ul>
</li>
<!-- Scroll -->
<li class="menu-section">
<a href="/docs/nightly/api/directive/ionScroll/" class="api-section">
Scroll
</a>
<ul>
<li>
<a href="/docs/nightly/api/directive/ionScroll/">
ion-scroll
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionInfiniteScroll/">
ion-infinite-scroll
</a>
</li>
<li>
<a href="/docs/nightly/api/service/$ionicScrollDelegate/">
$ionicScrollDelegate
</a>
</li>
</ul>
</li>
<!-- Side Menus -->
<li class="menu-section">
<a href="/docs/nightly/api/directive/ionSideMenus/" class="api-section">
Side Menus
</a>
<ul>
<li>
<a href="/docs/nightly/api/directive/ionSideMenus/">
ion-side-menus
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionSideMenuContent/">
ion-side-menu-content
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionSideMenu/">
ion-side-menu
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/exposeAsideWhen/">
expose-aside-when
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/menuToggle/">
menu-toggle
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/menuClose/">
menu-close
</a>
</li>
<li>
<a href="/docs/nightly/api/service/$ionicSideMenuDelegate/">
$ionicSideMenuDelegate
</a>
</li>
</ul>
</li>
<!-- Slide Box -->
<li class="menu-section">
<a href="/docs/nightly/api/directive/ionSlideBox/" class="api-section">
Slide Box
</a>
<ul>
<li>
<a href="/docs/nightly/api/directive/ionSlideBox/">
ion-slide-box
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionSlidePager/">
ion-slide-pager
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionSlide/">
ion-slide
</a>
</li>
<li>
<a href="/docs/nightly/api/service/$ionicSlideBoxDelegate/">
$ionicSlideBoxDelegate
</a>
</li>
</ul>
</li>
<!-- Spinner -->
<li class="menu-section">
<a href="/docs/nightly/api/directive/ionSpinner/" class="api-section">
Spinner
</a>
<ul>
<li>
<a href="/docs/nightly/api/directive/ionSpinner/">
ion-spinner
</a>
</li>
</ul>
</li>
<!-- Tabs -->
<li class="menu-section">
<a href="/docs/nightly/api/directive/ionTabs/" class="api-section">
Tabs
</a>
<ul>
<li>
<a href="/docs/nightly/api/directive/ionTabs/">
ion-tabs
</a>
</li>
<li>
<a href="/docs/nightly/api/directive/ionTab/">
ion-tab
</a>
</li>
<li>
<a href="/docs/nightly/api/service/$ionicTabsDelegate/">
$ionicTabsDelegate
</a>
</li>
</ul>
</li>
<!-- Tap -->
<li class="menu-section">
<a href="/docs/nightly/api/page/tap/" class="api-section">
Tap & Click
</a>
</li>
<!-- Utility -->
<li class="menu-section">
<a href="#" class="api-section">
Utility
</a>
<ul>
<li>
<a href="/docs/nightly/api/provider/$ionicConfigProvider/">
$ionicConfigProvider
</a>
</li>
<li>
<a href="/docs/nightly/api/utility/ionic.Platform/">
ionic.Platform
</a>
</li>
<li>
<a href="/docs/nightly/api/utility/ionic.DomUtil/">
ionic.DomUtil
</a>
</li>
<li>
<a href="/docs/nightly/api/utility/ionic.EventController/">
ionic.EventController
</a>
</li>
<li>
<a href="/docs/nightly/api/service/$ionicPosition/">
$ionicPosition
</a>
</li>
</ul>
</li>
</ul>
<ul class="nav left-menu">
<li class="menu-title">
<a href="/docs/cli/">CLI</a>
</li>
</ul>
<ul class="nav left-menu">
<li class="menu-title">
<a href="http://learn.ionicframework.com/">Learn Ionic</a>
</li>
</ul>
<ul class="nav left-menu">
<li class="menu-title">
<a href="/docs/guide/">Guide</a>
</li>
</ul>
<ul class="nav left-menu">
<li class="menu-title">
<a href="/docs/ionic-cli-faq/">FAQ</a>
</li>
</ul>
<ul class="nav left-menu">
<li class="menu-title">
<a href="/docs/getting-help/">Getting Help</a>
</li>
</ul>
<ul class="nav left-menu">
<li class="menu-title">
<a href="/docs/concepts/">Ionic Concepts</a>
</li>
</ul>
</div>
</div>
<div class="col-md-10 col-sm-9 main-content">
<div class="improve-docs">
<a href='http://github.com/driftyco/ionic/tree/master/js/angular/service/scrollDelegate.js#L2'>
View Source
</a>
<a href='http://github.com/driftyco/ionic/edit/master/js/angular/service/scrollDelegate.js#L2'>
Improve this doc
</a>
</div>
<h1 class="api-title">
$ionicScrollDelegate
</h1>
<p>Delegate for controlling scrollViews (created by
<a href="/docs/nightly/api/directive/ionContent/"><code>ionContent</code></a> and
<a href="/docs/nightly/api/directive/ionScroll/"><code>ionScroll</code></a> directives).</p>
<p>Methods called directly on the $ionicScrollDelegate service will control all scroll
views. Use the <a href="/docs/nightly/api/service/$ionicScrollDelegate/#$getByHandle">$getByHandle</a>
method to control specific scrollViews.</p>
<h2>Usage</h2>
<div class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt"><body</span> <span class="na">ng-controller=</span><span class="s">"MainCtrl"</span><span class="nt">></span>
<span class="nt"><ion-content></span>
<span class="nt"><button</span> <span class="na">ng-click=</span><span class="s">"scrollTop()"</span><span class="nt">></span>Scroll to Top!<span class="nt"></button></span>
<span class="nt"></ion-content></span>
<span class="nt"></body></span>
</code></pre></div><div class="highlight"><pre><code class="language-js" data-lang="js"><span class="kd">function</span> <span class="nx">MainCtrl</span><span class="p">(</span><span class="nx">$scope</span><span class="p">,</span> <span class="nx">$ionicScrollDelegate</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">$scope</span><span class="p">.</span><span class="nx">scrollTop</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">$ionicScrollDelegate</span><span class="p">.</span><span class="nx">scrollTop</span><span class="p">();</span>
<span class="p">};</span>
<span class="p">}</span>
</code></pre></div>
<p>Example of advanced usage, with two scroll areas using <code>delegate-handle</code>
for fine control.</p>
<div class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt"><body</span> <span class="na">ng-controller=</span><span class="s">"MainCtrl"</span><span class="nt">></span>
<span class="nt"><ion-content</span> <span class="na">delegate-handle=</span><span class="s">"mainScroll"</span><span class="nt">></span>
<span class="nt"><button</span> <span class="na">ng-click=</span><span class="s">"scrollMainToTop()"</span><span class="nt">></span>
Scroll content to top!
<span class="nt"></button></span>
<span class="nt"><ion-scroll</span> <span class="na">delegate-handle=</span><span class="s">"small"</span> <span class="na">style=</span><span class="s">"height: 100px;"</span><span class="nt">></span>
<span class="nt"><button</span> <span class="na">ng-click=</span><span class="s">"scrollSmallToTop()"</span><span class="nt">></span>
Scroll small area to top!
<span class="nt"></button></span>
<span class="nt"></ion-scroll></span>
<span class="nt"></ion-content></span>
<span class="nt"></body></span>
</code></pre></div><div class="highlight"><pre><code class="language-js" data-lang="js"><span class="kd">function</span> <span class="nx">MainCtrl</span><span class="p">(</span><span class="nx">$scope</span><span class="p">,</span> <span class="nx">$ionicScrollDelegate</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">$scope</span><span class="p">.</span><span class="nx">scrollMainToTop</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">$ionicScrollDelegate</span><span class="p">.</span><span class="nx">$getByHandle</span><span class="p">(</span><span class="s1">'mainScroll'</span><span class="p">).</span><span class="nx">scrollTop</span><span class="p">();</span>
<span class="p">};</span>
<span class="nx">$scope</span><span class="p">.</span><span class="nx">scrollSmallToTop</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="nx">$ionicScrollDelegate</span><span class="p">.</span><span class="nx">$getByHandle</span><span class="p">(</span><span class="s1">'small'</span><span class="p">).</span><span class="nx">scrollTop</span><span class="p">();</span>
<span class="p">};</span>
<span class="p">}</span>
</code></pre></div>
<h2>Methods</h2>
<div id="resize"></div>
<h2>
<code>resize()</code>
</h2>
<p>Tell the scrollView to recalculate the size of its container.</p>
<div id="scrollTop"></div>
<h2>
<code>scrollTop([shouldAnimate])</code>
</h2>
<table class="table" style="margin:0;">
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
shouldAnimate
<div><em>(optional)</em></div>
</td>
<td>
<code>boolean</code>
</td>
<td>
<p>Whether the scroll should animate.</p>
</td>
</tr>
</tbody>
</table>
<div id="scrollBottom"></div>
<h2>
<code>scrollBottom([shouldAnimate])</code>
</h2>
<table class="table" style="margin:0;">
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
shouldAnimate
<div><em>(optional)</em></div>
</td>
<td>
<code>boolean</code>
</td>
<td>
<p>Whether the scroll should animate.</p>
</td>
</tr>
</tbody>
</table>
<div id="scrollTo"></div>
<h2>
<code>scrollTo(left, top, [shouldAnimate])</code>
</h2>
<table class="table" style="margin:0;">
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
left
</td>
<td>
<code>number</code>
</td>
<td>
<p>The x-value to scroll to.</p>
</td>
</tr>
<tr>
<td>
top
</td>
<td>
<code>number</code>
</td>
<td>
<p>The y-value to scroll to.</p>
</td>
</tr>
<tr>
<td>
shouldAnimate
<div><em>(optional)</em></div>
</td>
<td>
<code>boolean</code>
</td>
<td>
<p>Whether the scroll should animate.</p>
</td>
</tr>
</tbody>
</table>
<div id="scrollBy"></div>
<h2>
<code>scrollBy(left, top, [shouldAnimate])</code>
</h2>
<table class="table" style="margin:0;">
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
left
</td>
<td>
<code>number</code>
</td>
<td>
<p>The x-offset to scroll by.</p>
</td>
</tr>
<tr>
<td>
top
</td>
<td>
<code>number</code>
</td>
<td>
<p>The y-offset to scroll by.</p>
</td>
</tr>
<tr>
<td>
shouldAnimate
<div><em>(optional)</em></div>
</td>
<td>
<code>boolean</code>
</td>
<td>
<p>Whether the scroll should animate.</p>
</td>
</tr>
</tbody>
</table>
<div id="zoomTo"></div>
<h2>
<code>zoomTo(level, [animate], [originLeft], [originTop])</code>
</h2>
<table class="table" style="margin:0;">
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
level
</td>
<td>
<code>number</code>
</td>
<td>
<p>Level to zoom to.</p>
</td>
</tr>
<tr>
<td>
animate
<div><em>(optional)</em></div>
</td>
<td>
<code>boolean</code>
</td>
<td>
<p>Whether to animate the zoom.</p>
</td>
</tr>
<tr>
<td>
originLeft
<div><em>(optional)</em></div>
</td>
<td>
<code>number</code>
</td>
<td>
<p>Zoom in at given left coordinate.</p>
</td>
</tr>
<tr>
<td>
originTop
<div><em>(optional)</em></div>
</td>
<td>
<code>number</code>
</td>
<td>
<p>Zoom in at given top coordinate.</p>
</td>
</tr>
</tbody>
</table>
<div id="zoomBy"></div>
<h2>
<code>zoomBy(factor, [animate], [originLeft], [originTop])</code>
</h2>
<table class="table" style="margin:0;">
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
factor
</td>
<td>
<code>number</code>
</td>
<td>
<p>The factor to zoom by.</p>
</td>
</tr>
<tr>
<td>
animate
<div><em>(optional)</em></div>
</td>
<td>
<code>boolean</code>
</td>
<td>
<p>Whether to animate the zoom.</p>
</td>
</tr>
<tr>
<td>
originLeft
<div><em>(optional)</em></div>
</td>
<td>
<code>number</code>
</td>
<td>
<p>Zoom in at given left coordinate.</p>
</td>
</tr>
<tr>
<td>
originTop
<div><em>(optional)</em></div>
</td>
<td>
<code>number</code>
</td>
<td>
<p>Zoom in at given top coordinate.</p>
</td>
</tr>
</tbody>
</table>
<div id="getScrollPosition"></div>
<h2>
<code>getScrollPosition()</code>
</h2>
<ul>
<li>Returns:
<code>object</code> The scroll position of this view, with the following properties:
<ul>
<li><code>{number}</code> <code>left</code> The distance the user has scrolled from the left (starts at 0).</li>
<li><code>{number}</code> <code>top</code> The distance the user has scrolled from the top (starts at 0).</li>
</ul></li>
</ul>
<div id="anchorScroll"></div>
<h2>
<code>anchorScroll([shouldAnimate])</code>
</h2>
<p>Tell the scrollView to scroll to the element with an id
matching window.location.hash.</p>
<p>If no matching element is found, it will scroll to top.</p>
<table class="table" style="margin:0;">
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
shouldAnimate
<div><em>(optional)</em></div>
</td>
<td>
<code>boolean</code>
</td>
<td>
<p>Whether the scroll should animate.</p>
</td>
</tr>
</tbody>
</table>
<div id="freezeScroll"></div>
<h2>
<code>freezeScroll([shouldFreeze])</code>
</h2>
<p>Does not allow this scroll view to scroll either x or y.</p>
<table class="table" style="margin:0;">
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
shouldFreeze
<div><em>(optional)</em></div>
</td>
<td>
<code>boolean</code>
</td>
<td>
<p>Should this scroll view be prevented from scrolling or not.</p>
</td>
</tr>
</tbody>
</table>
<ul>
<li>Returns:
<code>object</code> If the scroll view is being prevented from scrolling or not.</li>
</ul>
<div id="freezeAllScrolls"></div>
<h2>
<code>freezeAllScrolls([shouldFreeze])</code>
</h2>
<p>Does not allow any of the app's scroll views to scroll either x or y.</p>
<table class="table" style="margin:0;">
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
shouldFreeze
<div><em>(optional)</em></div>
</td>
<td>
<code>boolean</code>
</td>
<td>
<p>Should all app scrolls be prevented from scrolling or not.</p>
</td>
</tr>
</tbody>
</table>
<div id="getScrollView"></div>
<h2>
<code>getScrollView()</code>
</h2>
<ul>
<li>Returns:
<code>object</code> The scrollView associated with this delegate.</li>
</ul>
<div id="$getByHandle"></div>
<h2>
<code>$getByHandle(handle)</code>
</h2>
<table class="table" style="margin:0;">
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
handle
</td>
<td>
<code>string</code>
</td>
<td>
</td>
</tr>
</tbody>
</table>
<ul>
<li>Returns:
<code>delegateInstance</code> A delegate instance that controls only the
scrollViews with <code>delegate-handle</code> matching the given handle.</li>
</ul>
<p>Example: <code>$ionicScrollDelegate.$getByHandle('my-handle').scrollTop();</code></p>
</div>
</div>
</div>
<div class="pre-footer">
<div class="row ionic">
<div class="col-sm-6 col-a">
<h4>
<a href="/getting-started/">Getting started <span class="icon ion-arrow-right-c"></span></a>
</h4>
<p>
Learn more about how Ionic was built, why you should use it, and what's included. We'll cover
the basics and help you get started from the ground up.
</p>
</div>
<div class="col-sm-6 col-b">
<h4>
<a href="/docs/">Documentation <span class="icon ion-arrow-right-c"></span></a>
</h4>
<p>
What are you waiting for? Take a look and get coding! Our documentation covers all you need to know
to get an app up and running in minutes.
</p>
</div>
</div>
</div>
<footer class="footer">
<nav class="base-links">
<dl>
<dt>Docs</dt>
<dd><a href="http://ionicframework.com/docs/">Documentation</a></dd>
<dd><a href="http://ionicframework.com/getting-started/">Getting Started</a></dd>
<dd><a href="http://ionicframework.com/docs/overview/">Overview</a></dd>
<dd><a href="http://ionicframework.com/docs/components/">Components</a></dd>
<dd><a href="http://ionicframework.com/docs/api/">JavaScript</a></dd>
<dd><a href="http://ionicframework.com/submit-issue/">Submit Issue</a></dd>
</dl>
<dl>
<dt>Resources</dt>
<dd><a href="http://learn.ionicframework.com/">Learn Ionic</a></dd>
<dd><a href="http://ngcordova.com/">ngCordova</a></dd>
<dd><a href="http://ionicons.com/">Ionicons</a></dd>
<dd><a href="http://creator.ionic.io/">Creator</a></dd>
<dd><a href="http://showcase.ionicframework.com/">Showcase</a></dd>
<dd><a href="http://manning.com/wilken/?a_aid=ionicinactionben&a_bid=1f0a0e1d">The Ionic Book</a></dd>
</dl>
<dl>
<dt>Contribute</dt>
<dd><a href="http://forum.ionicframework.com/">Community Forum</a></dd>
<dd><a href="http://webchat.freenode.net/?randomnick=1&channels=%23ionic&uio=d4">Ionic IRC</a></dd>
<dd><a href="http://ionicframework.com/present-ionic/">Present Ionic</a></dd>
<dd><a href="http://ionicframework.com/contribute/">Contribute</a></dd>
<dd><a href="https://github.com/driftyco/ionic-learn/issues/new">Write for us</a></dd>
<dd><a href="http://shop.ionic.io/">Ionic Shop</a></dd>
</dl>
<dl class="small-break">
<dt>About</dt>
<dd><a href="http://blog.ionic.io/">Blog</a></dd>
<dd><a href="http://ionic.io">Services</a></dd>
<dd><a href="http://drifty.com">Company</a></dd>
<dd><a href="https://s3.amazonaws.com/ionicframework.com/logo-pack.zip">Logo Pack</a></dd>
<dd><a href="mailto:[email protected]">Contact</a></dd>
<dd><a href="http://ionicframework.com/jobs/">Jobs</a></dd>
</dl>
<dl>
<dt>Connect</dt>
<dd><a href="https://twitter.com/IonicFramework">Twitter</a></dd>
<dd><a href="https://github.com/driftyco/ionic">GitHub</a></dd>
<dd><a href="https://www.facebook.com/ionicframework">Facebook</a></dd>
<dd><a href="https://plus.google.com/b/112280728135675018538/+Ionicframework/posts">Google+</a></dd>
<dd><a href="https://www.youtube.com/channel/UChYheBnVeCfhCmqZfCUdJQw">YouTube</a></dd>
<dd><a href="https://twitter.com/ionitron">Ionitron</a></dd>
</dl>
</nav>
<div class="newsletter row">
<div class="newsletter-container">
<div class="col-sm-7">
<div class="newsletter-text">Stay in the loop</div>
<div class="sign-up">Sign up to receive emails for the latest updates, features, and news on the framework.</div>
</div>
<form action="http://codiqa.createsend.com/t/t/s/jytylh/" method="post" class="input-group col-sm-5">
<input id="fieldEmail" name="cm-jytylh-jytylh" class="form-control" type="email" placeholder="Email" required />
<span class="input-group-btn">
<button class="btn btn-default" type="submit">Subscribe</button>
</span>
</form>
</div>
</div>
<div class="copy">
<div class="copy-container">
<p class="authors">
Code licensed under <a href="/docs/#license">MIT</a>.
Docs under <a href="https://tldrlegal.com/license/apache-license-2.0-(apache-2.0)">Apache 2</a>
<span>|</span>
© 2013-2015 <a href="http://drifty.com/">Drifty Co</a>
</p>
</div>
</div>
</footer>
<script type="text/javascript">
var _sf_async_config = { uid: 54141, domain: 'ionicframework.com', useCanonical: true };
(function() {
function loadChartbeat() {
window._sf_endpt = (new Date()).getTime();
var e = document.createElement('script');
e.setAttribute('language', 'javascript');
e.setAttribute('type', 'text/javascript');
e.setAttribute('src','//static.chartbeat.com/js/chartbeat.js');
document.body.appendChild(e);
};
var oldonload = window.onload;
window.onload = (typeof window.onload != 'function') ?
loadChartbeat : function() { oldonload(); loadChartbeat(); };
})();
</script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>
<script src="/js/site.js?1"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/Cookies.js/0.4.0/cookies.min.js"></script>
<script>
$('.navbar .dropdown').on('show.bs.dropdown', function(e){
//$(this).find('.dropdown-menu').addClass('animated fadeInDown');
});
// ADD SLIDEUP ANIMATION TO DROPDOWN //
$('.navbar .dropdown').on('hide.bs.dropdown', function(e){
//$(this).find('.dropdown-menu').first().stop(true, true).slideUp(200);
//$(this).find('.dropdown-menu').removeClass('animated fadeInDown');
});
try {
var d = new Date('2015-03-20 05:00:00 -0500');
var ts = d.getTime();
var cd = Cookies.get('_iondj');
if(cd) {
cd = JSON.parse(atob(cd));
if(parseInt(cd.lp) < ts) {
var bt = document.getElementById('blog-badge');
bt.style.display = 'block';
}
cd.lp = ts;
} else {
var bt = document.getElementById('blog-badge');
bt.style.display = 'block';
cd = {
lp: ts
}
}
Cookies.set('_iondj', btoa(JSON.stringify(cd)));
} catch(e) {
}
</script>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
</body>
</html>
|
apache-2.0
|
dotledger/dotledger
|
app/models/payment.rb
|
556
|
require 'schedule_serializer'
class Payment < ActiveRecord::Base
include IceCube
self.inheritance_column = nil
belongs_to :category
PAYMENT_TYPES = %w[Spend Receive].freeze
PAYMENT_PERIODS = %w[Day Week Month].freeze
validates :name, presence: true
validates :category, presence: true
validates :amount, presence: true
validates :schedule, presence: true
validates :type, presence: true, inclusion: { in: PAYMENT_TYPES }
delegate :name, :type, to: :category, prefix: true
serialize :schedule, ScheduleSerializer.new
end
|
apache-2.0
|
SmartDeveloperHub/sdh-vocabulary
|
src/test/java/org/smartdeveloperhub/vocabulary/util/CatalogsTest.java
|
7465
|
/**
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* This file is part of the Smart Developer Hub Project:
* http://www.smartdeveloperhub.org/
*
* Center for Open Middleware
* http://www.centeropenmiddleware.com/
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* Copyright (C) 2015-2016 Center for Open Middleware.
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* 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.
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* Artifact : org.smartdeveloperhub.vocabulary:sdh-vocabulary:0.3.0
* Bundle : sdh-vocabulary-0.3.0.jar
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/
package org.smartdeveloperhub.vocabulary.util;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assume.assumeThat;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class CatalogsTest {
private static final Path ROOT=Paths.get("src","main","resources","vocabulary");
private static final URI BASE=URI.create("http://www.smartdeveloperhub.org/vocabulary/");
private Catalog catalog;
@Before
public void setUp() throws IOException {
final Result<Catalog> result = Catalogs.loadFrom(ROOT,BASE);
assertThat(result.isAvailable(),equalTo(true));
this.catalog = result.get();
assertThat(this.catalog,notNullValue());
}
@Test
public void absoluteCanonicalModulesCanBeResolved() throws Exception {
for(final String relativePath:this.catalog.canonicalModules()) {
final URI ontology = absoluteResource(relativePath);
final Module module=this.catalog.resolve(ontology);
assertThat(module,notNullValue());
assertThat(module.relativePath(),not(equalTo(relativePath)));
assertThat(module.ontology(),equalTo(ontology.toString()));
}
}
@Test
public void absoluteVersionModulesCanBeResolved() throws Exception {
for(final String relativePath:this.catalog.versionModules()) {
final Module module=this.catalog.resolve(absoluteResource(relativePath));
assertThat(module,notNullValue());
assertThat(module.relativePath(),equalTo(relativePath));
}
}
@Test
public void absoluteExternalModulesCanBeResolved() throws Exception {
for(final String relativePath:this.catalog.externalModules()) {
final Module module=this.catalog.resolve(absoluteResource(relativePath));
assertThat(module,notNullValue());
assertThat(module.relativePath(),equalTo(relativePath));
}
}
@Test
public void absoluteExternalModuleImplementationsCanBeResolved() throws Exception {
for(final String relativePath:this.catalog.externalModules()) {
final Module module=this.catalog.resolve(absoluteResource(relativePath));
assumeThat(module,notNullValue());
assumeThat(module.relativePath(),equalTo(relativePath));
final URI externalLocation = module.context().getImplementationEndpoint(module.location());
final Module same=this.catalog.resolve(externalLocation);
assertThat(same,sameInstance(module));
}
}
@Test
public void relativeCanonicalModulesCanBeResolved() throws Exception {
for(final String relativePath:this.catalog.canonicalModules()) {
final Module module=this.catalog.resolve(relativeResource(relativePath));
assertThat(module,notNullValue());
assertThat(module.relativePath(),not(equalTo(relativePath)));
assertThat(module.ontology(),equalTo(absoluteResource(relativePath).toString()));
}
}
@Test
public void relativeVersionModulesCanBeResolved() throws Exception {
for(final String relativePath:this.catalog.versionModules()) {
final Module module=this.catalog.resolve(relativeResource(relativePath));
assertThat(module,notNullValue());
assertThat(module.relativePath(),equalTo(relativePath));
}
}
@Test
public void relativeExternalModulesCanBeResolved() throws Exception {
for(final String relativePath:this.catalog.externalModules()) {
final Module module=this.catalog.resolve(relativeResource(relativePath));
assertThat(module,notNullValue());
assertThat(module.relativePath(),equalTo(relativePath));
}
}
@Test
public void dealsNamespaces() throws IOException {
final Result<Catalog> result = Catalogs.loadFrom(TestHelper.TEST_ROOT,TestHelper.BASE);
assertThat(result.toString(),result.isAvailable(),equalTo(true));
final Catalog catalog = result.get();
assertThat(catalog,notNullValue());
for(final String moduleId:catalog.modules()) {
final Module module=catalog.get(moduleId);
assertThat(module,notNullValue());
}
assertThat(catalog.resolve(absoluteResource("")),notNullValue());
assertThat(catalog.resolve(absoluteResource("index")),nullValue());
final Module hashModule = catalog.resolve(absoluteResource("hash#"));
assertThat(hashModule,notNullValue());
assertThat(catalog.resolve(absoluteResource("hash")),sameInstance(hashModule));
assertThat(catalog.resolve(absoluteResource("v1/hash#")),sameInstance(hashModule));
assertThat(catalog.resolve(absoluteResource("v1/hash")),sameInstance(hashModule));
final Module slashModule = catalog.resolve(absoluteResource("slash/"));
assertThat(slashModule,notNullValue());
assertThat(catalog.resolve(absoluteResource("v1/slash/")),sameInstance(slashModule));
assertThat(catalog.resolve(absoluteResource("v1/slash/index")),nullValue());
}
private static URI absoluteResource(final String relativePath) {
return BASE.resolve(relativePath);
}
private static URI relativeResource(final String relativePath) {
return URI.create(relativePath);
}
void generateCode() throws Exception {
final Result<Catalog> result = Catalogs.loadFrom(ROOT,BASE);
if(result.isAvailable()) {
final Catalog catalog = result.get();
System.out.println(generateStringArray(catalog.externalModules(), "externals"));
System.out.println(generateStringArray(catalog.canonicalModules(), "canonicals"));
System.out.println(generateStringArray(catalog.versionModules(), "versions"));
}
}
private String generateStringArray(final List<String> values, final String variable) {
final StringBuilder builder=new StringBuilder();
builder.append("final String[] ").append(variable).append("={");
final Iterator<String> iterator=values.iterator();
while(iterator.hasNext()) {
builder.append("\n \"").append(iterator.next()).append("\"");
if(iterator.hasNext()) {
builder.append(",");
}
}
builder.append("\n}");
final String value = builder.toString();
return value;
}
}
|
apache-2.0
|
googleapis/google-api-ruby-client
|
generated/google-apis-monitoring_v1/spec/generated_spec.rb
|
919
|
# Copyright 2020 Google LLC
#
# 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.
require "rspec"
RSpec.describe "Google::Apis::MonitoringV1" do
# Minimal test just to ensure no syntax errors in generated code
it "should load" do
expect do
require "google/apis/monitoring_v1"
end.not_to raise_error
expect do
Google::Apis::MonitoringV1::MonitoringService.new
end.not_to raise_error
end
end
|
apache-2.0
|
silencewj/devops
|
_includes/header.html
|
396
|
<header>
<div class="header-content">
<div class="header-content-inner">
<img class="img-me" src="{{site.baseurl}}{{ site.me-img }}" alt="">
<h1>探索、记录、分享、生活</h1>
<hr>
<p>Devops,SN</p>
<a href="#contact" class="btn btn-primary btn-xl page-scroll">关于我更多</a>
</div>
</div>
</header>
|
apache-2.0
|
tzou24/BPS
|
BPS/src/com/frameworkset/platform/menu/BaseColumnTree.java
|
7661
|
package com.frameworkset.platform.menu;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.jsp.PageContext;
import org.apache.log4j.Logger;
import com.frameworkset.platform.config.ConfigManager;
import com.frameworkset.platform.framework.Framework;
import com.frameworkset.platform.framework.FrameworkServlet;
import com.frameworkset.platform.framework.Item;
import com.frameworkset.platform.framework.ItemQueue;
import com.frameworkset.platform.framework.MenuHelper;
import com.frameworkset.platform.framework.MenuItem;
import com.frameworkset.platform.framework.Module;
import com.frameworkset.platform.framework.ModuleQueue;
import com.frameworkset.common.tag.tree.COMTree;
import com.frameworkset.common.tag.tree.itf.ITreeNode;
import com.frameworkset.util.StringUtil;
/**
* <p>Title: BaseColumnTree</p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2006</p>
*
* <p>Company: 三一集团</p>
*
* @author biaoping.yin
* @version 1.0
*/
public class BaseColumnTree extends COMTree implements Serializable{
private static final Logger log = Logger.getLogger(BaseColumnTree.class);
private MenuHelper menuHelper;
private String subsystem;
public void setPageContext(PageContext context)
{
super.setPageContext(context);
subsystem = FrameworkServlet.getSubSystem(this.request,this.response,this.accessControl.getUserAccount());
if(menuHelper == null )
menuHelper = new MenuHelper(subsystem,accessControl);
else
menuHelper.resetControl(accessControl);
}
public boolean hasSon(ITreeNode father) {
String path = father.getId();
boolean hasson = false;
int idx = path.indexOf("::");
if(idx == -1) path = subsystem + "::" + path;
Framework framework = Framework.getInstance(subsystem);
if(father.isRoot() && path.equals(Framework.getSuperMenu(subsystem)))
{
ModuleQueue queue = null;
ItemQueue iqueue = null;
if(ConfigManager.getInstance().securityEnabled())
{
queue = this.menuHelper.getModules();
iqueue = this.menuHelper.getItems();
}
else
{
queue = framework.getModules();
iqueue = framework.getItems();
}
for(int i = 0; i < queue.size(); i ++)
{
MenuItem item = queue.getModule(i);
if(item.isUsed())
{
return hasson = true;
}
}
for(int i = 0; i < iqueue.size(); i ++)
{
MenuItem item = iqueue.getItem(i);
if(item.isUsed())
{
return hasson = true;
}
}
}
else
{
MenuItem menuItem = framework.getMenu(path);
if(menuItem instanceof Item)
{
return hasson = false;
}
else if(menuItem instanceof Module)
{
Module module = (Module)menuItem;
ItemQueue iqueue = null;
ModuleQueue mqueue = null;
if(ConfigManager.getInstance().securityEnabled())
{
iqueue = this.menuHelper.getSubItems(module.getPath());
mqueue = this.menuHelper.getSubModules(module.getPath());
}
else
{
iqueue = module.getItems();
mqueue = module.getSubModules();
}
for(int i = 0; i < iqueue.size(); i ++)
{
if(iqueue.getItem(i).isUsed())
return true;
}
for(int i = 0; i < mqueue.size(); i ++)
{
if(mqueue.getModule(i).isUsed())
return true;
}
}
}
return hasson;
}
public boolean setSon(ITreeNode father, int curLevel) {
String parentPath = father.getId();
ModuleQueue submodules = null;
ItemQueue items = null;
int idx = parentPath.indexOf("::");
if(idx == -1) parentPath = subsystem + "::" + parentPath;
Framework framework = Framework.getInstance(subsystem);
if(father.isRoot() && parentPath.equals(Framework.getSuperMenu(subsystem)))
{
if(ConfigManager.getInstance().securityEnabled())
{
submodules = this.menuHelper.getModules();
items = this.menuHelper.getItems();
}
else
{
submodules = framework.getModules();
items = framework.getItems();
}
}
else
{
if(ConfigManager.getInstance().securityEnabled())
{
items = this.menuHelper.getSubItems(parentPath);
submodules = this.menuHelper.getSubModules(parentPath);
}
else
{
Module module = framework.getModule(parentPath);
items = module.getItems();
submodules = module.getSubModules();
}
}
String treeid = "";
String treeName = "";
String moduleType = "module";
String itemType = "item";
boolean showHref = true;
String memo = null;
String radioValue = null;
String checkboxValue = null;
String path = "";
String nodeLink = null;
for(int i = 0; i < submodules.size(); i ++)
{
Map params = new HashMap();
Module submodule = submodules.getModule(i);
if(!submodule.isUsed())
continue;
treeid = submodule.getPath();
treeName = submodule.getName(request);
path = submodule.getPath();
showHref = false;
addNode(father, treeid, treeName, moduleType, showHref, curLevel, memo,
radioValue, checkboxValue, params);
}
for(int i = 0; i < items.size(); i ++)
{
Map params = new HashMap();
Item subitem = (Item)items.getItem(i);
if(!subitem.isUsed())
continue;
treeid = subitem.getPath();
treeName = subitem.getName(request);
path = subitem.getPath();
showHref = true;
nodeLink = getNodeLink(subitem,null);
//通过参数动态设置节点链接,nodeLink为树型结构中的保留的参数名称,其他应用不能覆盖或使用nodeLink作为参数名称
params.put("nodeLink",nodeLink);
addNode(father, treeid, treeName, itemType, showHref, curLevel, memo,
radioValue, checkboxValue, params);
}
return true;
}
private String getNodeLink(MenuItem menuItem,String sessionid)
{
String nodeLink = request.getContextPath() + "/" + Framework.getUrl(Framework.CONTENT_CONTAINER_URL,sessionid)
+ Framework.MENU_PATH + "=" +
StringUtil.encode(menuItem.getPath(), null) + "&"
+ Framework.MENU_TYPE + "=" +
// Framework.CONTENT_CONTAINER + "&ancestor=1";
Framework.CONTENT_CONTAINER;
return nodeLink;
}
}
|
apache-2.0
|
moniruzzaman-monir/Oj-solved
|
UVa all in C++/uva10922.cpp
|
917
|
#include <bits/stdc++.h>
using namespace std;
#include<string>
int mod(int n)
{
int s=0,c=1,a;
a=n;
while(a>0)
{
s+=a%10;
a/=10;
}
if(s==9)return 2;
else if(s<9)return 1;
if(s%9==0)
{
return 1+mod(s);
}
}
int main()
{
char str[1001];
int i,j,k,a,b,c,s,ln;
while(gets(str))
{
if(str[0]-48==0)return 0;
s=0;
c=0;
ln=strlen(str);
for(i=0;i<ln;i++)
s+=str[i]-48;
if(str[0]-48==9&&ln==1)c=1;
else if(s%9==0&&s==9&&ln!=1)c=2;
if(s%9==0&&s!=9)
{
c=mod(s);
}
if(c>0){
printf("%s",str);
cout << " is a multiple of 9 and has 9-degree "<< c << "." << endl;
}
else
{
printf("%s",str);
cout << " is not a multiple of 9."<<endl;
}
}
}
|
apache-2.0
|
sdphome/blog-content
|
content/pages/about.md
|
1736
|
Title: 关于
Date: 2016-05-19 20:04
Update: 2016-05-19 21:47
Comment: off
[1]: http://docs.getpelican.com/ "pelican documentation"
[2]: https://github.com/sdphome/blog-content "my pelican blog repository"
[3]: https://github.com/mawenbao/niu-x2 "my pelican theme"
[5]: https://github.com/sdphome "my github homepage"
[6]: http://www.douban.com/people/wishome/ "my douban homepage"
[7]: /my_gnupg.html "my gnu public key"
[10]: http://www.hawkhost.com/ "http://www.hawkhost.com/"
[11]: http://www.linode.com/ "http://www.linode.com/"
[12]: http://wordpress.org/extend/themes/responsive "http://wordpress.org/extend/themes/responsive"
[13]: /research/create_pseudo_static_blog_with_wordpress.html "create a pseudo static blog with wordpress"
[14]: /agreement.html "使用协议"
[15]: /my_projects.html "我的开源项目"
[16]: https://github.com/mawenbao/niu-x2-sidebar "niu-x2-sidebar"
[20]: http://www.atime.me
## 关于本博客
本博客使用[pelican][1]搭建,文章(markdown格式)和pelican配置文件放在[这里][2]。博客采用niu-x2-sidebar主题,源码放在[这里][16],作者的网站在[这里][20],感谢作者提供如此强大的主题。
如果没有特殊说明,本网站的原创文字作品和代码都使用商业友好的许可协议发布,详情可参考[使用协议][14],希望对大家有些用处。
## 关于我本人
程序猿一只,坐标上海/无锡,宅,爱老婆,爱家庭,爱工作。目前从事于Android偏底层开发(驱动/HAL),也做过一些linux应用开发,闲暇时学习一些python,openstack,虚拟化。喜欢音乐,爱看美剧,喜欢做美食。
## 如何联系我
* 邮箱: dp.shao AT gmail DOT com
* Github: [@sdphome][5]
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Chenopodiaceae/Dysphania/Dysphania anthelmintica/Chenopodium anthelminticum hastatum/README.md
|
195
|
# Chenopodium anthelminticum var. hastatum Moq. VARIETY
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Rubus/Rubus gillottii/README.md
|
188
|
# Rubus gillottii Boulay SPECIES
#### Status
ACCEPTED
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Saccharomycetes/Saccharomycetales/Candida/Candida viswanathii/ Syn. Trichosporon lodderae/README.md
|
212
|
# Trichosporon lodderae Phaff, Mrak & O.B. Williams, 1952 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Eurotiomycetes/Onygenales/Arthrodermataceae/Trichophyton/Trichophyton dactilistegicum/README.md
|
207
|
# Trichophyton dactilistegicum Szathmáry SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Trichophyton dactilistegicum Szathmáry
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Chromista/Haptophyta/Prymnesiophyceae/Stephanolithiaceae/Corollithion/Corollithion ellipticum/README.md
|
163
|
# Corollithion ellipticum SPECIES
#### Status
ACCEPTED
#### According to
Paleobiology Database
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Pseudocercospora/Pseudocercospora bangalorensis/README.md
|
249
|
# Pseudocercospora bangalorensis (Thirum. & Chupp) Deighton SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Mycol. Pap. 140: 140 (1976)
#### Original name
Cercospora bangalorensis Thirum. & Chupp
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Chromista/Ochrophyta/Phaeophyceae/Fucales/Fucaceae/Silvetia/Silvetia babingtonii/ Syn. Pelvetia babingtonii/README.md
|
194
|
# Pelvetia babingtonii (Harvey) De Toni SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Sasa/Sasa kurokawana/README.md
|
199
|
# Sasa kurokawana Makino SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
J. Jap. Bot. 7:27. 1931
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Ramalinaceae/Bacidia/Bacidia ioeessa/README.md
|
171
|
# Bacidia ioeessa Herre SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Bacidia ioeessa Herre
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Sordariomycetes/Magnaporthaceae/Ophioceras/Ophioceras hystrix/README.md
|
186
|
# Ophioceras hystrix (Ces.) Sacc. SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Rhaphidospora hystrix Ces.
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Acacia/Acacia dentifera/Acacia dentifera dentifera/README.md
|
188
|
# Acacia dentifera var. dentifera Benth. VARIETY
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
macchina-io/macchina.io
|
platform/NetSSL_OpenSSL/src/HTTPSStreamFactory.cpp
|
4963
|
//
// HTTPSStreamFactory.cpp
//
// Library: NetSSL_OpenSSL
// Package: HTTPSClient
// Module: HTTPSStreamFactory
//
// Copyright (c) 2006-2012, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/Net/HTTPSStreamFactory.h"
#include "Poco/Net/HTTPSClientSession.h"
#include "Poco/Net/HTTPIOStream.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/HTTPCredentials.h"
#include "Poco/Net/NetException.h"
#include "Poco/URI.h"
#include "Poco/URIStreamOpener.h"
#include "Poco/UnbufferedStreamBuf.h"
#include "Poco/NullStream.h"
#include "Poco/StreamCopier.h"
#include "Poco/Format.h"
#include "Poco/Version.h"
using Poco::URIStreamFactory;
using Poco::URI;
using Poco::URIStreamOpener;
using Poco::UnbufferedStreamBuf;
namespace Poco {
namespace Net {
HTTPSStreamFactory::HTTPSStreamFactory():
_proxyPort(HTTPSession::HTTP_PORT)
{
}
HTTPSStreamFactory::HTTPSStreamFactory(const std::string& proxyHost, Poco::UInt16 proxyPort):
_proxyHost(proxyHost),
_proxyPort(proxyPort)
{
}
HTTPSStreamFactory::HTTPSStreamFactory(const std::string& proxyHost, Poco::UInt16 proxyPort, const std::string& proxyUsername, const std::string& proxyPassword):
_proxyHost(proxyHost),
_proxyPort(proxyPort),
_proxyUsername(proxyUsername),
_proxyPassword(proxyPassword)
{
}
HTTPSStreamFactory::~HTTPSStreamFactory()
{
}
std::istream* HTTPSStreamFactory::open(const URI& uri)
{
poco_assert (uri.getScheme() == "https" || uri.getScheme() == "http");
URI resolvedURI(uri);
URI proxyUri;
HTTPClientSession* pSession = 0;
HTTPResponse res;
try
{
bool retry = false;
bool authorize = false;
int redirects = 0;
std::string username;
std::string password;
do
{
if (!pSession)
{
if (resolvedURI.getScheme() != "http")
pSession = new HTTPSClientSession(resolvedURI.getHost(), resolvedURI.getPort());
else
pSession = new HTTPClientSession(resolvedURI.getHost(), resolvedURI.getPort());
if (proxyUri.empty())
{
if (!_proxyHost.empty())
{
pSession->setProxy(_proxyHost, _proxyPort);
pSession->setProxyCredentials(_proxyUsername, _proxyPassword);
}
}
else
{
pSession->setProxy(proxyUri.getHost(), proxyUri.getPort());
if (!_proxyUsername.empty())
{
pSession->setProxyCredentials(_proxyUsername, _proxyPassword);
}
}
}
std::string path = resolvedURI.getPathAndQuery();
if (path.empty()) path = "/";
HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
if (authorize)
{
HTTPCredentials::extractCredentials(uri, username, password);
HTTPCredentials cred(username, password);
cred.authenticate(req, res);
}
req.set("User-Agent", Poco::format("poco/%d.%d.%d",
(POCO_VERSION >> 24) & 0xFF,
(POCO_VERSION >> 16) & 0xFF,
(POCO_VERSION >> 8) & 0xFF));
req.set("Accept", "*/*");
pSession->sendRequest(req);
std::istream& rs = pSession->receiveResponse(res);
bool moved = (res.getStatus() == HTTPResponse::HTTP_MOVED_PERMANENTLY ||
res.getStatus() == HTTPResponse::HTTP_FOUND ||
res.getStatus() == HTTPResponse::HTTP_SEE_OTHER ||
res.getStatus() == HTTPResponse::HTTP_TEMPORARY_REDIRECT);
if (moved)
{
resolvedURI.resolve(res.get("Location"));
if (!username.empty())
{
resolvedURI.setUserInfo(username + ":" + password);
authorize = false;
}
delete pSession;
pSession = 0;
++redirects;
retry = true;
}
else if (res.getStatus() == HTTPResponse::HTTP_OK)
{
return new HTTPResponseStream(rs, pSession);
}
else if (res.getStatus() == HTTPResponse::HTTP_USEPROXY && !retry)
{
// The requested resource MUST be accessed through the proxy
// given by the Location field. The Location field gives the
// URI of the proxy. The recipient is expected to repeat this
// single request via the proxy. 305 responses MUST only be generated by origin servers.
// only use for one single request!
proxyUri.resolve(res.get("Location"));
delete pSession;
pSession = 0;
retry = true; // only allow useproxy once
}
else if (res.getStatus() == HTTPResponse::HTTP_UNAUTHORIZED && !authorize)
{
authorize = true;
retry = true;
Poco::NullOutputStream null;
Poco::StreamCopier::copyStream(rs, null);
}
else throw HTTPException(res.getReason(), uri.toString());
}
while (retry && redirects < MAX_REDIRECTS);
throw HTTPException("Too many redirects", uri.toString());
}
catch (...)
{
delete pSession;
throw;
}
}
void HTTPSStreamFactory::registerFactory()
{
URIStreamOpener::defaultOpener().registerStreamFactory("https", new HTTPSStreamFactory);
}
void HTTPSStreamFactory::unregisterFactory()
{
URIStreamOpener::defaultOpener().unregisterStreamFactory("https");
}
} } // namespace Poco::Net
|
apache-2.0
|
amedia/meteo
|
meteo-jaxb/src/main/java/no/api/meteo/jaxb/temperatureverification/v1_0/Windspeed.java
|
4167
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2018.02.17 at 03:24:41 PM CET
//
package no.api.meteo.jaxb.temperatureverification.v1_0;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* Element denoting the wind speed by name, meters per second or the Beaufort scale.
*
*
* <p>Java class for windspeed complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="windspeed">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="mps" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}decimal">
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="name">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="beaufort">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <minInclusive value="0"/>
* <maxInclusive value="12"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "windspeed")
public class Windspeed {
@XmlAttribute(name = "mps", required = true)
protected BigDecimal mps;
@XmlAttribute(name = "name")
protected String name;
@XmlAttribute(name = "beaufort")
protected Integer beaufort;
@XmlAttribute(name = "id")
protected String id;
/**
* Gets the value of the mps property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getMps() {
return mps;
}
/**
* Sets the value of the mps property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setMps(BigDecimal value) {
this.mps = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the beaufort property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getBeaufort() {
return beaufort;
}
/**
* Sets the value of the beaufort property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setBeaufort(Integer value) {
this.beaufort = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
}
|
apache-2.0
|
stackforge/cloudbase-init
|
cloudbaseinit/constant.py
|
1737
|
# Copyright 2016 Cloudbase Solutions Srl
#
# 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.
# Config Drive types and possible locations.
CD_TYPES = {
"vfat", # Visible device (with partition table).
"iso", # "Raw" format containing ISO bytes.
}
CD_LOCATIONS = {
# Look into optical devices. Only an ISO format could be
# used here (vfat ignored).
"cdrom",
# Search through physical disks for raw ISO content or vfat filesystems
# containing configuration drive's content.
"hdd",
# Search through partitions for raw ISO content or through volumes
# containing configuration drive's content.
"partition",
}
POLICY_IGNORE_ALL_FAILURES = "ignoreallfailures"
SAN_POLICY_ONLINE_STR = 'OnlineAll'
SAN_POLICY_OFFLINE_STR = 'OfflineAll'
SAN_POLICY_OFFLINE_SHARED_STR = 'OfflineShared'
CLEAR_TEXT_INJECTED_ONLY = 'clear_text_injected_only'
ALWAYS_CHANGE = 'always'
NEVER_CHANGE = 'no'
LOGON_PASSWORD_CHANGE_OPTIONS = [CLEAR_TEXT_INJECTED_ONLY, NEVER_CHANGE,
ALWAYS_CHANGE]
VOL_ACT_KMS = "KMS"
VOL_ACT_AVMA = "AVMA"
CERT_LOCATION_LOCAL_MACHINE = "LocalMachine"
CERT_LOCATION_CURRENT_USER = "CurrentUser"
SCRIPT_HEADER_CMD = 'rem cmd'
|
apache-2.0
|
cedral/aws-sdk-cpp
|
aws-cpp-sdk-ds/source/model/DescribeLDAPSSettingsRequest.cpp
|
1835
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#include <aws/ds/model/DescribeLDAPSSettingsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::DirectoryService::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DescribeLDAPSSettingsRequest::DescribeLDAPSSettingsRequest() :
m_directoryIdHasBeenSet(false),
m_type(LDAPSType::NOT_SET),
m_typeHasBeenSet(false),
m_nextTokenHasBeenSet(false),
m_limit(0),
m_limitHasBeenSet(false)
{
}
Aws::String DescribeLDAPSSettingsRequest::SerializePayload() const
{
JsonValue payload;
if(m_directoryIdHasBeenSet)
{
payload.WithString("DirectoryId", m_directoryId);
}
if(m_typeHasBeenSet)
{
payload.WithString("Type", LDAPSTypeMapper::GetNameForLDAPSType(m_type));
}
if(m_nextTokenHasBeenSet)
{
payload.WithString("NextToken", m_nextToken);
}
if(m_limitHasBeenSet)
{
payload.WithInteger("Limit", m_limit);
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection DescribeLDAPSSettingsRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "DirectoryService_20150416.DescribeLDAPSSettings"));
return headers;
}
|
apache-2.0
|
arpg/Gazebo
|
gazebo/physics/dart/DARTMultiRayShape.hh
|
1763
|
/*
* Copyright 2014 Open Source Robotics Foundation
*
* 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.
*
*/
#ifndef _GAZEBO_DARTMULTIRAYSHAPE_HH_
#define _GAZEBO_DARTMULTIRAYSHAPE_HH_
#include "gazebo/physics/MultiRayShape.hh"
#include "gazebo/physics/dart/DARTTypes.hh"
#include "gazebo/util/system.hh"
namespace gazebo
{
namespace physics
{
/// \ingroup gazebo_physics
/// \addtogroup gazebo_physics_bullet Bullet Physics
/// \{
/// \brief DART specific version of MultiRayShape
class GAZEBO_VISIBLE DARTMultiRayShape : public MultiRayShape
{
/// \brief Constructor.
/// \param[in] _parent Parent Collision.
public: explicit DARTMultiRayShape(CollisionPtr _parent);
/// \brief Destructor.
public: virtual ~DARTMultiRayShape();
// Documentation inherited.
public: virtual void UpdateRays();
/// \brief Add a ray to the collision.
/// \param[in] _start Start location of the ray.
/// \param[in] _end End location of the ray.
protected: void AddRay(const math::Vector3 &_start,
const math::Vector3 &_end);
/// \brief Pointer to the DART physics engine.
private: DARTPhysicsPtr physicsEngine;
};
}
}
#endif
|
apache-2.0
|
hmusavi/jpo-ode
|
jpo-ode-plugins/src/test/java/us/dot/its/jpo/ode/plugin/j2735/builders/MassOrWeightBuilderTest.java
|
10656
|
package us.dot.its.jpo.ode.plugin.j2735.builders;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import org.junit.Test;
import com.fasterxml.jackson.databind.node.ObjectNode;
import us.dot.its.jpo.ode.util.JsonUtils;
public class MassOrWeightBuilderTest {
// TrailerMass tests
/**
* Test that an undefined trailer mass value of (0) returns (null)
*/
@Test
public void shouldReturnUndefinedTrailerMass() {
ObjectNode testInput = JsonUtils.newNode().put("mass", 0);
Integer expectedValue = null;
Integer actualValue = MassOrWeightBuilder.genericTrailerMass(testInput.get("mass"));
assertEquals(expectedValue, actualValue);
}
/**
* Test that a minimum trailer mass of (1) returns (500)
*/
@Test
public void shouldReturnMinimumTrailerMass() {
//
ObjectNode testInput = JsonUtils.newNode().put("mass", 1);
Integer expectedValue = 500;
Integer actualValue = MassOrWeightBuilder.genericTrailerMass(testInput.get("mass"));
assertEquals(expectedValue, actualValue);
}
/**
* Test that a maximum trailer mass of (254) returns (127000)
*/
@Test
public void shouldReturnMaximumTrailerMass() {
ObjectNode testInput = JsonUtils.newNode().put("mass", 254);
Integer expectedValue = 127000;
Integer actualValue = MassOrWeightBuilder.genericTrailerMass(testInput.get("mass"));
assertEquals(expectedValue, actualValue);
}
/**
* Test that a trailer mass of (255) indicates a trailer mass larger than
* (127000)
*/
@Test
public void shouldReturnLargerTrailerMass() {
ObjectNode testInput = JsonUtils.newNode().put("mass", 255);
Integer expectedValue = 127000;
Integer actualValue = MassOrWeightBuilder.genericTrailerMass(testInput.get("mass"));
assertTrue(actualValue > expectedValue);
}
/**
* Test that a known trailer mass of (123) returns (61500)
*/
@Test
public void shouldReturnKnownTrailerMass() {
ObjectNode testInput = JsonUtils.newNode().put("mass", 123);
Integer expectedValue = 61500;
Integer actualValue = MassOrWeightBuilder.genericTrailerMass(testInput.get("mass"));
assertEquals(expectedValue, actualValue);
}
/**
* Test that an invalid trailer mass below (0) throws an exception
*/
@Test
public void shouldThrowExceptionTrailerMassBelowLowerBound() {
ObjectNode testInput = JsonUtils.newNode().put("mass", -1);
try {
MassOrWeightBuilder.genericTrailerMass(testInput.get("mass"));
fail("Expected IllegalArgumentException");
} catch (RuntimeException e) {
assertEquals(IllegalArgumentException.class, e.getClass());
}
}
/**
* Test that an invalid trailer mass above (255) throws an exception
*/
@Test
public void shouldThrowExceptionTrailerMassAboveUpperBound() {
ObjectNode testInput = JsonUtils.newNode().put("mass", 256);
try {
MassOrWeightBuilder.genericTrailerMass(testInput.get("mass"));
fail("Expected IllegalArgumentException");
} catch (RuntimeException e) {
assertEquals(IllegalArgumentException.class, e.getClass());
}
}
// TrailerWeight tests
/**
* Test that a minimum trailer weight of (0) returns (0)
*/
@Test
public void shouldReturnMinimumTrailerWeight() {
ObjectNode testInput = JsonUtils.newNode().put("weight", 0);
Integer expectedValue = 0;
Integer actualValue = MassOrWeightBuilder.genericTrailerWeight(testInput.get("weight"));
assertEquals(expectedValue, actualValue);
}
/**
* Test that a maximum trailer weight of (64255) returns (128510)
*/
@Test
public void shouldReturnMaximumTrailerWeight() {
ObjectNode testInput = JsonUtils.newNode().put("weight", 64255);
Integer expectedValue = 128510;
Integer actualValue = MassOrWeightBuilder.genericTrailerWeight(testInput.get("weight"));
assertEquals(expectedValue, actualValue);
}
/**
* Test that a known trailer weight of (12500) returns (25000)
*/
@Test
public void shouldReturnKnownTrailerWeight() {
ObjectNode testInput = JsonUtils.newNode().put("weight", 12500);
Integer expectedValue = 25000;
Integer actualValue = MassOrWeightBuilder.genericTrailerWeight(testInput.get("weight"));
assertEquals(expectedValue, actualValue);
}
/**
* Test that an invalid trailer weight below (0) throws an exception
*/
@Test
public void shouldThrowExceptionTrailerWeightBelowLowerBound() {
ObjectNode testInput = JsonUtils.newNode().put("weight", -1);
try {
MassOrWeightBuilder.genericTrailerWeight(testInput.get("weight"));
fail("Expected IllegalArgumentException");
} catch (RuntimeException e) {
assertEquals(IllegalArgumentException.class, e.getClass());
}
}
/**
* Test that an invalid trailer weight above (64255) throws an exception
*/
@Test
public void shouldThrowExceptionTrailerWeightAboveUpperBound() {
ObjectNode testInput = JsonUtils.newNode().put("weight", 64256);
try {
MassOrWeightBuilder.genericTrailerWeight(testInput.get("weight"));
fail("Expected IllegalArgumentException");
} catch (RuntimeException e) {
assertEquals(IllegalArgumentException.class, e.getClass());
}
}
// VehicleMass tests
/**
* Test that an input vehicle mass in lowest 50kg step range of (0) returns
* (0)
*/
@Test
public void shouldReturnMinimumVehicleMass50KGStep() {
ObjectNode testInput = JsonUtils.newNode().put("mass", 0);
Integer expectedValue = 0;
Integer actualValue = MassOrWeightBuilder.genericVehicleMass(testInput.get("mass"));
assertEquals(expectedValue, actualValue);
}
/**
* Test that an input vehicle mass in highest 50kg step range of (80) returns
* (4000)
*/
@Test
public void shouldReturnMaximumVehicleMass50KGStep() {
ObjectNode testInput = JsonUtils.newNode().put("mass", 80);
Integer expectedValue = 4000;
Integer actualValue = MassOrWeightBuilder.genericVehicleMass(testInput.get("mass"));
assertEquals(expectedValue, actualValue);
}
/**
* Test that an input vehicle mass in lowest 500kg step range of (81) returns
* (4500)
*/
@Test
public void shouldReturnMinimumVehicleMass500KGStep() {
ObjectNode testInput = JsonUtils.newNode().put("mass", 81);
Integer expectedValue = 4500;
Integer actualValue = MassOrWeightBuilder.genericVehicleMass(testInput.get("mass"));
assertEquals(expectedValue, actualValue);
}
/**
* Test that an input vehicle mass in highest 500kg step range of (200)
* returns (64000)
*/
@Test
public void shouldReturnMaximumVehicleMass500KGStep() {
ObjectNode testInput = JsonUtils.newNode().put("mass", 200);
Integer expectedValue = 64000;
Integer actualValue = MassOrWeightBuilder.genericVehicleMass(testInput.get("mass"));
assertEquals(expectedValue, actualValue);
}
/**
* Test that an input vehicle mass in lowest 2000kg step range of (201)
* returns (66000)
*/
@Test
public void shouldReturnMinimumVehicleMass2000KGStep() {
ObjectNode testInput = JsonUtils.newNode().put("mass", 201);
Integer expectedValue = 66000;
Integer actualValue = MassOrWeightBuilder.genericVehicleMass(testInput.get("mass"));
assertEquals(expectedValue, actualValue);
}
/**
* Test that an input vehicle mass in highest 2000kg step range of (253)
* returns (170000)
*/
@Test
public void shouldReturnMaximumVehicleMass2000KGStep() {
ObjectNode testInput = JsonUtils.newNode().put("mass", 253);
Integer expectedValue = 170000;
Integer actualValue = MassOrWeightBuilder.genericVehicleMass(testInput.get("mass"));
assertEquals(expectedValue, actualValue);
}
/**
* Test that an input vehicle mass of (254) signifies a vehicle mass greater
* than (170000)
*/
@Test
public void shouldReturnLargerVehicleMass() {
ObjectNode testInput = JsonUtils.newNode().put("mass", 254);
Integer expectedValue = 170000;
Integer actualValue = MassOrWeightBuilder.genericVehicleMass(testInput.get("mass"));
assertTrue(actualValue > expectedValue);
}
/**
* Test that an input vehicle mass of (255) signifies an undefined vehicle
* mass (null)
*/
@Test
public void shouldReturnUndefinedVehicleMass() {
ObjectNode testInput = JsonUtils.newNode().put("mass", 255);
Integer actualValue = MassOrWeightBuilder.genericVehicleMass(testInput.get("mass"));
assertNull(actualValue);
}
/**
* Test that an input vehicle mass below (0) throws an exception
*/
@Test
public void shouldThrowExceptionVehicleMassBelowLowerBound() {
ObjectNode testInput = JsonUtils.newNode().put("mass", -1);
try {
MassOrWeightBuilder.genericVehicleMass(testInput.get("mass"));
fail("Expected IllegalArgumentException");
} catch (RuntimeException e) {
assertEquals(IllegalArgumentException.class, e.getClass());
}
}
/**
* Test that an input vehicle mass above (255) throws an exception
*/
@Test
public void shouldThrowExceptionVehicleMassAboveUpperBound() {
ObjectNode testInput = JsonUtils.newNode().put("mass", 256);
try {
MassOrWeightBuilder.genericVehicleMass(testInput.get("mass"));
fail("Expected IllegalArgumentException");
} catch (RuntimeException e) {
assertEquals(IllegalArgumentException.class, e.getClass());
}
}
@Test
public void testConstructorIsPrivate()
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Constructor<MassOrWeightBuilder> constructor = MassOrWeightBuilder.class.getDeclaredConstructor();
assertTrue(Modifier.isPrivate(constructor.getModifiers()));
constructor.setAccessible(true);
try {
constructor.newInstance();
fail("Expected IllegalAccessException.class");
} catch (Exception e) {
assertEquals(InvocationTargetException.class, e.getClass());
}
}
}
|
apache-2.0
|
Orbittman/MockResponse
|
MockResponse.Core/Utilities/DateTimeProvider.cs
|
222
|
using System;
namespace MockResponse.Core.Utilities
{
public class DateTimeProvider : IDateTimeProvider
{
public DateTime Now => DateTime.Now;
public DateTime UtcNow => DateTime.UtcNow;
}
}
|
apache-2.0
|
tensorflow/tfjs
|
tfjs-backend-wasm/src/cc/kernels/ResizeBilinear_test.cc
|
3867
|
/* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ===========================================================================*/
#include <gtest/gtest.h>
#include <cstddef>
#include <vector>
#include "tfjs-backend-wasm/src/cc/backend.h"
#include "tfjs-backend-wasm/src/cc/kernels/ResizeBilinear.h"
TEST(BATCH_MATMUL, xnn_operator_lifetime) {
tfjs::wasm::init();
ASSERT_EQ(0, tfjs::backend::num_tensors());
const size_t x0_id = 1;
const size_t x1_id = 2;
const size_t x_size = 4;
float x_values[x_size] = {1, 2, 2, 2};
const size_t out_id = 3;
const size_t out_size = 8;
float out_values[out_size] = {0, 0, 0, 0, 0, 0, 0, 0};
tfjs::wasm::register_tensor(x0_id, x_size, x_values);
tfjs::wasm::register_tensor(x1_id, x_size, x_values);
tfjs::wasm::register_tensor(out_id, out_size, out_values);
ASSERT_EQ(3, tfjs::backend::num_tensors());
ASSERT_EQ(0, tfjs::backend::xnn_operator_count);
const size_t batch_size = 1;
// One new xnn_operator should be created for the first call to
// ResizeBilinear.
const size_t old_height0 = 2;
const size_t old_width0 = 1;
const size_t num_channels0 = 2;
const size_t new_height0 = 2;
const size_t new_width0 = 2;
bool align_corners0 = false;
bool half_pixel_centers0 = false;
tfjs::wasm::ResizeBilinear(x0_id, batch_size, old_height0, old_width0,
num_channels0, new_height0, new_width0,
align_corners0, half_pixel_centers0, out_id);
ASSERT_EQ(1, tfjs::backend::xnn_operator_count);
// No new xnn_operators should be created for the second call to
// ResizeBilinear with the same arguments.
tfjs::wasm::ResizeBilinear(x0_id, batch_size, old_height0, old_width0,
num_channels0, new_height0, new_width0,
align_corners0, half_pixel_centers0, out_id);
ASSERT_EQ(1, tfjs::backend::xnn_operator_count);
// No new xnn_operators should be created for the second call to
// ResizeBilinear with a new x id but same arguments.
tfjs::wasm::ResizeBilinear(x1_id, batch_size, old_height0, old_width0,
num_channels0, new_height0, new_width0,
align_corners0, half_pixel_centers0, out_id);
ASSERT_EQ(1, tfjs::backend::xnn_operator_count);
// One new xnn_operator should be created for another call to ResizeBilinear
// with a different num_channels argument.
const size_t old_height1 = 2;
const size_t old_width1 = 2;
const size_t num_channels1 = 1;
const size_t new_height1 = 2;
const size_t new_width1 = 4;
tfjs::wasm::ResizeBilinear(x0_id, batch_size, old_height1, old_width1,
num_channels1, new_height1, new_width1,
align_corners0, half_pixel_centers0, out_id);
ASSERT_EQ(2, tfjs::backend::xnn_operator_count);
// One new xnn_operator should be created for another call to ResizeBilinear
// with a different align_corners argument
bool align_corners1 = true;
tfjs::wasm::ResizeBilinear(x0_id, batch_size, old_height1, old_width1,
num_channels1, new_height1, new_width1,
align_corners1, half_pixel_centers0, out_id);
ASSERT_EQ(3, tfjs::backend::xnn_operator_count);
tfjs::wasm::dispose();
}
|
apache-2.0
|
Sargul/dbeaver
|
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/edit/SQLDatabasePersistActionComment.java
|
1173
|
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2021 DBeaver Corp and others
*
* 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.jkiss.dbeaver.model.impl.edit;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.sql.SQLUtils;
/**
* Comment action
*/
public class SQLDatabasePersistActionComment extends SQLDatabasePersistAction {
public SQLDatabasePersistActionComment(DBPDataSource dataSource, String comment) {
super("Comment",
SQLUtils.getDialectFromDataSource(dataSource).getSingleLineComments()[0] + " " + comment,
ActionType.COMMENT,
false);
}
}
|
apache-2.0
|
knuppe/SharpNL
|
src/SharpNL/Utility/FeatureGen/IAdaptiveFeatureGenerator.cs
|
3334
|
//
// Copyright 2014 Gustavo J Knuppe (https://github.com/knuppe)
//
// 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.
//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - May you do good and not evil. -
// - May you find forgiveness for yourself and forgive others. -
// - May you share freely, never taking more than you give. -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
using System.Collections.Generic;
namespace SharpNL.Utility.FeatureGen {
/// <summary>
/// An interface for generating features for name entity identification and for
/// updating document level contexts.
/// </summary>
/// <remarks>
/// Most implementors do not need the adaptive functionality of this
/// interface, they should extend the <see cref="FeatureGeneratorAdapter"/> class instead.
///
/// Feature generation is not thread safe and a instance of a feature generator
/// must only be called from one thread. The resources used by a feature
/// generator are typically shared between man instances of features generators
/// which are called from many threads and have to be thread safe.
/// </remarks>
/// <seealso cref="FeatureGeneratorAdapter"/>
public interface IAdaptiveFeatureGenerator {
/// <summary>
/// Adds the appropriate features for the token at the specified index with the
/// specified array of previous outcomes to the specified list of features.
/// </summary>
/// <param name="features">The list of features to be added to.</param>
/// <param name="tokens">The tokens of the sentence or other text unit being processed.</param>
/// <param name="index">The index of the token which is currently being processed.</param>
/// <param name="previousOutcomes">The outcomes for the tokens prior to the specified index.</param>
void CreateFeatures(List<string> features, string[] tokens, int index, string[] previousOutcomes);
/// <summary>
/// Informs the feature generator that the specified tokens have been classified with the
/// corresponding set of specified outcomes.
/// </summary>
/// <param name="tokens">The tokens of the sentence or other text unit which has been processed.</param>
/// <param name="outcomes">The outcomes associated with the specified tokens.</param>
void UpdateAdaptiveData(string[] tokens, string[] outcomes);
/// <summary>
/// Informs the feature generator that the context of the adaptive data (typically a document)
/// is no longer valid.
/// </summary>
void ClearAdaptiveData();
}
}
|
apache-2.0
|
taktos/ea2ddl
|
ea2ddl-dao/src/main/java/jp/sourceforge/ea2ddl/dao/cbean/cq/bs/BsTConnectorCQ.java
|
53489
|
package jp.sourceforge.ea2ddl.dao.cbean.cq.bs;
import java.util.Map;
import org.seasar.dbflute.cbean.*;
import org.seasar.dbflute.cbean.cvalue.ConditionValue;
import org.seasar.dbflute.cbean.sqlclause.SqlClause;
import jp.sourceforge.ea2ddl.dao.cbean.cq.ciq.*;
import jp.sourceforge.ea2ddl.dao.cbean.*;
import jp.sourceforge.ea2ddl.dao.cbean.cq.*;
/**
* The base condition-query of t_connector.
* @author DBFlute(AutoGenerator)
*/
public class BsTConnectorCQ extends AbstractBsTConnectorCQ {
// ===================================================================================
// Attribute
// =========
protected TConnectorCIQ _inlineQuery;
// ===================================================================================
// Constructor
// ===========
public BsTConnectorCQ(ConditionQuery childQuery, SqlClause sqlClause, String aliasName, int nestLevel) {
super(childQuery, sqlClause, aliasName, nestLevel);
}
// ===================================================================================
// Inline
// ======
/**
* Prepare inline query. <br />
* {select ... from ... left outer join (select * from t_connector) where abc = [abc] ...}
* @return Inline query. (NotNull)
*/
public TConnectorCIQ inline() {
if (_inlineQuery == null) {
_inlineQuery = new TConnectorCIQ(getChildQuery(), getSqlClause(), getAliasName(), getNestLevel(), this);
}
_inlineQuery.xsetOnClauseInline(false); return _inlineQuery;
}
/**
* Prepare on-clause query. <br />
* {select ... from ... left outer join t_connector on ... and abc = [abc] ...}
* @return On-clause query. (NotNull)
*/
public TConnectorCIQ on() {
if (isBaseQuery(this)) { throw new UnsupportedOperationException("Unsupported on-clause for local table!"); }
TConnectorCIQ inlineQuery = inline(); inlineQuery.xsetOnClauseInline(true); return inlineQuery;
}
// ===================================================================================
// Query
// =====
protected ConditionValue _connectorId;
public ConditionValue getConnectorId() {
if (_connectorId == null) { _connectorId = new ConditionValue(); }
return _connectorId;
}
protected ConditionValue getCValueConnectorId() { return getConnectorId(); }
public BsTConnectorCQ addOrderBy_ConnectorId_Asc() { regOBA("Connector_ID"); return this; }
public BsTConnectorCQ addOrderBy_ConnectorId_Desc() { regOBD("Connector_ID"); return this; }
protected ConditionValue _name;
public ConditionValue getName() {
if (_name == null) { _name = new ConditionValue(); }
return _name;
}
protected ConditionValue getCValueName() { return getName(); }
public BsTConnectorCQ addOrderBy_Name_Asc() { regOBA("Name"); return this; }
public BsTConnectorCQ addOrderBy_Name_Desc() { regOBD("Name"); return this; }
protected ConditionValue _direction;
public ConditionValue getDirection() {
if (_direction == null) { _direction = new ConditionValue(); }
return _direction;
}
protected ConditionValue getCValueDirection() { return getDirection(); }
public BsTConnectorCQ addOrderBy_Direction_Asc() { regOBA("Direction"); return this; }
public BsTConnectorCQ addOrderBy_Direction_Desc() { regOBD("Direction"); return this; }
protected ConditionValue _notes;
public ConditionValue getNotes() {
if (_notes == null) { _notes = new ConditionValue(); }
return _notes;
}
protected ConditionValue getCValueNotes() { return getNotes(); }
public BsTConnectorCQ addOrderBy_Notes_Asc() { regOBA("Notes"); return this; }
public BsTConnectorCQ addOrderBy_Notes_Desc() { regOBD("Notes"); return this; }
protected ConditionValue _connectorType;
public ConditionValue getConnectorType() {
if (_connectorType == null) { _connectorType = new ConditionValue(); }
return _connectorType;
}
protected ConditionValue getCValueConnectorType() { return getConnectorType(); }
public BsTConnectorCQ addOrderBy_ConnectorType_Asc() { regOBA("Connector_Type"); return this; }
public BsTConnectorCQ addOrderBy_ConnectorType_Desc() { regOBD("Connector_Type"); return this; }
protected ConditionValue _subtype;
public ConditionValue getSubtype() {
if (_subtype == null) { _subtype = new ConditionValue(); }
return _subtype;
}
protected ConditionValue getCValueSubtype() { return getSubtype(); }
public BsTConnectorCQ addOrderBy_Subtype_Asc() { regOBA("SubType"); return this; }
public BsTConnectorCQ addOrderBy_Subtype_Desc() { regOBD("SubType"); return this; }
protected ConditionValue _sourcecard;
public ConditionValue getSourcecard() {
if (_sourcecard == null) { _sourcecard = new ConditionValue(); }
return _sourcecard;
}
protected ConditionValue getCValueSourcecard() { return getSourcecard(); }
public BsTConnectorCQ addOrderBy_Sourcecard_Asc() { regOBA("SourceCard"); return this; }
public BsTConnectorCQ addOrderBy_Sourcecard_Desc() { regOBD("SourceCard"); return this; }
protected ConditionValue _sourceaccess;
public ConditionValue getSourceaccess() {
if (_sourceaccess == null) { _sourceaccess = new ConditionValue(); }
return _sourceaccess;
}
protected ConditionValue getCValueSourceaccess() { return getSourceaccess(); }
public BsTConnectorCQ addOrderBy_Sourceaccess_Asc() { regOBA("SourceAccess"); return this; }
public BsTConnectorCQ addOrderBy_Sourceaccess_Desc() { regOBD("SourceAccess"); return this; }
protected ConditionValue _sourceelement;
public ConditionValue getSourceelement() {
if (_sourceelement == null) { _sourceelement = new ConditionValue(); }
return _sourceelement;
}
protected ConditionValue getCValueSourceelement() { return getSourceelement(); }
public BsTConnectorCQ addOrderBy_Sourceelement_Asc() { regOBA("SourceElement"); return this; }
public BsTConnectorCQ addOrderBy_Sourceelement_Desc() { regOBD("SourceElement"); return this; }
protected ConditionValue _destcard;
public ConditionValue getDestcard() {
if (_destcard == null) { _destcard = new ConditionValue(); }
return _destcard;
}
protected ConditionValue getCValueDestcard() { return getDestcard(); }
public BsTConnectorCQ addOrderBy_Destcard_Asc() { regOBA("DestCard"); return this; }
public BsTConnectorCQ addOrderBy_Destcard_Desc() { regOBD("DestCard"); return this; }
protected ConditionValue _destaccess;
public ConditionValue getDestaccess() {
if (_destaccess == null) { _destaccess = new ConditionValue(); }
return _destaccess;
}
protected ConditionValue getCValueDestaccess() { return getDestaccess(); }
public BsTConnectorCQ addOrderBy_Destaccess_Asc() { regOBA("DestAccess"); return this; }
public BsTConnectorCQ addOrderBy_Destaccess_Desc() { regOBD("DestAccess"); return this; }
protected ConditionValue _destelement;
public ConditionValue getDestelement() {
if (_destelement == null) { _destelement = new ConditionValue(); }
return _destelement;
}
protected ConditionValue getCValueDestelement() { return getDestelement(); }
public BsTConnectorCQ addOrderBy_Destelement_Asc() { regOBA("DestElement"); return this; }
public BsTConnectorCQ addOrderBy_Destelement_Desc() { regOBD("DestElement"); return this; }
protected ConditionValue _sourcerole;
public ConditionValue getSourcerole() {
if (_sourcerole == null) { _sourcerole = new ConditionValue(); }
return _sourcerole;
}
protected ConditionValue getCValueSourcerole() { return getSourcerole(); }
protected Map<String, TOperationCQ> _sourcerole_InScopeSubQuery_TOperationBySourceroleMap;
public Map<String, TOperationCQ> getSourcerole_InScopeSubQuery_TOperationBySourcerole() { return _sourcerole_InScopeSubQuery_TOperationBySourceroleMap; }
public String keepSourcerole_InScopeSubQuery_TOperationBySourcerole(TOperationCQ subQuery) {
if (_sourcerole_InScopeSubQuery_TOperationBySourceroleMap == null) { _sourcerole_InScopeSubQuery_TOperationBySourceroleMap = newLinkedHashMap(); }
String key = "subQueryMapKey" + (_sourcerole_InScopeSubQuery_TOperationBySourceroleMap.size() + 1);
_sourcerole_InScopeSubQuery_TOperationBySourceroleMap.put(key, subQuery); return "sourcerole_InScopeSubQuery_TOperationBySourcerole." + key;
}
public BsTConnectorCQ addOrderBy_Sourcerole_Asc() { regOBA("SourceRole"); return this; }
public BsTConnectorCQ addOrderBy_Sourcerole_Desc() { regOBD("SourceRole"); return this; }
protected ConditionValue _sourceroletype;
public ConditionValue getSourceroletype() {
if (_sourceroletype == null) { _sourceroletype = new ConditionValue(); }
return _sourceroletype;
}
protected ConditionValue getCValueSourceroletype() { return getSourceroletype(); }
public BsTConnectorCQ addOrderBy_Sourceroletype_Asc() { regOBA("SourceRoleType"); return this; }
public BsTConnectorCQ addOrderBy_Sourceroletype_Desc() { regOBD("SourceRoleType"); return this; }
protected ConditionValue _sourcerolenote;
public ConditionValue getSourcerolenote() {
if (_sourcerolenote == null) { _sourcerolenote = new ConditionValue(); }
return _sourcerolenote;
}
protected ConditionValue getCValueSourcerolenote() { return getSourcerolenote(); }
public BsTConnectorCQ addOrderBy_Sourcerolenote_Asc() { regOBA("SourceRoleNote"); return this; }
public BsTConnectorCQ addOrderBy_Sourcerolenote_Desc() { regOBD("SourceRoleNote"); return this; }
protected ConditionValue _sourcecontainment;
public ConditionValue getSourcecontainment() {
if (_sourcecontainment == null) { _sourcecontainment = new ConditionValue(); }
return _sourcecontainment;
}
protected ConditionValue getCValueSourcecontainment() { return getSourcecontainment(); }
public BsTConnectorCQ addOrderBy_Sourcecontainment_Asc() { regOBA("SourceContainment"); return this; }
public BsTConnectorCQ addOrderBy_Sourcecontainment_Desc() { regOBD("SourceContainment"); return this; }
protected ConditionValue _sourceisaggregate;
public ConditionValue getSourceisaggregate() {
if (_sourceisaggregate == null) { _sourceisaggregate = new ConditionValue(); }
return _sourceisaggregate;
}
protected ConditionValue getCValueSourceisaggregate() { return getSourceisaggregate(); }
public BsTConnectorCQ addOrderBy_Sourceisaggregate_Asc() { regOBA("SourceIsAggregate"); return this; }
public BsTConnectorCQ addOrderBy_Sourceisaggregate_Desc() { regOBD("SourceIsAggregate"); return this; }
protected ConditionValue _sourceisordered;
public ConditionValue getSourceisordered() {
if (_sourceisordered == null) { _sourceisordered = new ConditionValue(); }
return _sourceisordered;
}
protected ConditionValue getCValueSourceisordered() { return getSourceisordered(); }
public BsTConnectorCQ addOrderBy_Sourceisordered_Asc() { regOBA("SourceIsOrdered"); return this; }
public BsTConnectorCQ addOrderBy_Sourceisordered_Desc() { regOBD("SourceIsOrdered"); return this; }
protected ConditionValue _sourcequalifier;
public ConditionValue getSourcequalifier() {
if (_sourcequalifier == null) { _sourcequalifier = new ConditionValue(); }
return _sourcequalifier;
}
protected ConditionValue getCValueSourcequalifier() { return getSourcequalifier(); }
public BsTConnectorCQ addOrderBy_Sourcequalifier_Asc() { regOBA("SourceQualifier"); return this; }
public BsTConnectorCQ addOrderBy_Sourcequalifier_Desc() { regOBD("SourceQualifier"); return this; }
protected ConditionValue _destrole;
public ConditionValue getDestrole() {
if (_destrole == null) { _destrole = new ConditionValue(); }
return _destrole;
}
protected ConditionValue getCValueDestrole() { return getDestrole(); }
protected Map<String, TOperationCQ> _destrole_InScopeSubQuery_TOperationByDestroleMap;
public Map<String, TOperationCQ> getDestrole_InScopeSubQuery_TOperationByDestrole() { return _destrole_InScopeSubQuery_TOperationByDestroleMap; }
public String keepDestrole_InScopeSubQuery_TOperationByDestrole(TOperationCQ subQuery) {
if (_destrole_InScopeSubQuery_TOperationByDestroleMap == null) { _destrole_InScopeSubQuery_TOperationByDestroleMap = newLinkedHashMap(); }
String key = "subQueryMapKey" + (_destrole_InScopeSubQuery_TOperationByDestroleMap.size() + 1);
_destrole_InScopeSubQuery_TOperationByDestroleMap.put(key, subQuery); return "destrole_InScopeSubQuery_TOperationByDestrole." + key;
}
public BsTConnectorCQ addOrderBy_Destrole_Asc() { regOBA("DestRole"); return this; }
public BsTConnectorCQ addOrderBy_Destrole_Desc() { regOBD("DestRole"); return this; }
protected ConditionValue _destroletype;
public ConditionValue getDestroletype() {
if (_destroletype == null) { _destroletype = new ConditionValue(); }
return _destroletype;
}
protected ConditionValue getCValueDestroletype() { return getDestroletype(); }
public BsTConnectorCQ addOrderBy_Destroletype_Asc() { regOBA("DestRoleType"); return this; }
public BsTConnectorCQ addOrderBy_Destroletype_Desc() { regOBD("DestRoleType"); return this; }
protected ConditionValue _destrolenote;
public ConditionValue getDestrolenote() {
if (_destrolenote == null) { _destrolenote = new ConditionValue(); }
return _destrolenote;
}
protected ConditionValue getCValueDestrolenote() { return getDestrolenote(); }
public BsTConnectorCQ addOrderBy_Destrolenote_Asc() { regOBA("DestRoleNote"); return this; }
public BsTConnectorCQ addOrderBy_Destrolenote_Desc() { regOBD("DestRoleNote"); return this; }
protected ConditionValue _destcontainment;
public ConditionValue getDestcontainment() {
if (_destcontainment == null) { _destcontainment = new ConditionValue(); }
return _destcontainment;
}
protected ConditionValue getCValueDestcontainment() { return getDestcontainment(); }
public BsTConnectorCQ addOrderBy_Destcontainment_Asc() { regOBA("DestContainment"); return this; }
public BsTConnectorCQ addOrderBy_Destcontainment_Desc() { regOBD("DestContainment"); return this; }
protected ConditionValue _destisaggregate;
public ConditionValue getDestisaggregate() {
if (_destisaggregate == null) { _destisaggregate = new ConditionValue(); }
return _destisaggregate;
}
protected ConditionValue getCValueDestisaggregate() { return getDestisaggregate(); }
public BsTConnectorCQ addOrderBy_Destisaggregate_Asc() { regOBA("DestIsAggregate"); return this; }
public BsTConnectorCQ addOrderBy_Destisaggregate_Desc() { regOBD("DestIsAggregate"); return this; }
protected ConditionValue _destisordered;
public ConditionValue getDestisordered() {
if (_destisordered == null) { _destisordered = new ConditionValue(); }
return _destisordered;
}
protected ConditionValue getCValueDestisordered() { return getDestisordered(); }
public BsTConnectorCQ addOrderBy_Destisordered_Asc() { regOBA("DestIsOrdered"); return this; }
public BsTConnectorCQ addOrderBy_Destisordered_Desc() { regOBD("DestIsOrdered"); return this; }
protected ConditionValue _destqualifier;
public ConditionValue getDestqualifier() {
if (_destqualifier == null) { _destqualifier = new ConditionValue(); }
return _destqualifier;
}
protected ConditionValue getCValueDestqualifier() { return getDestqualifier(); }
public BsTConnectorCQ addOrderBy_Destqualifier_Asc() { regOBA("DestQualifier"); return this; }
public BsTConnectorCQ addOrderBy_Destqualifier_Desc() { regOBD("DestQualifier"); return this; }
protected ConditionValue _startObjectId;
public ConditionValue getStartObjectId() {
if (_startObjectId == null) { _startObjectId = new ConditionValue(); }
return _startObjectId;
}
protected ConditionValue getCValueStartObjectId() { return getStartObjectId(); }
protected Map<String, TObjectCQ> _startObjectId_InScopeSubQuery_TObjectByStartObjectIdMap;
public Map<String, TObjectCQ> getStartObjectId_InScopeSubQuery_TObjectByStartObjectId() { return _startObjectId_InScopeSubQuery_TObjectByStartObjectIdMap; }
public String keepStartObjectId_InScopeSubQuery_TObjectByStartObjectId(TObjectCQ subQuery) {
if (_startObjectId_InScopeSubQuery_TObjectByStartObjectIdMap == null) { _startObjectId_InScopeSubQuery_TObjectByStartObjectIdMap = newLinkedHashMap(); }
String key = "subQueryMapKey" + (_startObjectId_InScopeSubQuery_TObjectByStartObjectIdMap.size() + 1);
_startObjectId_InScopeSubQuery_TObjectByStartObjectIdMap.put(key, subQuery); return "startObjectId_InScopeSubQuery_TObjectByStartObjectId." + key;
}
public BsTConnectorCQ addOrderBy_StartObjectId_Asc() { regOBA("Start_Object_ID"); return this; }
public BsTConnectorCQ addOrderBy_StartObjectId_Desc() { regOBD("Start_Object_ID"); return this; }
protected ConditionValue _endObjectId;
public ConditionValue getEndObjectId() {
if (_endObjectId == null) { _endObjectId = new ConditionValue(); }
return _endObjectId;
}
protected ConditionValue getCValueEndObjectId() { return getEndObjectId(); }
protected Map<String, TObjectCQ> _endObjectId_InScopeSubQuery_TObjectByEndObjectIdMap;
public Map<String, TObjectCQ> getEndObjectId_InScopeSubQuery_TObjectByEndObjectId() { return _endObjectId_InScopeSubQuery_TObjectByEndObjectIdMap; }
public String keepEndObjectId_InScopeSubQuery_TObjectByEndObjectId(TObjectCQ subQuery) {
if (_endObjectId_InScopeSubQuery_TObjectByEndObjectIdMap == null) { _endObjectId_InScopeSubQuery_TObjectByEndObjectIdMap = newLinkedHashMap(); }
String key = "subQueryMapKey" + (_endObjectId_InScopeSubQuery_TObjectByEndObjectIdMap.size() + 1);
_endObjectId_InScopeSubQuery_TObjectByEndObjectIdMap.put(key, subQuery); return "endObjectId_InScopeSubQuery_TObjectByEndObjectId." + key;
}
public BsTConnectorCQ addOrderBy_EndObjectId_Asc() { regOBA("End_Object_ID"); return this; }
public BsTConnectorCQ addOrderBy_EndObjectId_Desc() { regOBD("End_Object_ID"); return this; }
protected ConditionValue _topStartLabel;
public ConditionValue getTopStartLabel() {
if (_topStartLabel == null) { _topStartLabel = new ConditionValue(); }
return _topStartLabel;
}
protected ConditionValue getCValueTopStartLabel() { return getTopStartLabel(); }
public BsTConnectorCQ addOrderBy_TopStartLabel_Asc() { regOBA("Top_Start_Label"); return this; }
public BsTConnectorCQ addOrderBy_TopStartLabel_Desc() { regOBD("Top_Start_Label"); return this; }
protected ConditionValue _topMidLabel;
public ConditionValue getTopMidLabel() {
if (_topMidLabel == null) { _topMidLabel = new ConditionValue(); }
return _topMidLabel;
}
protected ConditionValue getCValueTopMidLabel() { return getTopMidLabel(); }
public BsTConnectorCQ addOrderBy_TopMidLabel_Asc() { regOBA("Top_Mid_Label"); return this; }
public BsTConnectorCQ addOrderBy_TopMidLabel_Desc() { regOBD("Top_Mid_Label"); return this; }
protected ConditionValue _topEndLabel;
public ConditionValue getTopEndLabel() {
if (_topEndLabel == null) { _topEndLabel = new ConditionValue(); }
return _topEndLabel;
}
protected ConditionValue getCValueTopEndLabel() { return getTopEndLabel(); }
public BsTConnectorCQ addOrderBy_TopEndLabel_Asc() { regOBA("Top_End_Label"); return this; }
public BsTConnectorCQ addOrderBy_TopEndLabel_Desc() { regOBD("Top_End_Label"); return this; }
protected ConditionValue _btmStartLabel;
public ConditionValue getBtmStartLabel() {
if (_btmStartLabel == null) { _btmStartLabel = new ConditionValue(); }
return _btmStartLabel;
}
protected ConditionValue getCValueBtmStartLabel() { return getBtmStartLabel(); }
public BsTConnectorCQ addOrderBy_BtmStartLabel_Asc() { regOBA("Btm_Start_Label"); return this; }
public BsTConnectorCQ addOrderBy_BtmStartLabel_Desc() { regOBD("Btm_Start_Label"); return this; }
protected ConditionValue _btmMidLabel;
public ConditionValue getBtmMidLabel() {
if (_btmMidLabel == null) { _btmMidLabel = new ConditionValue(); }
return _btmMidLabel;
}
protected ConditionValue getCValueBtmMidLabel() { return getBtmMidLabel(); }
public BsTConnectorCQ addOrderBy_BtmMidLabel_Asc() { regOBA("Btm_Mid_Label"); return this; }
public BsTConnectorCQ addOrderBy_BtmMidLabel_Desc() { regOBD("Btm_Mid_Label"); return this; }
protected ConditionValue _btmEndLabel;
public ConditionValue getBtmEndLabel() {
if (_btmEndLabel == null) { _btmEndLabel = new ConditionValue(); }
return _btmEndLabel;
}
protected ConditionValue getCValueBtmEndLabel() { return getBtmEndLabel(); }
public BsTConnectorCQ addOrderBy_BtmEndLabel_Asc() { regOBA("Btm_End_Label"); return this; }
public BsTConnectorCQ addOrderBy_BtmEndLabel_Desc() { regOBD("Btm_End_Label"); return this; }
protected ConditionValue _startEdge;
public ConditionValue getStartEdge() {
if (_startEdge == null) { _startEdge = new ConditionValue(); }
return _startEdge;
}
protected ConditionValue getCValueStartEdge() { return getStartEdge(); }
public BsTConnectorCQ addOrderBy_StartEdge_Asc() { regOBA("Start_Edge"); return this; }
public BsTConnectorCQ addOrderBy_StartEdge_Desc() { regOBD("Start_Edge"); return this; }
protected ConditionValue _endEdge;
public ConditionValue getEndEdge() {
if (_endEdge == null) { _endEdge = new ConditionValue(); }
return _endEdge;
}
protected ConditionValue getCValueEndEdge() { return getEndEdge(); }
public BsTConnectorCQ addOrderBy_EndEdge_Asc() { regOBA("End_Edge"); return this; }
public BsTConnectorCQ addOrderBy_EndEdge_Desc() { regOBD("End_Edge"); return this; }
protected ConditionValue _ptstartx;
public ConditionValue getPtstartx() {
if (_ptstartx == null) { _ptstartx = new ConditionValue(); }
return _ptstartx;
}
protected ConditionValue getCValuePtstartx() { return getPtstartx(); }
public BsTConnectorCQ addOrderBy_Ptstartx_Asc() { regOBA("PtStartX"); return this; }
public BsTConnectorCQ addOrderBy_Ptstartx_Desc() { regOBD("PtStartX"); return this; }
protected ConditionValue _ptstarty;
public ConditionValue getPtstarty() {
if (_ptstarty == null) { _ptstarty = new ConditionValue(); }
return _ptstarty;
}
protected ConditionValue getCValuePtstarty() { return getPtstarty(); }
public BsTConnectorCQ addOrderBy_Ptstarty_Asc() { regOBA("PtStartY"); return this; }
public BsTConnectorCQ addOrderBy_Ptstarty_Desc() { regOBD("PtStartY"); return this; }
protected ConditionValue _ptendx;
public ConditionValue getPtendx() {
if (_ptendx == null) { _ptendx = new ConditionValue(); }
return _ptendx;
}
protected ConditionValue getCValuePtendx() { return getPtendx(); }
public BsTConnectorCQ addOrderBy_Ptendx_Asc() { regOBA("PtEndX"); return this; }
public BsTConnectorCQ addOrderBy_Ptendx_Desc() { regOBD("PtEndX"); return this; }
protected ConditionValue _ptendy;
public ConditionValue getPtendy() {
if (_ptendy == null) { _ptendy = new ConditionValue(); }
return _ptendy;
}
protected ConditionValue getCValuePtendy() { return getPtendy(); }
public BsTConnectorCQ addOrderBy_Ptendy_Asc() { regOBA("PtEndY"); return this; }
public BsTConnectorCQ addOrderBy_Ptendy_Desc() { regOBD("PtEndY"); return this; }
protected ConditionValue _seqno;
public ConditionValue getSeqno() {
if (_seqno == null) { _seqno = new ConditionValue(); }
return _seqno;
}
protected ConditionValue getCValueSeqno() { return getSeqno(); }
public BsTConnectorCQ addOrderBy_Seqno_Asc() { regOBA("SeqNo"); return this; }
public BsTConnectorCQ addOrderBy_Seqno_Desc() { regOBD("SeqNo"); return this; }
protected ConditionValue _headstyle;
public ConditionValue getHeadstyle() {
if (_headstyle == null) { _headstyle = new ConditionValue(); }
return _headstyle;
}
protected ConditionValue getCValueHeadstyle() { return getHeadstyle(); }
public BsTConnectorCQ addOrderBy_Headstyle_Asc() { regOBA("HeadStyle"); return this; }
public BsTConnectorCQ addOrderBy_Headstyle_Desc() { regOBD("HeadStyle"); return this; }
protected ConditionValue _linestyle;
public ConditionValue getLinestyle() {
if (_linestyle == null) { _linestyle = new ConditionValue(); }
return _linestyle;
}
protected ConditionValue getCValueLinestyle() { return getLinestyle(); }
public BsTConnectorCQ addOrderBy_Linestyle_Asc() { regOBA("LineStyle"); return this; }
public BsTConnectorCQ addOrderBy_Linestyle_Desc() { regOBD("LineStyle"); return this; }
protected ConditionValue _routestyle;
public ConditionValue getRoutestyle() {
if (_routestyle == null) { _routestyle = new ConditionValue(); }
return _routestyle;
}
protected ConditionValue getCValueRoutestyle() { return getRoutestyle(); }
public BsTConnectorCQ addOrderBy_Routestyle_Asc() { regOBA("RouteStyle"); return this; }
public BsTConnectorCQ addOrderBy_Routestyle_Desc() { regOBD("RouteStyle"); return this; }
protected ConditionValue _isbold;
public ConditionValue getIsbold() {
if (_isbold == null) { _isbold = new ConditionValue(); }
return _isbold;
}
protected ConditionValue getCValueIsbold() { return getIsbold(); }
public BsTConnectorCQ addOrderBy_Isbold_Asc() { regOBA("IsBold"); return this; }
public BsTConnectorCQ addOrderBy_Isbold_Desc() { regOBD("IsBold"); return this; }
protected ConditionValue _linecolor;
public ConditionValue getLinecolor() {
if (_linecolor == null) { _linecolor = new ConditionValue(); }
return _linecolor;
}
protected ConditionValue getCValueLinecolor() { return getLinecolor(); }
public BsTConnectorCQ addOrderBy_Linecolor_Asc() { regOBA("LineColor"); return this; }
public BsTConnectorCQ addOrderBy_Linecolor_Desc() { regOBD("LineColor"); return this; }
protected ConditionValue _stereotype;
public ConditionValue getStereotype() {
if (_stereotype == null) { _stereotype = new ConditionValue(); }
return _stereotype;
}
protected ConditionValue getCValueStereotype() { return getStereotype(); }
public BsTConnectorCQ addOrderBy_Stereotype_Asc() { regOBA("Stereotype"); return this; }
public BsTConnectorCQ addOrderBy_Stereotype_Desc() { regOBD("Stereotype"); return this; }
protected ConditionValue _virtualinheritance;
public ConditionValue getVirtualinheritance() {
if (_virtualinheritance == null) { _virtualinheritance = new ConditionValue(); }
return _virtualinheritance;
}
protected ConditionValue getCValueVirtualinheritance() { return getVirtualinheritance(); }
public BsTConnectorCQ addOrderBy_Virtualinheritance_Asc() { regOBA("VirtualInheritance"); return this; }
public BsTConnectorCQ addOrderBy_Virtualinheritance_Desc() { regOBD("VirtualInheritance"); return this; }
protected ConditionValue _linkaccess;
public ConditionValue getLinkaccess() {
if (_linkaccess == null) { _linkaccess = new ConditionValue(); }
return _linkaccess;
}
protected ConditionValue getCValueLinkaccess() { return getLinkaccess(); }
public BsTConnectorCQ addOrderBy_Linkaccess_Asc() { regOBA("LinkAccess"); return this; }
public BsTConnectorCQ addOrderBy_Linkaccess_Desc() { regOBD("LinkAccess"); return this; }
protected ConditionValue _pdata1;
public ConditionValue getPdata1() {
if (_pdata1 == null) { _pdata1 = new ConditionValue(); }
return _pdata1;
}
protected ConditionValue getCValuePdata1() { return getPdata1(); }
public BsTConnectorCQ addOrderBy_Pdata1_Asc() { regOBA("PDATA1"); return this; }
public BsTConnectorCQ addOrderBy_Pdata1_Desc() { regOBD("PDATA1"); return this; }
protected ConditionValue _pdata2;
public ConditionValue getPdata2() {
if (_pdata2 == null) { _pdata2 = new ConditionValue(); }
return _pdata2;
}
protected ConditionValue getCValuePdata2() { return getPdata2(); }
public BsTConnectorCQ addOrderBy_Pdata2_Asc() { regOBA("PDATA2"); return this; }
public BsTConnectorCQ addOrderBy_Pdata2_Desc() { regOBD("PDATA2"); return this; }
protected ConditionValue _pdata3;
public ConditionValue getPdata3() {
if (_pdata3 == null) { _pdata3 = new ConditionValue(); }
return _pdata3;
}
protected ConditionValue getCValuePdata3() { return getPdata3(); }
public BsTConnectorCQ addOrderBy_Pdata3_Asc() { regOBA("PDATA3"); return this; }
public BsTConnectorCQ addOrderBy_Pdata3_Desc() { regOBD("PDATA3"); return this; }
protected ConditionValue _pdata4;
public ConditionValue getPdata4() {
if (_pdata4 == null) { _pdata4 = new ConditionValue(); }
return _pdata4;
}
protected ConditionValue getCValuePdata4() { return getPdata4(); }
public BsTConnectorCQ addOrderBy_Pdata4_Asc() { regOBA("PDATA4"); return this; }
public BsTConnectorCQ addOrderBy_Pdata4_Desc() { regOBD("PDATA4"); return this; }
protected ConditionValue _pdata5;
public ConditionValue getPdata5() {
if (_pdata5 == null) { _pdata5 = new ConditionValue(); }
return _pdata5;
}
protected ConditionValue getCValuePdata5() { return getPdata5(); }
public BsTConnectorCQ addOrderBy_Pdata5_Asc() { regOBA("PDATA5"); return this; }
public BsTConnectorCQ addOrderBy_Pdata5_Desc() { regOBD("PDATA5"); return this; }
protected ConditionValue _diagramid;
public ConditionValue getDiagramid() {
if (_diagramid == null) { _diagramid = new ConditionValue(); }
return _diagramid;
}
protected ConditionValue getCValueDiagramid() { return getDiagramid(); }
public BsTConnectorCQ addOrderBy_Diagramid_Asc() { regOBA("DiagramID"); return this; }
public BsTConnectorCQ addOrderBy_Diagramid_Desc() { regOBD("DiagramID"); return this; }
protected ConditionValue _eaGuid;
public ConditionValue getEaGuid() {
if (_eaGuid == null) { _eaGuid = new ConditionValue(); }
return _eaGuid;
}
protected ConditionValue getCValueEaGuid() { return getEaGuid(); }
public BsTConnectorCQ addOrderBy_EaGuid_Asc() { regOBA("ea_guid"); return this; }
public BsTConnectorCQ addOrderBy_EaGuid_Desc() { regOBD("ea_guid"); return this; }
protected ConditionValue _sourceconstraint;
public ConditionValue getSourceconstraint() {
if (_sourceconstraint == null) { _sourceconstraint = new ConditionValue(); }
return _sourceconstraint;
}
protected ConditionValue getCValueSourceconstraint() { return getSourceconstraint(); }
public BsTConnectorCQ addOrderBy_Sourceconstraint_Asc() { regOBA("SourceConstraint"); return this; }
public BsTConnectorCQ addOrderBy_Sourceconstraint_Desc() { regOBD("SourceConstraint"); return this; }
protected ConditionValue _destconstraint;
public ConditionValue getDestconstraint() {
if (_destconstraint == null) { _destconstraint = new ConditionValue(); }
return _destconstraint;
}
protected ConditionValue getCValueDestconstraint() { return getDestconstraint(); }
public BsTConnectorCQ addOrderBy_Destconstraint_Asc() { regOBA("DestConstraint"); return this; }
public BsTConnectorCQ addOrderBy_Destconstraint_Desc() { regOBD("DestConstraint"); return this; }
protected ConditionValue _sourceisnavigable;
public ConditionValue getSourceisnavigable() {
if (_sourceisnavigable == null) { _sourceisnavigable = new ConditionValue(); }
return _sourceisnavigable;
}
protected ConditionValue getCValueSourceisnavigable() { return getSourceisnavigable(); }
public BsTConnectorCQ addOrderBy_Sourceisnavigable_Asc() { regOBA("SourceIsNavigable"); return this; }
public BsTConnectorCQ addOrderBy_Sourceisnavigable_Desc() { regOBD("SourceIsNavigable"); return this; }
protected ConditionValue _destisnavigable;
public ConditionValue getDestisnavigable() {
if (_destisnavigable == null) { _destisnavigable = new ConditionValue(); }
return _destisnavigable;
}
protected ConditionValue getCValueDestisnavigable() { return getDestisnavigable(); }
public BsTConnectorCQ addOrderBy_Destisnavigable_Asc() { regOBA("DestIsNavigable"); return this; }
public BsTConnectorCQ addOrderBy_Destisnavigable_Desc() { regOBD("DestIsNavigable"); return this; }
protected ConditionValue _isroot;
public ConditionValue getIsroot() {
if (_isroot == null) { _isroot = new ConditionValue(); }
return _isroot;
}
protected ConditionValue getCValueIsroot() { return getIsroot(); }
public BsTConnectorCQ addOrderBy_Isroot_Asc() { regOBA("IsRoot"); return this; }
public BsTConnectorCQ addOrderBy_Isroot_Desc() { regOBD("IsRoot"); return this; }
protected ConditionValue _isleaf;
public ConditionValue getIsleaf() {
if (_isleaf == null) { _isleaf = new ConditionValue(); }
return _isleaf;
}
protected ConditionValue getCValueIsleaf() { return getIsleaf(); }
public BsTConnectorCQ addOrderBy_Isleaf_Asc() { regOBA("IsLeaf"); return this; }
public BsTConnectorCQ addOrderBy_Isleaf_Desc() { regOBD("IsLeaf"); return this; }
protected ConditionValue _isspec;
public ConditionValue getIsspec() {
if (_isspec == null) { _isspec = new ConditionValue(); }
return _isspec;
}
protected ConditionValue getCValueIsspec() { return getIsspec(); }
public BsTConnectorCQ addOrderBy_Isspec_Asc() { regOBA("IsSpec"); return this; }
public BsTConnectorCQ addOrderBy_Isspec_Desc() { regOBD("IsSpec"); return this; }
protected ConditionValue _sourcechangeable;
public ConditionValue getSourcechangeable() {
if (_sourcechangeable == null) { _sourcechangeable = new ConditionValue(); }
return _sourcechangeable;
}
protected ConditionValue getCValueSourcechangeable() { return getSourcechangeable(); }
public BsTConnectorCQ addOrderBy_Sourcechangeable_Asc() { regOBA("SourceChangeable"); return this; }
public BsTConnectorCQ addOrderBy_Sourcechangeable_Desc() { regOBD("SourceChangeable"); return this; }
protected ConditionValue _destchangeable;
public ConditionValue getDestchangeable() {
if (_destchangeable == null) { _destchangeable = new ConditionValue(); }
return _destchangeable;
}
protected ConditionValue getCValueDestchangeable() { return getDestchangeable(); }
public BsTConnectorCQ addOrderBy_Destchangeable_Asc() { regOBA("DestChangeable"); return this; }
public BsTConnectorCQ addOrderBy_Destchangeable_Desc() { regOBD("DestChangeable"); return this; }
protected ConditionValue _sourcets;
public ConditionValue getSourcets() {
if (_sourcets == null) { _sourcets = new ConditionValue(); }
return _sourcets;
}
protected ConditionValue getCValueSourcets() { return getSourcets(); }
public BsTConnectorCQ addOrderBy_Sourcets_Asc() { regOBA("SourceTS"); return this; }
public BsTConnectorCQ addOrderBy_Sourcets_Desc() { regOBD("SourceTS"); return this; }
protected ConditionValue _destts;
public ConditionValue getDestts() {
if (_destts == null) { _destts = new ConditionValue(); }
return _destts;
}
protected ConditionValue getCValueDestts() { return getDestts(); }
public BsTConnectorCQ addOrderBy_Destts_Asc() { regOBA("DestTS"); return this; }
public BsTConnectorCQ addOrderBy_Destts_Desc() { regOBD("DestTS"); return this; }
protected ConditionValue _stateflags;
public ConditionValue getStateflags() {
if (_stateflags == null) { _stateflags = new ConditionValue(); }
return _stateflags;
}
protected ConditionValue getCValueStateflags() { return getStateflags(); }
public BsTConnectorCQ addOrderBy_Stateflags_Asc() { regOBA("StateFlags"); return this; }
public BsTConnectorCQ addOrderBy_Stateflags_Desc() { regOBD("StateFlags"); return this; }
protected ConditionValue _actionflags;
public ConditionValue getActionflags() {
if (_actionflags == null) { _actionflags = new ConditionValue(); }
return _actionflags;
}
protected ConditionValue getCValueActionflags() { return getActionflags(); }
public BsTConnectorCQ addOrderBy_Actionflags_Asc() { regOBA("ActionFlags"); return this; }
public BsTConnectorCQ addOrderBy_Actionflags_Desc() { regOBD("ActionFlags"); return this; }
protected ConditionValue _issignal;
public ConditionValue getIssignal() {
if (_issignal == null) { _issignal = new ConditionValue(); }
return _issignal;
}
protected ConditionValue getCValueIssignal() { return getIssignal(); }
public BsTConnectorCQ addOrderBy_Issignal_Asc() { regOBA("IsSignal"); return this; }
public BsTConnectorCQ addOrderBy_Issignal_Desc() { regOBD("IsSignal"); return this; }
protected ConditionValue _isstimulus;
public ConditionValue getIsstimulus() {
if (_isstimulus == null) { _isstimulus = new ConditionValue(); }
return _isstimulus;
}
protected ConditionValue getCValueIsstimulus() { return getIsstimulus(); }
public BsTConnectorCQ addOrderBy_Isstimulus_Asc() { regOBA("IsStimulus"); return this; }
public BsTConnectorCQ addOrderBy_Isstimulus_Desc() { regOBD("IsStimulus"); return this; }
protected ConditionValue _dispatchaction;
public ConditionValue getDispatchaction() {
if (_dispatchaction == null) { _dispatchaction = new ConditionValue(); }
return _dispatchaction;
}
protected ConditionValue getCValueDispatchaction() { return getDispatchaction(); }
public BsTConnectorCQ addOrderBy_Dispatchaction_Asc() { regOBA("DispatchAction"); return this; }
public BsTConnectorCQ addOrderBy_Dispatchaction_Desc() { regOBD("DispatchAction"); return this; }
protected ConditionValue _target2;
public ConditionValue getTarget2() {
if (_target2 == null) { _target2 = new ConditionValue(); }
return _target2;
}
protected ConditionValue getCValueTarget2() { return getTarget2(); }
public BsTConnectorCQ addOrderBy_Target2_Asc() { regOBA("Target2"); return this; }
public BsTConnectorCQ addOrderBy_Target2_Desc() { regOBD("Target2"); return this; }
protected ConditionValue _styleex;
public ConditionValue getStyleex() {
if (_styleex == null) { _styleex = new ConditionValue(); }
return _styleex;
}
protected ConditionValue getCValueStyleex() { return getStyleex(); }
public BsTConnectorCQ addOrderBy_Styleex_Asc() { regOBA("StyleEx"); return this; }
public BsTConnectorCQ addOrderBy_Styleex_Desc() { regOBD("StyleEx"); return this; }
protected ConditionValue _sourcestereotype;
public ConditionValue getSourcestereotype() {
if (_sourcestereotype == null) { _sourcestereotype = new ConditionValue(); }
return _sourcestereotype;
}
protected ConditionValue getCValueSourcestereotype() { return getSourcestereotype(); }
public BsTConnectorCQ addOrderBy_Sourcestereotype_Asc() { regOBA("SourceStereotype"); return this; }
public BsTConnectorCQ addOrderBy_Sourcestereotype_Desc() { regOBD("SourceStereotype"); return this; }
protected ConditionValue _deststereotype;
public ConditionValue getDeststereotype() {
if (_deststereotype == null) { _deststereotype = new ConditionValue(); }
return _deststereotype;
}
protected ConditionValue getCValueDeststereotype() { return getDeststereotype(); }
public BsTConnectorCQ addOrderBy_Deststereotype_Asc() { regOBA("DestStereotype"); return this; }
public BsTConnectorCQ addOrderBy_Deststereotype_Desc() { regOBD("DestStereotype"); return this; }
protected ConditionValue _sourcestyle;
public ConditionValue getSourcestyle() {
if (_sourcestyle == null) { _sourcestyle = new ConditionValue(); }
return _sourcestyle;
}
protected ConditionValue getCValueSourcestyle() { return getSourcestyle(); }
public BsTConnectorCQ addOrderBy_Sourcestyle_Asc() { regOBA("SourceStyle"); return this; }
public BsTConnectorCQ addOrderBy_Sourcestyle_Desc() { regOBD("SourceStyle"); return this; }
protected ConditionValue _deststyle;
public ConditionValue getDeststyle() {
if (_deststyle == null) { _deststyle = new ConditionValue(); }
return _deststyle;
}
protected ConditionValue getCValueDeststyle() { return getDeststyle(); }
public BsTConnectorCQ addOrderBy_Deststyle_Asc() { regOBA("DestStyle"); return this; }
public BsTConnectorCQ addOrderBy_Deststyle_Desc() { regOBD("DestStyle"); return this; }
protected ConditionValue _eventflags;
public ConditionValue getEventflags() {
if (_eventflags == null) { _eventflags = new ConditionValue(); }
return _eventflags;
}
protected ConditionValue getCValueEventflags() { return getEventflags(); }
public BsTConnectorCQ addOrderBy_Eventflags_Asc() { regOBA("EventFlags"); return this; }
public BsTConnectorCQ addOrderBy_Eventflags_Desc() { regOBD("EventFlags"); return this; }
// ===================================================================================
// Specified Derived OrderBy
// =========================
public BsTConnectorCQ addSpecifiedDerivedOrderBy_Asc(String aliasName) { registerSpecifiedDerivedOrderBy_Asc(aliasName); return this; }
public BsTConnectorCQ addSpecifiedDerivedOrderBy_Desc(String aliasName) { registerSpecifiedDerivedOrderBy_Desc(aliasName); return this; }
// ===================================================================================
// Union Query
// ===========
protected void reflectRelationOnUnionQuery(ConditionQuery baseQueryAsSuper, ConditionQuery unionQueryAsSuper) {
TConnectorCQ baseQuery = (TConnectorCQ)baseQueryAsSuper;
TConnectorCQ unionQuery = (TConnectorCQ)unionQueryAsSuper;
if (baseQuery.hasConditionQueryTOperationBySourcerole()) {
unionQuery.queryTOperationBySourcerole().reflectRelationOnUnionQuery(baseQuery.queryTOperationBySourcerole(), unionQuery.queryTOperationBySourcerole());
}
if (baseQuery.hasConditionQueryTOperationByDestrole()) {
unionQuery.queryTOperationByDestrole().reflectRelationOnUnionQuery(baseQuery.queryTOperationByDestrole(), unionQuery.queryTOperationByDestrole());
}
if (baseQuery.hasConditionQueryTObjectByStartObjectId()) {
unionQuery.queryTObjectByStartObjectId().reflectRelationOnUnionQuery(baseQuery.queryTObjectByStartObjectId(), unionQuery.queryTObjectByStartObjectId());
}
if (baseQuery.hasConditionQueryTObjectByEndObjectId()) {
unionQuery.queryTObjectByEndObjectId().reflectRelationOnUnionQuery(baseQuery.queryTObjectByEndObjectId(), unionQuery.queryTObjectByEndObjectId());
}
}
// ===================================================================================
// Foreign Query
// =============
public TOperationCQ queryTOperationBySourcerole() {
return getConditionQueryTOperationBySourcerole();
}
protected TOperationCQ _conditionQueryTOperationBySourcerole;
public TOperationCQ getConditionQueryTOperationBySourcerole() {
if (_conditionQueryTOperationBySourcerole == null) {
_conditionQueryTOperationBySourcerole = xcreateQueryTOperationBySourcerole();
xsetupOuterJoinTOperationBySourcerole();
}
return _conditionQueryTOperationBySourcerole;
}
protected TOperationCQ xcreateQueryTOperationBySourcerole() {
String nrp = resolveNextRelationPath("t_connector", "tOperationBySourcerole");
String jan = resolveJoinAliasName(nrp, getNextNestLevel());
TOperationCQ cq = new TOperationCQ(this, getSqlClause(), jan, getNextNestLevel());
cq.xsetForeignPropertyName("tOperationBySourcerole"); cq.xsetRelationPath(nrp); return cq;
}
protected void xsetupOuterJoinTOperationBySourcerole() {
TOperationCQ cq = getConditionQueryTOperationBySourcerole();
Map<String, String> joinOnMap = newLinkedHashMap();
joinOnMap.put(getRealColumnName("SourceRole"), cq.getRealColumnName("Name"));
registerOuterJoin(cq, joinOnMap);
}
public boolean hasConditionQueryTOperationBySourcerole() {
return _conditionQueryTOperationBySourcerole != null;
}
public TOperationCQ queryTOperationByDestrole() {
return getConditionQueryTOperationByDestrole();
}
protected TOperationCQ _conditionQueryTOperationByDestrole;
public TOperationCQ getConditionQueryTOperationByDestrole() {
if (_conditionQueryTOperationByDestrole == null) {
_conditionQueryTOperationByDestrole = xcreateQueryTOperationByDestrole();
xsetupOuterJoinTOperationByDestrole();
}
return _conditionQueryTOperationByDestrole;
}
protected TOperationCQ xcreateQueryTOperationByDestrole() {
String nrp = resolveNextRelationPath("t_connector", "tOperationByDestrole");
String jan = resolveJoinAliasName(nrp, getNextNestLevel());
TOperationCQ cq = new TOperationCQ(this, getSqlClause(), jan, getNextNestLevel());
cq.xsetForeignPropertyName("tOperationByDestrole"); cq.xsetRelationPath(nrp); return cq;
}
protected void xsetupOuterJoinTOperationByDestrole() {
TOperationCQ cq = getConditionQueryTOperationByDestrole();
Map<String, String> joinOnMap = newLinkedHashMap();
joinOnMap.put(getRealColumnName("DestRole"), cq.getRealColumnName("Name"));
registerOuterJoin(cq, joinOnMap);
}
public boolean hasConditionQueryTOperationByDestrole() {
return _conditionQueryTOperationByDestrole != null;
}
public TObjectCQ queryTObjectByStartObjectId() {
return getConditionQueryTObjectByStartObjectId();
}
protected TObjectCQ _conditionQueryTObjectByStartObjectId;
public TObjectCQ getConditionQueryTObjectByStartObjectId() {
if (_conditionQueryTObjectByStartObjectId == null) {
_conditionQueryTObjectByStartObjectId = xcreateQueryTObjectByStartObjectId();
xsetupOuterJoinTObjectByStartObjectId();
}
return _conditionQueryTObjectByStartObjectId;
}
protected TObjectCQ xcreateQueryTObjectByStartObjectId() {
String nrp = resolveNextRelationPath("t_connector", "tObjectByStartObjectId");
String jan = resolveJoinAliasName(nrp, getNextNestLevel());
TObjectCQ cq = new TObjectCQ(this, getSqlClause(), jan, getNextNestLevel());
cq.xsetForeignPropertyName("tObjectByStartObjectId"); cq.xsetRelationPath(nrp); return cq;
}
protected void xsetupOuterJoinTObjectByStartObjectId() {
TObjectCQ cq = getConditionQueryTObjectByStartObjectId();
Map<String, String> joinOnMap = newLinkedHashMap();
joinOnMap.put(getRealColumnName("Start_Object_ID"), cq.getRealColumnName("Object_ID"));
registerOuterJoin(cq, joinOnMap);
}
public boolean hasConditionQueryTObjectByStartObjectId() {
return _conditionQueryTObjectByStartObjectId != null;
}
public TObjectCQ queryTObjectByEndObjectId() {
return getConditionQueryTObjectByEndObjectId();
}
protected TObjectCQ _conditionQueryTObjectByEndObjectId;
public TObjectCQ getConditionQueryTObjectByEndObjectId() {
if (_conditionQueryTObjectByEndObjectId == null) {
_conditionQueryTObjectByEndObjectId = xcreateQueryTObjectByEndObjectId();
xsetupOuterJoinTObjectByEndObjectId();
}
return _conditionQueryTObjectByEndObjectId;
}
protected TObjectCQ xcreateQueryTObjectByEndObjectId() {
String nrp = resolveNextRelationPath("t_connector", "tObjectByEndObjectId");
String jan = resolveJoinAliasName(nrp, getNextNestLevel());
TObjectCQ cq = new TObjectCQ(this, getSqlClause(), jan, getNextNestLevel());
cq.xsetForeignPropertyName("tObjectByEndObjectId"); cq.xsetRelationPath(nrp); return cq;
}
protected void xsetupOuterJoinTObjectByEndObjectId() {
TObjectCQ cq = getConditionQueryTObjectByEndObjectId();
Map<String, String> joinOnMap = newLinkedHashMap();
joinOnMap.put(getRealColumnName("End_Object_ID"), cq.getRealColumnName("Object_ID"));
registerOuterJoin(cq, joinOnMap);
}
public boolean hasConditionQueryTObjectByEndObjectId() {
return _conditionQueryTObjectByEndObjectId != null;
}
// ===================================================================================
// Scalar SubQuery
// ===============
protected Map<String, TConnectorCQ> _scalarSubQueryMap;
public Map<String, TConnectorCQ> getScalarSubQuery() { return _scalarSubQueryMap; }
public String keepScalarSubQuery(TConnectorCQ subQuery) {
if (_scalarSubQueryMap == null) { _scalarSubQueryMap = newLinkedHashMap(); }
String key = "subQueryMapKey" + (_scalarSubQueryMap.size() + 1);
_scalarSubQueryMap.put(key, subQuery); return "scalarSubQuery." + key;
}
// ===================================================================================
// MySelf InScope SubQuery
// =======================
protected Map<String, TConnectorCQ> _myselfInScopeSubQueryMap;
public Map<String, TConnectorCQ> getMyselfInScopeSubQuery() { return _myselfInScopeSubQueryMap; }
public String keepMyselfInScopeSubQuery(TConnectorCQ subQuery) {
if (_myselfInScopeSubQueryMap == null) { _myselfInScopeSubQueryMap = newLinkedHashMap(); }
String key = "subQueryMapKey" + (_myselfInScopeSubQueryMap.size() + 1);
_myselfInScopeSubQueryMap.put(key, subQuery); return "myselfInScopeSubQuery." + key;
}
// ===================================================================================
// Very Internal
// =============
// Very Internal (for Suppressing Warn about 'Not Use Import')
String xCB() { return TConnectorCB.class.getName(); }
String xCQ() { return TConnectorCQ.class.getName(); }
String xMap() { return Map.class.getName(); }
}
|
apache-2.0
|
fceller/arangodb
|
3rdParty/V8/v7.1.302.28/src/torque/declaration-visitor.cc
|
22124
|
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/torque/declaration-visitor.h"
namespace v8 {
namespace internal {
namespace torque {
void DeclarationVisitor::Visit(Expression* expr) {
CurrentSourcePosition::Scope scope(expr->pos);
switch (expr->kind) {
#define ENUM_ITEM(name) \
case AstNode::Kind::k##name: \
return Visit(name::cast(expr));
AST_EXPRESSION_NODE_KIND_LIST(ENUM_ITEM)
#undef ENUM_ITEM
default:
UNIMPLEMENTED();
}
}
void DeclarationVisitor::Visit(Statement* stmt) {
CurrentSourcePosition::Scope scope(stmt->pos);
switch (stmt->kind) {
#define ENUM_ITEM(name) \
case AstNode::Kind::k##name: \
return Visit(name::cast(stmt));
AST_STATEMENT_NODE_KIND_LIST(ENUM_ITEM)
#undef ENUM_ITEM
default:
UNIMPLEMENTED();
}
}
void DeclarationVisitor::Visit(Declaration* decl) {
CurrentSourcePosition::Scope scope(decl->pos);
switch (decl->kind) {
#define ENUM_ITEM(name) \
case AstNode::Kind::k##name: \
return Visit(name::cast(decl));
AST_DECLARATION_NODE_KIND_LIST(ENUM_ITEM)
#undef ENUM_ITEM
default:
UNIMPLEMENTED();
}
}
void DeclarationVisitor::Visit(CallableNode* decl, const Signature& signature,
Statement* body) {
switch (decl->kind) {
#define ENUM_ITEM(name) \
case AstNode::Kind::k##name: \
return Visit(name::cast(decl), signature, body);
AST_CALLABLE_NODE_KIND_LIST(ENUM_ITEM)
#undef ENUM_ITEM
default:
UNIMPLEMENTED();
}
}
Builtin* DeclarationVisitor::BuiltinDeclarationCommon(
BuiltinDeclaration* decl, bool external, const Signature& signature) {
const bool javascript = decl->javascript_linkage;
const bool varargs = decl->signature->parameters.has_varargs;
Builtin::Kind kind = !javascript ? Builtin::kStub
: varargs ? Builtin::kVarArgsJavaScript
: Builtin::kFixedArgsJavaScript;
if (signature.types().size() == 0 ||
!(signature.types()[0] ==
declarations()->LookupGlobalType(CONTEXT_TYPE_STRING))) {
std::stringstream stream;
stream << "first parameter to builtin " << decl->name
<< " is not a context but should be";
ReportError(stream.str());
}
if (varargs && !javascript) {
std::stringstream stream;
stream << "builtin " << decl->name
<< " with rest parameters must be a JavaScript builtin";
ReportError(stream.str());
}
if (javascript) {
if (signature.types().size() < 2 ||
!(signature.types()[1] ==
declarations()->LookupGlobalType(OBJECT_TYPE_STRING))) {
std::stringstream stream;
stream << "second parameter to javascript builtin " << decl->name
<< " is " << *signature.types()[1] << " but should be Object";
ReportError(stream.str());
}
}
if (const StructType* struct_type =
StructType::DynamicCast(signature.return_type)) {
std::stringstream stream;
stream << "builtins (in this case" << decl->name
<< ") cannot return structs (in this case " << struct_type->name()
<< ")";
ReportError(stream.str());
}
std::string generated_name = GetGeneratedCallableName(
decl->name, declarations()->GetCurrentSpecializationTypeNamesVector());
return declarations()->DeclareBuiltin(generated_name, kind, external,
signature);
}
void DeclarationVisitor::Visit(ExternalRuntimeDeclaration* decl,
const Signature& signature, Statement* body) {
if (global_context_.verbose()) {
std::cout << "found declaration of external runtime " << decl->name
<< " with signature ";
}
if (signature.parameter_types.types.size() == 0 ||
!(signature.parameter_types.types[0] ==
declarations()->LookupGlobalType(CONTEXT_TYPE_STRING))) {
std::stringstream stream;
stream << "first parameter to runtime " << decl->name
<< " is not a context but should be";
ReportError(stream.str());
}
if (signature.return_type->IsStructType()) {
std::stringstream stream;
stream << "runtime functions (in this case" << decl->name
<< ") cannot return structs (in this case "
<< static_cast<const StructType*>(signature.return_type)->name()
<< ")";
ReportError(stream.str());
}
declarations()->DeclareRuntimeFunction(decl->name, signature);
}
void DeclarationVisitor::Visit(ExternalMacroDeclaration* decl,
const Signature& signature, Statement* body) {
if (global_context_.verbose()) {
std::cout << "found declaration of external macro " << decl->name
<< " with signature ";
}
std::string generated_name = GetGeneratedCallableName(
decl->name, declarations()->GetCurrentSpecializationTypeNamesVector());
declarations()->DeclareMacro(generated_name, signature, decl->op);
}
void DeclarationVisitor::Visit(TorqueBuiltinDeclaration* decl,
const Signature& signature, Statement* body) {
Builtin* builtin = BuiltinDeclarationCommon(decl, false, signature);
CurrentCallableActivator activator(global_context_, builtin, decl);
DeclareSignature(signature);
if (signature.parameter_types.var_args) {
declarations()->DeclareExternConstant(
decl->signature->parameters.arguments_variable,
TypeOracle::GetArgumentsType(), "arguments");
}
torque_builtins_.push_back(builtin);
Visit(body);
}
void DeclarationVisitor::Visit(TorqueMacroDeclaration* decl,
const Signature& signature, Statement* body) {
std::string generated_name = GetGeneratedCallableName(
decl->name, declarations()->GetCurrentSpecializationTypeNamesVector());
Macro* macro =
declarations()->DeclareMacro(generated_name, signature, decl->op);
CurrentCallableActivator activator(global_context_, macro, decl);
DeclareSignature(signature);
if (body != nullptr) {
Visit(body);
}
}
void DeclarationVisitor::Visit(ConstDeclaration* decl) {
declarations()->DeclareModuleConstant(decl->name,
declarations()->GetType(decl->type));
Visit(decl->expression);
}
void DeclarationVisitor::Visit(StandardDeclaration* decl) {
Signature signature = MakeSignature(decl->callable->signature.get());
Visit(decl->callable, signature, decl->body);
}
void DeclarationVisitor::Visit(GenericDeclaration* decl) {
declarations()->DeclareGeneric(decl->callable->name, CurrentModule(), decl);
}
void DeclarationVisitor::Visit(SpecializationDeclaration* decl) {
if ((decl->body != nullptr) == decl->external) {
std::stringstream stream;
stream << "specialization of " << decl->name
<< " must either be marked 'extern' or have a body";
ReportError(stream.str());
}
GenericList* generic_list = declarations()->LookupGeneric(decl->name);
// Find the matching generic specialization based on the concrete parameter
// list.
CallableNode* matching_callable = nullptr;
SpecializationKey matching_key;
Signature signature_with_types = MakeSignature(decl->signature.get());
for (Generic* generic : generic_list->list()) {
SpecializationKey key = {generic, GetTypeVector(decl->generic_parameters)};
CallableNode* callable_candidate = generic->declaration()->callable;
// Abuse the Specialization nodes' scope to temporarily declare the
// specialization aliases for the generic types to compare signatures. This
// scope is never used for anything else, so it's OK to pollute it.
Declarations::CleanNodeScopeActivator specialization_activator(
declarations(), decl);
DeclareSpecializedTypes(key);
Signature generic_signature_with_types =
MakeSignature(generic->declaration()->callable->signature.get());
if (signature_with_types.HasSameTypesAs(generic_signature_with_types)) {
if (matching_callable != nullptr) {
std::stringstream stream;
stream << "specialization of " << callable_candidate->name
<< " is ambigous, it matches more than one generic declaration ("
<< *matching_key.first << " and " << *key.first << ")";
ReportError(stream.str());
}
matching_callable = callable_candidate;
matching_key = key;
}
}
if (matching_callable == nullptr) {
std::stringstream stream;
stream << "specialization of " << decl->name
<< " doesn't match any generic declaration";
ReportError(stream.str());
}
// Make sure the declarations of the parameter types for the specialization
// are the ones from the matching generic.
{
Declarations::CleanNodeScopeActivator specialization_activator(
declarations(), decl);
DeclareSpecializedTypes(matching_key);
}
SpecializeGeneric({matching_key, matching_callable, decl->signature.get(),
decl->body, decl->pos});
}
void DeclarationVisitor::Visit(ReturnStatement* stmt) {
if (stmt->value) {
Visit(*stmt->value);
}
}
Variable* DeclarationVisitor::DeclareVariable(const std::string& name,
const Type* type, bool is_const) {
Variable* result = declarations()->DeclareVariable(name, type, is_const);
return result;
}
Parameter* DeclarationVisitor::DeclareParameter(const std::string& name,
const Type* type) {
return declarations()->DeclareParameter(
name, GetParameterVariableFromName(name), type);
}
void DeclarationVisitor::Visit(VarDeclarationStatement* stmt) {
std::string variable_name = stmt->name;
if (!stmt->const_qualified) {
if (!stmt->type) {
ReportError(
"variable declaration is missing type. Only 'const' bindings can "
"infer the type.");
}
const Type* type = declarations()->GetType(*stmt->type);
if (type->IsConstexpr()) {
ReportError(
"cannot declare variable with constexpr type. Use 'const' instead.");
}
DeclareVariable(variable_name, type, stmt->const_qualified);
if (global_context_.verbose()) {
std::cout << "declared variable " << variable_name << " with type "
<< *type << "\n";
}
}
// const qualified variables are required to be initialized properly.
if (stmt->const_qualified && !stmt->initializer) {
std::stringstream stream;
stream << "local constant \"" << variable_name << "\" is not initialized.";
ReportError(stream.str());
}
if (stmt->initializer) {
Visit(*stmt->initializer);
if (global_context_.verbose()) {
std::cout << "variable has initialization expression at "
<< CurrentPositionAsString() << "\n";
}
}
}
void DeclarationVisitor::Visit(ExternConstDeclaration* decl) {
const Type* type = declarations()->GetType(decl->type);
if (!type->IsConstexpr()) {
std::stringstream stream;
stream << "extern constants must have constexpr type, but found: \""
<< *type << "\"\n";
ReportError(stream.str());
}
declarations()->DeclareExternConstant(decl->name, type, decl->literal);
}
void DeclarationVisitor::Visit(StructDeclaration* decl) {
std::vector<NameAndType> fields;
for (auto& field : decl->fields) {
const Type* field_type = declarations()->GetType(field.type);
fields.push_back({field.name, field_type});
}
declarations()->DeclareStruct(CurrentModule(), decl->name, fields);
}
void DeclarationVisitor::Visit(LogicalOrExpression* expr) {
{
Declarations::NodeScopeActivator scope(declarations(), expr->left);
declarations()->DeclareLabel(kFalseLabelName);
Visit(expr->left);
}
Visit(expr->right);
}
void DeclarationVisitor::Visit(LogicalAndExpression* expr) {
{
Declarations::NodeScopeActivator scope(declarations(), expr->left);
declarations()->DeclareLabel(kTrueLabelName);
Visit(expr->left);
}
Visit(expr->right);
}
void DeclarationVisitor::DeclareExpressionForBranch(
Expression* node, base::Optional<Statement*> true_statement,
base::Optional<Statement*> false_statement) {
Declarations::NodeScopeActivator scope(declarations(), node);
// Conditional expressions can either explicitly return a bit
// type, or they can be backed by macros that don't return but
// take a true and false label. By declaring the labels before
// visiting the conditional expression, those label-based
// macro conditionals will be able to find them through normal
// label lookups.
declarations()->DeclareLabel(kTrueLabelName, true_statement);
declarations()->DeclareLabel(kFalseLabelName, false_statement);
Visit(node);
}
void DeclarationVisitor::Visit(ConditionalExpression* expr) {
DeclareExpressionForBranch(expr->condition);
Visit(expr->if_true);
Visit(expr->if_false);
}
void DeclarationVisitor::Visit(IfStatement* stmt) {
DeclareExpressionForBranch(stmt->condition, stmt->if_true, stmt->if_false);
Visit(stmt->if_true);
if (stmt->if_false) Visit(*stmt->if_false);
}
void DeclarationVisitor::Visit(WhileStatement* stmt) {
Declarations::NodeScopeActivator scope(declarations(), stmt);
DeclareExpressionForBranch(stmt->condition);
Visit(stmt->body);
}
void DeclarationVisitor::Visit(ForOfLoopStatement* stmt) {
// Scope for for iteration variable
Declarations::NodeScopeActivator scope(declarations(), stmt);
Visit(stmt->var_declaration);
Visit(stmt->iterable);
if (stmt->begin) Visit(*stmt->begin);
if (stmt->end) Visit(*stmt->end);
Visit(stmt->body);
}
void DeclarationVisitor::Visit(ForLoopStatement* stmt) {
Declarations::NodeScopeActivator scope(declarations(), stmt);
if (stmt->var_declaration) Visit(*stmt->var_declaration);
// Same as DeclareExpressionForBranch, but without the extra scope.
// If no test expression is present we can not use it for the scope.
declarations()->DeclareLabel(kTrueLabelName);
declarations()->DeclareLabel(kFalseLabelName);
if (stmt->test) Visit(*stmt->test);
Visit(stmt->body);
if (stmt->action) Visit(*stmt->action);
}
void DeclarationVisitor::Visit(TryLabelExpression* stmt) {
// Activate a new scope to declare the handler's label parameters, they should
// not be visible outside the label block.
{
Declarations::NodeScopeActivator scope(declarations(), stmt);
// Declare label
{
LabelBlock* block = stmt->label_block;
CurrentSourcePosition::Scope scope(block->pos);
Label* shared_label =
declarations()->DeclareLabel(block->label, block->body);
{
Declarations::NodeScopeActivator scope(declarations(), block->body);
if (block->parameters.has_varargs) {
std::stringstream stream;
stream << "cannot use ... for label parameters";
ReportError(stream.str());
}
size_t i = 0;
for (const auto& p : block->parameters.names) {
const Type* type =
declarations()->GetType(block->parameters.types[i]);
if (type->IsConstexpr()) {
ReportError("no constexpr type allowed for label arguments");
}
shared_label->AddVariable(DeclareVariable(p, type, false));
++i;
}
if (global_context_.verbose()) {
std::cout << " declaring label " << block->label << "\n";
}
}
}
Visit(stmt->try_expression);
}
Visit(stmt->label_block->body);
}
void DeclarationVisitor::GenerateHeader(std::string& file_name) {
std::stringstream new_contents_stream;
new_contents_stream
<< "#ifndef V8_BUILTINS_BUILTIN_DEFINITIONS_FROM_DSL_H_\n"
"#define V8_BUILTINS_BUILTIN_DEFINITIONS_FROM_DSL_H_\n"
"\n"
"#define BUILTIN_LIST_FROM_DSL(CPP, API, TFJ, TFC, TFS, TFH, ASM) "
"\\\n";
for (auto builtin : torque_builtins_) {
int firstParameterIndex = 1;
bool declareParameters = true;
if (builtin->IsStub()) {
new_contents_stream << "TFS(" << builtin->name();
} else {
new_contents_stream << "TFJ(" << builtin->name();
if (builtin->IsVarArgsJavaScript()) {
new_contents_stream
<< ", SharedFunctionInfo::kDontAdaptArgumentsSentinel";
declareParameters = false;
} else {
assert(builtin->IsFixedArgsJavaScript());
// FixedArg javascript builtins need to offer the parameter
// count.
assert(builtin->parameter_names().size() >= 2);
new_contents_stream << ", " << (builtin->parameter_names().size() - 2);
// And the receiver is explicitly declared.
new_contents_stream << ", kReceiver";
firstParameterIndex = 2;
}
}
if (declareParameters) {
int index = 0;
for (const auto& parameter : builtin->parameter_names()) {
if (index >= firstParameterIndex) {
new_contents_stream << ", k" << CamelifyString(parameter);
}
index++;
}
}
new_contents_stream << ") \\\n";
}
new_contents_stream
<< "\n"
"#endif // V8_BUILTINS_BUILTIN_DEFINITIONS_FROM_DSL_H_\n";
std::string new_contents(new_contents_stream.str());
ReplaceFileContentsIfDifferent(file_name, new_contents);
}
void DeclarationVisitor::Visit(IdentifierExpression* expr) {
if (expr->generic_arguments.size() != 0) {
TypeVector specialization_types;
for (auto t : expr->generic_arguments) {
specialization_types.push_back(declarations()->GetType(t));
}
// Specialize all versions of the generic, since the exact parameter type
// list cannot be resolved until the call's parameter expressions are
// evaluated. This is an overly conservative but simple way to make sure
// that the correct specialization exists.
for (auto generic : declarations()->LookupGeneric(expr->name)->list()) {
CallableNode* callable = generic->declaration()->callable;
if (generic->declaration()->body) {
QueueGenericSpecialization({generic, specialization_types}, callable,
callable->signature.get(),
generic->declaration()->body);
}
}
}
}
void DeclarationVisitor::Visit(StatementExpression* expr) {
Visit(expr->statement);
}
void DeclarationVisitor::Visit(CallExpression* expr) {
Visit(&expr->callee);
for (Expression* arg : expr->arguments) Visit(arg);
}
void DeclarationVisitor::Visit(TypeDeclaration* decl) {
std::string generates = decl->generates ? *decl->generates : std::string("");
const AbstractType* type = declarations()->DeclareAbstractType(
decl->name, generates, {}, decl->extends);
if (decl->constexpr_generates) {
std::string constexpr_name = CONSTEXPR_TYPE_PREFIX + decl->name;
base::Optional<std::string> constexpr_extends;
if (decl->extends)
constexpr_extends = CONSTEXPR_TYPE_PREFIX + *decl->extends;
declarations()->DeclareAbstractType(
constexpr_name, *decl->constexpr_generates, type, constexpr_extends);
}
}
void DeclarationVisitor::DeclareSignature(const Signature& signature) {
auto type_iterator = signature.parameter_types.types.begin();
for (const auto& name : signature.parameter_names) {
const Type* t(*type_iterator++);
if (name.size() != 0) {
DeclareParameter(name, t);
}
}
for (auto& label : signature.labels) {
auto label_params = label.types;
Label* new_label = declarations()->DeclareLabel(label.name);
new_label->set_external_label_name("label_" + label.name);
size_t i = 0;
for (auto var_type : label_params) {
if (var_type->IsConstexpr()) {
ReportError("no constexpr type allowed for label arguments");
}
std::string var_name = label.name + std::to_string(i++);
new_label->AddVariable(
declarations()->CreateVariable(var_name, var_type, false));
}
}
}
void DeclarationVisitor::DeclareSpecializedTypes(const SpecializationKey& key) {
size_t i = 0;
Generic* generic = key.first;
const std::size_t generic_parameter_count =
generic->declaration()->generic_parameters.size();
if (generic_parameter_count != key.second.size()) {
std::stringstream stream;
stream << "Wrong generic argument count for specialization of \""
<< generic->name() << "\", expected: " << generic_parameter_count
<< ", actual: " << key.second.size();
ReportError(stream.str());
}
for (auto type : key.second) {
std::string generic_type_name =
generic->declaration()->generic_parameters[i++];
declarations()->DeclareType(generic_type_name, type);
}
}
void DeclarationVisitor::Specialize(const SpecializationKey& key,
CallableNode* callable,
const CallableNodeSignature* signature,
Statement* body) {
Generic* generic = key.first;
// TODO(tebbi): The error should point to the source position where the
// instantiation was requested.
CurrentSourcePosition::Scope pos_scope(generic->declaration()->pos);
size_t generic_parameter_count =
generic->declaration()->generic_parameters.size();
if (generic_parameter_count != key.second.size()) {
std::stringstream stream;
stream << "number of template parameters ("
<< std::to_string(key.second.size())
<< ") to intantiation of generic " << callable->name
<< " doesnt match the generic's declaration ("
<< std::to_string(generic_parameter_count) << ")";
ReportError(stream.str());
}
Signature type_signature;
{
// Manually activate the specialized generic's scope when declaring the
// generic parameter specializations.
Declarations::GenericScopeActivator namespace_scope(declarations(), key);
DeclareSpecializedTypes(key);
type_signature = MakeSignature(signature);
}
Visit(callable, type_signature, body);
}
} // namespace torque
} // namespace internal
} // namespace v8
|
apache-2.0
|
castagna/hbase-rdf
|
src/main/java/com/talis/hbase/rdf/layout/vpindexed/TableDescVPIndexedCommon.java
|
1247
|
/*
* Copyright © 2010, 2011, 2012 Talis Systems Ltd.
*
* 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 com.talis.hbase.rdf.layout.vpindexed;
import com.talis.hbase.rdf.store.TableDesc;
public class TableDescVPIndexedCommon extends TableDesc
{
protected static final String COL_FAMILY_NAME_STR = "nodes" ;
protected static final String NODE_SEPARATOR = "~~" ;
private final String _COL_FAMILY_NAME_STR ;
public TableDescVPIndexedCommon( String tName ) { this( tName, COL_FAMILY_NAME_STR ) ; }
public TableDescVPIndexedCommon( String tableName, String colFamily )
{
super( tableName, colFamily ) ;
_COL_FAMILY_NAME_STR = colFamily ;
}
public String getColFamilyName() { return _COL_FAMILY_NAME_STR ; }
}
|
apache-2.0
|
mguidi/SOA-Code-Factory
|
com.mguidi.soa/src-gen/com/mguidi/soa/soa/impl/ServiceImpl.java
|
5474
|
/**
*/
package com.mguidi.soa.soa.impl;
import com.mguidi.soa.soa.Operation;
import com.mguidi.soa.soa.Service;
import com.mguidi.soa.soa.SoaPackage;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Service</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link com.mguidi.soa.soa.impl.ServiceImpl#getName <em>Name</em>}</li>
* <li>{@link com.mguidi.soa.soa.impl.ServiceImpl#getOperations <em>Operations</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class ServiceImpl extends MinimalEObjectImpl.Container implements Service
{
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* The cached value of the '{@link #getOperations() <em>Operations</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOperations()
* @generated
* @ordered
*/
protected EList<Operation> operations;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ServiceImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return SoaPackage.Literals.SERVICE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName()
{
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName)
{
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, SoaPackage.SERVICE__NAME, oldName, name));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Operation> getOperations()
{
if (operations == null)
{
operations = new EObjectContainmentEList<Operation>(Operation.class, this, SoaPackage.SERVICE__OPERATIONS);
}
return operations;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case SoaPackage.SERVICE__OPERATIONS:
return ((InternalEList<?>)getOperations()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case SoaPackage.SERVICE__NAME:
return getName();
case SoaPackage.SERVICE__OPERATIONS:
return getOperations();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case SoaPackage.SERVICE__NAME:
setName((String)newValue);
return;
case SoaPackage.SERVICE__OPERATIONS:
getOperations().clear();
getOperations().addAll((Collection<? extends Operation>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case SoaPackage.SERVICE__NAME:
setName(NAME_EDEFAULT);
return;
case SoaPackage.SERVICE__OPERATIONS:
getOperations().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case SoaPackage.SERVICE__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
case SoaPackage.SERVICE__OPERATIONS:
return operations != null && !operations.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString()
{
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (name: ");
result.append(name);
result.append(')');
return result.toString();
}
} //ServiceImpl
|
apache-2.0
|
lorinbeer/Pender-iOS-POC
|
pender/pender/spidermonkey/jsobj.h
|
36644
|
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sw=4 et tw=78:
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code, released
* March 31, 1998.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef jsobj_h___
#define jsobj_h___
/*
* JS object definitions.
*
* A JS object consists of a possibly-shared object descriptor containing
* ordered property names, called the map; and a dense vector of property
* values, called slots. The map/slot pointer pair is GC'ed, while the map
* is reference counted and the slot vector is malloc'ed.
*/
#include "jshash.h" /* Added by JSIFY */
#include "jsprvtd.h"
#include "jspubtd.h"
JS_BEGIN_EXTERN_C
/* For detailed comments on these function pointer types, see jsprvtd.h. */
struct JSObjectOps {
/*
* Custom shared object map for non-native objects. For native objects
* this should be null indicating, that JSObject.map is an instance of
* JSScope.
*/
const JSObjectMap *objectMap;
/* Mandatory non-null function pointer members. */
JSLookupPropOp lookupProperty;
JSDefinePropOp defineProperty;
JSPropertyIdOp getProperty;
JSPropertyIdOp setProperty;
JSAttributesOp getAttributes;
JSAttributesOp setAttributes;
JSPropertyIdOp deleteProperty;
JSConvertOp defaultValue;
JSNewEnumerateOp enumerate;
JSCheckAccessIdOp checkAccess;
/* Optionally non-null members start here. */
JSObjectOp thisObject;
JSPropertyRefOp dropProperty;
JSNative call;
JSNative construct;
JSHasInstanceOp hasInstance;
JSTraceOp trace;
JSFinalizeOp clear;
};
struct JSObjectMap {
const JSObjectOps * const ops; /* high level object operation vtable */
uint32 shape; /* shape identifier */
explicit JSObjectMap(const JSObjectOps *ops, uint32 shape) : ops(ops), shape(shape) {}
enum { SHAPELESS = 0xffffffff };
};
const uint32 JS_INITIAL_NSLOTS = 5;
const uint32 JSSLOT_PROTO = 0;
const uint32 JSSLOT_PARENT = 1;
/*
* The first available slot to store generic value. For JSCLASS_HAS_PRIVATE
* classes the slot stores a pointer to private data reinterpreted as jsval.
* Such pointer is stored as is without an overhead of PRIVATE_TO_JSVAL
* tagging and should be accessed using the (get|set)Private methods of
* JSObject.
*/
const uint32 JSSLOT_PRIVATE = 2;
const uint32 JSSLOT_PRIMITIVE_THIS = JSSLOT_PRIVATE;
const uintptr_t JSSLOT_CLASS_MASK_BITS = 3;
/*
* JSObject struct, with members sized to fit in 32 bytes on 32-bit targets,
* 64 bytes on 64-bit systems. The JSFunction struct is an extension of this
* struct allocated from a larger GC size-class.
*
* The classword member stores the JSClass pointer for this object, with the
* least two bits encoding whether this object is a "delegate" or a "system"
* object. We do *not* synchronize updates of classword -- API clients must
* take care.
*
* An object is a delegate if it is on another object's prototype (linked by
* JSSLOT_PROTO) or scope (JSSLOT_PARENT) chain, and therefore the delegate
* might be asked implicitly to get or set a property on behalf of another
* object. Delegates may be accessed directly too, as may any object, but only
* those objects linked after the head of any prototype or scope chain are
* flagged as delegates. This definition helps to optimize shape-based property
* cache invalidation (see Purge{Scope,Proto}Chain in jsobj.cpp).
*
* The meaning of the system object bit is defined by the API client. It is
* set in JS_NewSystemObject and is queried by JS_IsSystemObject (jsdbgapi.h),
* but it has no intrinsic meaning to SpiderMonkey. Further, JSFILENAME_SYSTEM
* and JS_FlagScriptFilenamePrefix (also exported via jsdbgapi.h) are intended
* to be complementary to this bit, but it is up to the API client to implement
* any such association.
*
* Both these classword tag bits are initially zero; they may be set or queried
* using the (is|set)(Delegate|System) inline methods.
*
* The dslots member is null or a pointer into a dynamically allocated vector
* of jsvals for reserved and dynamic slots. If dslots is not null, dslots[-1]
* records the number of available slots.
*/
struct JSObject {
JSObjectMap *map; /* property map, see jsscope.h */
jsuword classword; /* JSClass ptr | bits, see above */
jsval fslots[JS_INITIAL_NSLOTS]; /* small number of fixed slots */
jsval *dslots; /* dynamically allocated slots */
JSClass *getClass() const {
return (JSClass *) (classword & ~JSSLOT_CLASS_MASK_BITS);
}
bool isDelegate() const {
return (classword & jsuword(1)) != jsuword(0);
}
void setDelegate() {
classword |= jsuword(1);
}
static void setDelegateNullSafe(JSObject *obj) {
if (obj)
obj->setDelegate();
}
bool isSystem() const {
return (classword & jsuword(2)) != jsuword(0);
}
void setSystem() {
classword |= jsuword(2);
}
JSObject *getProto() const {
return JSVAL_TO_OBJECT(fslots[JSSLOT_PROTO]);
}
void clearProto() {
fslots[JSSLOT_PROTO] = JSVAL_NULL;
}
void setProto(JSObject *newProto) {
setDelegateNullSafe(newProto);
fslots[JSSLOT_PROTO] = OBJECT_TO_JSVAL(newProto);
}
JSObject *getParent() const {
return JSVAL_TO_OBJECT(fslots[JSSLOT_PARENT]);
}
void clearParent() {
fslots[JSSLOT_PARENT] = JSVAL_NULL;
}
void setParent(JSObject *newParent) {
setDelegateNullSafe(newParent);
fslots[JSSLOT_PARENT] = OBJECT_TO_JSVAL(newParent);
}
void traceProtoAndParent(JSTracer *trc) const {
JSObject *proto = getProto();
if (proto)
JS_CALL_OBJECT_TRACER(trc, proto, "__proto__");
JSObject *parent = getParent();
if (parent)
JS_CALL_OBJECT_TRACER(trc, parent, "__parent__");
}
void *getPrivate() const {
JS_ASSERT(getClass()->flags & JSCLASS_HAS_PRIVATE);
jsval v = fslots[JSSLOT_PRIVATE];
JS_ASSERT((v & jsval(1)) == jsval(0));
return reinterpret_cast<void *>(v);
}
void setPrivate(void *data) {
JS_ASSERT(getClass()->flags & JSCLASS_HAS_PRIVATE);
jsval v = reinterpret_cast<jsval>(data);
JS_ASSERT((v & jsval(1)) == jsval(0));
fslots[JSSLOT_PRIVATE] = v;
}
static jsval defaultPrivate(JSClass *clasp) {
return (clasp->flags & JSCLASS_HAS_PRIVATE)
? JSVAL_NULL
: JSVAL_VOID;
}
/* The map field is not initialized here and should be set separately. */
void init(JSClass *clasp, JSObject *proto, JSObject *parent,
jsval privateSlotValue) {
JS_ASSERT(((jsuword) clasp & 3) == 0);
JS_STATIC_ASSERT(JSSLOT_PRIVATE + 3 == JS_INITIAL_NSLOTS);
JS_ASSERT_IF(clasp->flags & JSCLASS_HAS_PRIVATE,
(privateSlotValue & jsval(1)) == jsval(0));
classword = jsuword(clasp);
JS_ASSERT(!isDelegate());
JS_ASSERT(!isSystem());
setProto(proto);
setParent(parent);
fslots[JSSLOT_PRIVATE] = privateSlotValue;
fslots[JSSLOT_PRIVATE + 1] = JSVAL_VOID;
fslots[JSSLOT_PRIVATE + 2] = JSVAL_VOID;
dslots = NULL;
}
/*
* Like init, but also initializes map. The catch: proto must be the result
* of a call to js_InitClass(...clasp, ...).
*/
inline void initSharingEmptyScope(JSClass *clasp, JSObject *proto, JSObject *parent,
jsval privateSlotValue);
JSBool lookupProperty(JSContext *cx, jsid id,
JSObject **objp, JSProperty **propp) {
return map->ops->lookupProperty(cx, this, id, objp, propp);
}
JSBool defineProperty(JSContext *cx, jsid id, jsval value,
JSPropertyOp getter = JS_PropertyStub,
JSPropertyOp setter = JS_PropertyStub,
uintN attrs = JSPROP_ENUMERATE) {
return map->ops->defineProperty(cx, this, id, value, getter, setter, attrs);
}
JSBool getProperty(JSContext *cx, jsid id, jsval *vp) {
return map->ops->getProperty(cx, this, id, vp);
}
JSBool setProperty(JSContext *cx, jsid id, jsval *vp) {
return map->ops->setProperty(cx, this, id, vp);
}
JSBool getAttributes(JSContext *cx, jsid id, JSProperty *prop,
uintN *attrsp) {
return map->ops->getAttributes(cx, this, id, prop, attrsp);
}
JSBool setAttributes(JSContext *cx, jsid id, JSProperty *prop,
uintN *attrsp) {
return map->ops->setAttributes(cx, this, id, prop, attrsp);
}
JSBool deleteProperty(JSContext *cx, jsid id, jsval *rval) {
return map->ops->deleteProperty(cx, this, id, rval);
}
JSBool defaultValue(JSContext *cx, JSType hint, jsval *vp) {
return map->ops->defaultValue(cx, this, hint, vp);
}
JSBool enumerate(JSContext *cx, JSIterateOp op, jsval *statep,
jsid *idp) {
return map->ops->enumerate(cx, this, op, statep, idp);
}
JSBool checkAccess(JSContext *cx, jsid id, JSAccessMode mode, jsval *vp,
uintN *attrsp) {
return map->ops->checkAccess(cx, this, id, mode, vp, attrsp);
}
/* These four are time-optimized to avoid stub calls. */
JSObject *thisObject(JSContext *cx) {
return map->ops->thisObject ? map->ops->thisObject(cx, this) : this;
}
void dropProperty(JSContext *cx, JSProperty *prop) {
if (map->ops->dropProperty)
map->ops->dropProperty(cx, this, prop);
}
};
/* Compatibility macros. */
#define STOBJ_GET_PROTO(obj) ((obj)->getProto())
#define STOBJ_SET_PROTO(obj,proto) ((obj)->setProto(proto))
#define STOBJ_CLEAR_PROTO(obj) ((obj)->clearProto())
#define STOBJ_GET_PARENT(obj) ((obj)->getParent())
#define STOBJ_SET_PARENT(obj,parent) ((obj)->setParent(parent))
#define STOBJ_CLEAR_PARENT(obj) ((obj)->clearParent())
#define OBJ_GET_PROTO(cx,obj) STOBJ_GET_PROTO(obj)
#define OBJ_SET_PROTO(cx,obj,proto) STOBJ_SET_PROTO(obj, proto)
#define OBJ_CLEAR_PROTO(cx,obj) STOBJ_CLEAR_PROTO(obj)
#define OBJ_GET_PARENT(cx,obj) STOBJ_GET_PARENT(obj)
#define OBJ_SET_PARENT(cx,obj,parent) STOBJ_SET_PARENT(obj, parent)
#define OBJ_CLEAR_PARENT(cx,obj) STOBJ_CLEAR_PARENT(obj)
#define JSSLOT_START(clasp) (((clasp)->flags & JSCLASS_HAS_PRIVATE) \
? JSSLOT_PRIVATE + 1 \
: JSSLOT_PRIVATE)
#define JSSLOT_FREE(clasp) (JSSLOT_START(clasp) \
+ JSCLASS_RESERVED_SLOTS(clasp))
/*
* Maximum capacity of the obj->dslots vector, net of the hidden slot at
* obj->dslots[-1] that is used to store the length of the vector biased by
* JS_INITIAL_NSLOTS (and again net of the slot at index -1).
*/
#define MAX_DSLOTS_LENGTH (JS_MAX(~uint32(0), ~size_t(0)) / sizeof(jsval) - 1)
#define MAX_DSLOTS_LENGTH32 (~uint32(0) / sizeof(jsval) - 1)
/*
* STOBJ prefix means Single Threaded Object. Use the following fast macros to
* directly manipulate slots in obj when only one thread can access obj, or
* when accessing read-only slots within JS_INITIAL_NSLOTS.
*/
#define STOBJ_NSLOTS(obj) \
((obj)->dslots ? (uint32)(obj)->dslots[-1] : (uint32)JS_INITIAL_NSLOTS)
inline jsval&
STOBJ_GET_SLOT(JSObject *obj, uintN slot)
{
return (slot < JS_INITIAL_NSLOTS)
? obj->fslots[slot]
: (JS_ASSERT(slot < (uint32)obj->dslots[-1]),
obj->dslots[slot - JS_INITIAL_NSLOTS]);
}
inline void
STOBJ_SET_SLOT(JSObject *obj, uintN slot, jsval value)
{
if (slot < JS_INITIAL_NSLOTS) {
obj->fslots[slot] = value;
} else {
JS_ASSERT(slot < (uint32)obj->dslots[-1]);
obj->dslots[slot - JS_INITIAL_NSLOTS] = value;
}
}
inline JSClass*
STOBJ_GET_CLASS(const JSObject* obj)
{
return obj->getClass();
}
#define OBJ_CHECK_SLOT(obj,slot) \
(JS_ASSERT(OBJ_IS_NATIVE(obj)), JS_ASSERT(slot < OBJ_SCOPE(obj)->freeslot))
#define LOCKED_OBJ_GET_SLOT(obj,slot) \
(OBJ_CHECK_SLOT(obj, slot), STOBJ_GET_SLOT(obj, slot))
#define LOCKED_OBJ_SET_SLOT(obj,slot,value) \
(OBJ_CHECK_SLOT(obj, slot), STOBJ_SET_SLOT(obj, slot, value))
#ifdef JS_THREADSAFE
/* Thread-safe functions and wrapper macros for accessing slots in obj. */
#define OBJ_GET_SLOT(cx,obj,slot) \
(OBJ_CHECK_SLOT(obj, slot), \
(OBJ_SCOPE(obj)->title.ownercx == cx) \
? LOCKED_OBJ_GET_SLOT(obj, slot) \
: js_GetSlotThreadSafe(cx, obj, slot))
#define OBJ_SET_SLOT(cx,obj,slot,value) \
JS_BEGIN_MACRO \
OBJ_CHECK_SLOT(obj, slot); \
if (OBJ_SCOPE(obj)->title.ownercx == cx) \
LOCKED_OBJ_SET_SLOT(obj, slot, value); \
else \
js_SetSlotThreadSafe(cx, obj, slot, value); \
JS_END_MACRO
/*
* If thread-safe, define an OBJ_GET_SLOT wrapper that bypasses, for a native
* object, the lock-free "fast path" test of (OBJ_SCOPE(obj)->ownercx == cx),
* to avoid needlessly switching from lock-free to lock-full scope when doing
* GC on a different context from the last one to own the scope. The caller
* in this case is probably a JSClass.mark function, e.g., fun_mark, or maybe
* a finalizer.
*
* The GC runs only when all threads except the one on which the GC is active
* are suspended at GC-safe points, so calling STOBJ_GET_SLOT from the GC's
* thread is safe when rt->gcRunning is set. See jsgc.c for details.
*/
#define THREAD_IS_RUNNING_GC(rt, thread) \
((rt)->gcRunning && (rt)->gcThread == (thread))
#define CX_THREAD_IS_RUNNING_GC(cx) \
THREAD_IS_RUNNING_GC((cx)->runtime, (cx)->thread)
#else /* !JS_THREADSAFE */
#define OBJ_GET_SLOT(cx,obj,slot) LOCKED_OBJ_GET_SLOT(obj,slot)
#define OBJ_SET_SLOT(cx,obj,slot,value) LOCKED_OBJ_SET_SLOT(obj,slot,value)
#endif /* !JS_THREADSAFE */
/*
* Class is invariant and comes from the fixed clasp member. Thus no locking
* is necessary to read it. Same for the private slot.
*/
#define OBJ_GET_CLASS(cx,obj) STOBJ_GET_CLASS(obj)
/*
* Test whether the object is native. FIXME bug 492938: consider how it would
* affect the performance to do just the !ops->objectMap check.
*/
#define OPS_IS_NATIVE(ops) \
JS_LIKELY((ops) == &js_ObjectOps || !(ops)->objectMap)
#define OBJ_IS_NATIVE(obj) OPS_IS_NATIVE((obj)->map->ops)
#ifdef __cplusplus
inline void
OBJ_TO_INNER_OBJECT(JSContext *cx, JSObject *&obj)
{
JSClass *clasp = OBJ_GET_CLASS(cx, obj);
if (clasp->flags & JSCLASS_IS_EXTENDED) {
JSExtendedClass *xclasp = (JSExtendedClass *) clasp;
if (xclasp->innerObject)
obj = xclasp->innerObject(cx, obj);
}
}
/*
* The following function has been copied to jsd/jsd_val.c. If making changes to
* OBJ_TO_OUTER_OBJECT, please update jsd/jsd_val.c as well.
*/
inline void
OBJ_TO_OUTER_OBJECT(JSContext *cx, JSObject *&obj)
{
JSClass *clasp = OBJ_GET_CLASS(cx, obj);
if (clasp->flags & JSCLASS_IS_EXTENDED) {
JSExtendedClass *xclasp = (JSExtendedClass *) clasp;
if (xclasp->outerObject)
obj = xclasp->outerObject(cx, obj);
}
}
#endif
extern JS_FRIEND_DATA(JSObjectOps) js_ObjectOps;
extern JS_FRIEND_DATA(JSObjectOps) js_WithObjectOps;
extern JSClass js_ObjectClass;
extern JSClass js_WithClass;
extern JSClass js_BlockClass;
/*
* Block scope object macros. The slots reserved by js_BlockClass are:
*
* JSSLOT_PRIVATE JSStackFrame * active frame pointer or null
* JSSLOT_BLOCK_DEPTH int depth of block slots in frame
*
* After JSSLOT_BLOCK_DEPTH come one or more slots for the block locals.
*
* A With object is like a Block object, in that both have one reserved slot
* telling the stack depth of the relevant slots (the slot whose value is the
* object named in the with statement, the slots containing the block's local
* variables); and both have a private slot referring to the JSStackFrame in
* whose activation they were created (or null if the with or block object
* outlives the frame).
*/
#define JSSLOT_BLOCK_DEPTH (JSSLOT_PRIVATE + 1)
static inline bool
OBJ_IS_CLONED_BLOCK(JSObject *obj)
{
return obj->getProto() != NULL;
}
extern JSBool
js_DefineBlockVariable(JSContext *cx, JSObject *obj, jsid id, intN index);
#define OBJ_BLOCK_COUNT(cx,obj) \
(OBJ_SCOPE(obj)->entryCount)
#define OBJ_BLOCK_DEPTH(cx,obj) \
JSVAL_TO_INT(STOBJ_GET_SLOT(obj, JSSLOT_BLOCK_DEPTH))
#define OBJ_SET_BLOCK_DEPTH(cx,obj,depth) \
STOBJ_SET_SLOT(obj, JSSLOT_BLOCK_DEPTH, INT_TO_JSVAL(depth))
/*
* To make sure this slot is well-defined, always call js_NewWithObject to
* create a With object, don't call js_NewObject directly. When creating a
* With object that does not correspond to a stack slot, pass -1 for depth.
*
* When popping the stack across this object's "with" statement, client code
* must call withobj->setPrivate(NULL).
*/
extern JS_REQUIRES_STACK JSObject *
js_NewWithObject(JSContext *cx, JSObject *proto, JSObject *parent, jsint depth);
/*
* Create a new block scope object not linked to any proto or parent object.
* Blocks are created by the compiler to reify let blocks and comprehensions.
* Only when dynamic scope is captured do they need to be cloned and spliced
* into an active scope chain.
*/
extern JSObject *
js_NewBlockObject(JSContext *cx);
extern JSObject *
js_CloneBlockObject(JSContext *cx, JSObject *proto, JSStackFrame *fp);
extern JS_REQUIRES_STACK JSBool
js_PutBlockObject(JSContext *cx, JSBool normalUnwind);
JSBool
js_XDRBlockObject(JSXDRState *xdr, JSObject **objp);
struct JSSharpObjectMap {
jsrefcount depth;
jsatomid sharpgen;
JSHashTable *table;
};
#define SHARP_BIT ((jsatomid) 1)
#define BUSY_BIT ((jsatomid) 2)
#define SHARP_ID_SHIFT 2
#define IS_SHARP(he) (JS_PTR_TO_UINT32((he)->value) & SHARP_BIT)
#define MAKE_SHARP(he) ((he)->value = JS_UINT32_TO_PTR(JS_PTR_TO_UINT32((he)->value)|SHARP_BIT))
#define IS_BUSY(he) (JS_PTR_TO_UINT32((he)->value) & BUSY_BIT)
#define MAKE_BUSY(he) ((he)->value = JS_UINT32_TO_PTR(JS_PTR_TO_UINT32((he)->value)|BUSY_BIT))
#define CLEAR_BUSY(he) ((he)->value = JS_UINT32_TO_PTR(JS_PTR_TO_UINT32((he)->value)&~BUSY_BIT))
extern JSHashEntry *
js_EnterSharpObject(JSContext *cx, JSObject *obj, JSIdArray **idap,
jschar **sp);
extern void
js_LeaveSharpObject(JSContext *cx, JSIdArray **idap);
/*
* Mark objects stored in map if GC happens between js_EnterSharpObject
* and js_LeaveSharpObject. GC calls this when map->depth > 0.
*/
extern void
js_TraceSharpMap(JSTracer *trc, JSSharpObjectMap *map);
extern JSBool
js_HasOwnPropertyHelper(JSContext *cx, JSLookupPropOp lookup, uintN argc,
jsval *vp);
extern JSBool
js_HasOwnProperty(JSContext *cx, JSLookupPropOp lookup, JSObject *obj, jsid id,
JSBool *foundp);
extern JSBool
js_PropertyIsEnumerable(JSContext *cx, JSObject *obj, jsid id, jsval *vp);
extern JSObject *
js_InitEval(JSContext *cx, JSObject *obj);
extern JSObject *
js_InitObjectClass(JSContext *cx, JSObject *obj);
extern JSObject *
js_InitClass(JSContext *cx, JSObject *obj, JSObject *parent_proto,
JSClass *clasp, JSNative constructor, uintN nargs,
JSPropertySpec *ps, JSFunctionSpec *fs,
JSPropertySpec *static_ps, JSFunctionSpec *static_fs);
/*
* Select Object.prototype method names shared between jsapi.cpp and jsobj.cpp.
*/
extern const char js_watch_str[];
extern const char js_unwatch_str[];
extern const char js_hasOwnProperty_str[];
extern const char js_isPrototypeOf_str[];
extern const char js_propertyIsEnumerable_str[];
extern const char js_defineGetter_str[];
extern const char js_defineSetter_str[];
extern const char js_lookupGetter_str[];
extern const char js_lookupSetter_str[];
extern JSBool
js_GetClassId(JSContext *cx, JSClass *clasp, jsid *idp);
extern JSObject *
js_NewObject(JSContext *cx, JSClass *clasp, JSObject *proto,
JSObject *parent, size_t objectSize = 0);
/*
* See jsapi.h, JS_NewObjectWithGivenProto.
*/
extern JSObject *
js_NewObjectWithGivenProto(JSContext *cx, JSClass *clasp, JSObject *proto,
JSObject *parent, size_t objectSize = 0);
/*
* Allocate a new native object with the given value of the proto and private
* slots. The parent slot is set to the value of proto's parent slot.
*
* clasp must be a native class. proto must be the result of a call to
* js_InitClass(...clasp, ...).
*
* Note that this is the correct global object for native class instances, but
* not for user-defined functions called as constructors. Functions used as
* constructors must create instances parented by the parent of the function
* object, not by the parent of its .prototype object value.
*/
extern JSObject*
js_NewObjectWithClassProto(JSContext *cx, JSClass *clasp, JSObject *proto,
jsval privateSlotValue);
/*
* Fast access to immutable standard objects (constructors and prototypes).
*/
extern JSBool
js_GetClassObject(JSContext *cx, JSObject *obj, JSProtoKey key,
JSObject **objp);
extern JSBool
js_SetClassObject(JSContext *cx, JSObject *obj, JSProtoKey key, JSObject *cobj);
extern JSBool
js_FindClassObject(JSContext *cx, JSObject *start, jsid id, jsval *vp);
extern JSObject *
js_ConstructObject(JSContext *cx, JSClass *clasp, JSObject *proto,
JSObject *parent, uintN argc, jsval *argv);
extern JSBool
js_AllocSlot(JSContext *cx, JSObject *obj, uint32 *slotp);
extern void
js_FreeSlot(JSContext *cx, JSObject *obj, uint32 slot);
extern bool
js_GrowSlots(JSContext *cx, JSObject *obj, size_t nslots);
extern void
js_ShrinkSlots(JSContext *cx, JSObject *obj, size_t nslots);
static inline void
js_FreeSlots(JSContext *cx, JSObject *obj)
{
if (obj->dslots)
js_ShrinkSlots(cx, obj, 0);
}
/*
* Ensure that the object has at least JSCLASS_RESERVED_SLOTS(clasp)+nreserved
* slots. The function can be called only for native objects just created with
* js_NewObject or its forms. In particular, the object should not be shared
* between threads and its dslots array must be null. nreserved must match the
* value that JSClass.reserveSlots (if any) would return after the object is
* fully initialized.
*/
bool
js_EnsureReservedSlots(JSContext *cx, JSObject *obj, size_t nreserved);
extern jsid
js_CheckForStringIndex(jsid id);
/*
* js_PurgeScopeChain does nothing if obj is not itself a prototype or parent
* scope, else it reshapes the scope and prototype chains it links. It calls
* js_PurgeScopeChainHelper, which asserts that obj is flagged as a delegate
* (i.e., obj has ever been on a prototype or parent chain).
*/
extern void
js_PurgeScopeChainHelper(JSContext *cx, JSObject *obj, jsid id);
#ifdef __cplusplus /* Aargh, libgjs, bug 492720. */
static JS_INLINE void
js_PurgeScopeChain(JSContext *cx, JSObject *obj, jsid id)
{
if (obj->isDelegate())
js_PurgeScopeChainHelper(cx, obj, id);
}
#endif
/*
* Find or create a property named by id in obj's scope, with the given getter
* and setter, slot, attributes, and other members.
*/
extern JSScopeProperty *
js_AddNativeProperty(JSContext *cx, JSObject *obj, jsid id,
JSPropertyOp getter, JSPropertyOp setter, uint32 slot,
uintN attrs, uintN flags, intN shortid);
/*
* Change sprop to have the given attrs, getter, and setter in scope, morphing
* it into a potentially new JSScopeProperty. Return a pointer to the changed
* or identical property.
*/
extern JSScopeProperty *
js_ChangeNativePropertyAttrs(JSContext *cx, JSObject *obj,
JSScopeProperty *sprop, uintN attrs, uintN mask,
JSPropertyOp getter, JSPropertyOp setter);
extern JSBool
js_DefineProperty(JSContext *cx, JSObject *obj, jsid id, jsval value,
JSPropertyOp getter, JSPropertyOp setter, uintN attrs);
/*
* Flags for the defineHow parameter of js_DefineNativeProperty.
*/
const uintN JSDNP_CACHE_RESULT = 1; /* an interpreter call from JSOP_INITPROP */
const uintN JSDNP_DONT_PURGE = 2; /* suppress js_PurgeScopeChain */
const uintN JSDNP_SET_METHOD = 4; /* js_{DefineNativeProperty,SetPropertyHelper}
must pass the SPROP_IS_METHOD flag on to
js_AddScopeProperty */
/*
* On error, return false. On success, if propp is non-null, return true with
* obj locked and with a held property in *propp; if propp is null, return true
* but release obj's lock first. Therefore all callers who pass non-null propp
* result parameters must later call obj->dropProperty(cx, *propp) both to drop
* the held property, and to release the lock on obj.
*/
extern JSBool
js_DefineNativeProperty(JSContext *cx, JSObject *obj, jsid id, jsval value,
JSPropertyOp getter, JSPropertyOp setter, uintN attrs,
uintN flags, intN shortid, JSProperty **propp,
uintN defineHow = 0);
/*
* Unlike js_DefineNativeProperty, propp must be non-null. On success, and if
* id was found, return true with *objp non-null and locked, and with a held
* property stored in *propp. If successful but id was not found, return true
* with both *objp and *propp null. Therefore all callers who receive a
* non-null *propp must later call (*objp)->dropProperty(cx, *propp).
*/
extern JS_FRIEND_API(JSBool)
js_LookupProperty(JSContext *cx, JSObject *obj, jsid id, JSObject **objp,
JSProperty **propp);
/*
* Specialized subroutine that allows caller to preset JSRESOLVE_* flags and
* returns the index along the prototype chain in which *propp was found, or
* the last index if not found, or -1 on error.
*/
extern int
js_LookupPropertyWithFlags(JSContext *cx, JSObject *obj, jsid id, uintN flags,
JSObject **objp, JSProperty **propp);
/*
* We cache name lookup results only for the global object or for native
* non-global objects without prototype or with prototype that never mutates,
* see bug 462734 and bug 487039.
*/
static inline bool
js_IsCacheableNonGlobalScope(JSObject *obj)
{
extern JS_FRIEND_DATA(JSClass) js_CallClass;
extern JS_FRIEND_DATA(JSClass) js_DeclEnvClass;
JS_ASSERT(STOBJ_GET_PARENT(obj));
JSClass *clasp = STOBJ_GET_CLASS(obj);
bool cacheable = (clasp == &js_CallClass ||
clasp == &js_BlockClass ||
clasp == &js_DeclEnvClass);
JS_ASSERT_IF(cacheable, obj->map->ops->lookupProperty == js_LookupProperty);
return cacheable;
}
/*
* If cacheResult is false, return JS_NO_PROP_CACHE_FILL on success.
*/
extern JSPropCacheEntry *
js_FindPropertyHelper(JSContext *cx, jsid id, JSBool cacheResult,
JSObject **objp, JSObject **pobjp, JSProperty **propp);
/*
* Return the index along the scope chain in which id was found, or the last
* index if not found, or -1 on error.
*/
extern JS_FRIEND_API(JSBool)
js_FindProperty(JSContext *cx, jsid id, JSObject **objp, JSObject **pobjp,
JSProperty **propp);
extern JS_REQUIRES_STACK JSObject *
js_FindIdentifierBase(JSContext *cx, JSObject *scopeChain, jsid id);
extern JSObject *
js_FindVariableScope(JSContext *cx, JSFunction **funp);
/*
* JSGET_CACHE_RESULT is the analogue of JSDNP_CACHE_RESULT for js_GetMethod.
*
* JSGET_METHOD_BARRIER (the default, hence 0 but provided for documentation)
* enables a read barrier that preserves standard function object semantics (by
* default we assume our caller won't leak a joined callee to script, where it
* would create hazardous mutable object sharing as well as observable identity
* according to == and ===.
*
* JSGET_NO_METHOD_BARRIER avoids the performance overhead of the method read
* barrier, which is not needed when invoking a lambda that otherwise does not
* leak its callee reference (via arguments.callee or its name).
*/
const uintN JSGET_CACHE_RESULT = 1; // from a caching interpreter opcode
const uintN JSGET_METHOD_BARRIER = 0; // get can leak joined function object
const uintN JSGET_NO_METHOD_BARRIER = 2; // call to joined function can't leak
/*
* NB: js_NativeGet and js_NativeSet are called with the scope containing sprop
* (pobj's scope for Get, obj's for Set) locked, and on successful return, that
* scope is again locked. But on failure, both functions return false with the
* scope containing sprop unlocked.
*/
extern JSBool
js_NativeGet(JSContext *cx, JSObject *obj, JSObject *pobj,
JSScopeProperty *sprop, uintN getHow, jsval *vp);
extern JSBool
js_NativeSet(JSContext *cx, JSObject *obj, JSScopeProperty *sprop, bool added,
jsval *vp);
extern JSBool
js_GetPropertyHelper(JSContext *cx, JSObject *obj, jsid id, uintN getHow,
jsval *vp);
extern JSBool
js_GetProperty(JSContext *cx, JSObject *obj, jsid id, jsval *vp);
extern JSBool
js_GetMethod(JSContext *cx, JSObject *obj, jsid id, uintN getHow, jsval *vp);
/*
* Check whether it is OK to assign an undeclared property of the global
* object at the current script PC.
*/
extern JS_FRIEND_API(bool)
js_CheckUndeclaredVarAssignment(JSContext *cx);
extern JSBool
js_SetPropertyHelper(JSContext *cx, JSObject *obj, jsid id, uintN defineHow,
jsval *vp);
extern JSBool
js_SetProperty(JSContext *cx, JSObject *obj, jsid id, jsval *vp);
extern JSBool
js_GetAttributes(JSContext *cx, JSObject *obj, jsid id, JSProperty *prop,
uintN *attrsp);
extern JSBool
js_SetAttributes(JSContext *cx, JSObject *obj, jsid id, JSProperty *prop,
uintN *attrsp);
extern JSBool
js_DeleteProperty(JSContext *cx, JSObject *obj, jsid id, jsval *rval);
extern JSBool
js_DefaultValue(JSContext *cx, JSObject *obj, JSType hint, jsval *vp);
extern JSBool
js_Enumerate(JSContext *cx, JSObject *obj, JSIterateOp enum_op,
jsval *statep, jsid *idp);
extern void
js_MarkEnumeratorState(JSTracer *trc, JSObject *obj, jsval state);
extern void
js_PurgeCachedNativeEnumerators(JSContext *cx, JSThreadData *data);
extern JSBool
js_CheckAccess(JSContext *cx, JSObject *obj, jsid id, JSAccessMode mode,
jsval *vp, uintN *attrsp);
extern JSBool
js_Call(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval);
extern JSBool
js_Construct(JSContext *cx, JSObject *obj, uintN argc, jsval *argv,
jsval *rval);
extern JSBool
js_HasInstance(JSContext *cx, JSObject *obj, jsval v, JSBool *bp);
extern JSBool
js_SetProtoOrParent(JSContext *cx, JSObject *obj, uint32 slot, JSObject *pobj,
JSBool checkForCycles);
extern JSBool
js_IsDelegate(JSContext *cx, JSObject *obj, jsval v, JSBool *bp);
extern JSBool
js_GetClassPrototype(JSContext *cx, JSObject *scope, jsid id,
JSObject **protop);
extern JSBool
js_SetClassPrototype(JSContext *cx, JSObject *ctor, JSObject *proto,
uintN attrs);
/*
* Wrap boolean, number or string as Boolean, Number or String object.
* *vp must not be an object, null or undefined.
*/
extern JSBool
js_PrimitiveToObject(JSContext *cx, jsval *vp);
extern JSBool
js_ValueToObject(JSContext *cx, jsval v, JSObject **objp);
extern JSObject *
js_ValueToNonNullObject(JSContext *cx, jsval v);
extern JSBool
js_TryValueOf(JSContext *cx, JSObject *obj, JSType type, jsval *rval);
extern JSBool
js_TryMethod(JSContext *cx, JSObject *obj, JSAtom *atom,
uintN argc, jsval *argv, jsval *rval);
extern JSBool
js_XDRObject(JSXDRState *xdr, JSObject **objp);
extern void
js_TraceObject(JSTracer *trc, JSObject *obj);
extern void
js_PrintObjectSlotName(JSTracer *trc, char *buf, size_t bufsize);
extern void
js_Clear(JSContext *cx, JSObject *obj);
extern bool
js_GetReservedSlot(JSContext *cx, JSObject *obj, uint32 index, jsval *vp);
bool
js_SetReservedSlot(JSContext *cx, JSObject *obj, uint32 index, jsval v);
/*
* Precondition: obj must be locked.
*/
extern JSBool
js_ReallocSlots(JSContext *cx, JSObject *obj, uint32 nslots,
JSBool exactAllocation);
extern JSObject *
js_CheckScopeChainValidity(JSContext *cx, JSObject *scopeobj, const char *caller);
extern JSBool
js_CheckPrincipalsAccess(JSContext *cx, JSObject *scopeobj,
JSPrincipals *principals, JSAtom *caller);
/* Infallible -- returns its argument if there is no wrapped object. */
extern JSObject *
js_GetWrappedObject(JSContext *cx, JSObject *obj);
/* NB: Infallible. */
extern const char *
js_ComputeFilename(JSContext *cx, JSStackFrame *caller,
JSPrincipals *principals, uintN *linenop);
/* Infallible, therefore cx is last parameter instead of first. */
extern JSBool
js_IsCallable(JSObject *obj, JSContext *cx);
void
js_ReportGetterOnlyAssignment(JSContext *cx);
extern JS_FRIEND_API(JSBool)
js_GetterOnlyPropertyStub(JSContext *cx, JSObject *obj, jsval id, jsval *vp);
#ifdef DEBUG
JS_FRIEND_API(void) js_DumpChars(const jschar *s, size_t n);
JS_FRIEND_API(void) js_DumpString(JSString *str);
JS_FRIEND_API(void) js_DumpAtom(JSAtom *atom);
JS_FRIEND_API(void) js_DumpValue(jsval val);
JS_FRIEND_API(void) js_DumpId(jsid id);
JS_FRIEND_API(void) js_DumpObject(JSObject *obj);
JS_FRIEND_API(void) js_DumpStackFrame(JSStackFrame *fp);
#endif
extern uintN
js_InferFlags(JSContext *cx, uintN defaultFlags);
/* Object constructor native. Exposed only so the JIT can know its address. */
JSBool
js_Object(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval);
JS_END_EXTERN_C
#endif /* jsobj_h___ */
|
apache-2.0
|
aws/aws-sdk-java
|
aws-java-sdk-iotfleethub/src/main/java/com/amazonaws/services/iotfleethub/model/transform/ListTagsForResourceResultJsonUnmarshaller.java
|
2982
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 com.amazonaws.services.iotfleethub.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.iotfleethub.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* ListTagsForResourceResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListTagsForResourceResultJsonUnmarshaller implements Unmarshaller<ListTagsForResourceResult, JsonUnmarshallerContext> {
public ListTagsForResourceResult unmarshall(JsonUnmarshallerContext context) throws Exception {
ListTagsForResourceResult listTagsForResourceResult = new ListTagsForResourceResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return listTagsForResourceResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("tags", targetDepth)) {
context.nextToken();
listTagsForResourceResult.setTags(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class), context
.getUnmarshaller(String.class)).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return listTagsForResourceResult;
}
private static ListTagsForResourceResultJsonUnmarshaller instance;
public static ListTagsForResourceResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new ListTagsForResourceResultJsonUnmarshaller();
return instance;
}
}
|
apache-2.0
|
Dennis-Koch/ambeth
|
jambeth/jambeth-ioc/src/main/java/com/koch/ambeth/ioc/BeanMonitoringSupport.java
|
1213
|
package com.koch.ambeth.ioc;
import com.koch.ambeth.ioc.util.IImmutableTypeSet;
import com.koch.ambeth.util.IConversionHelper;
import com.koch.ambeth.util.typeinfo.IPropertyInfoProvider;
public class BeanMonitoringSupport extends AbstractBeanMonitoringSupport {
private IServiceContext beanContext;
private IPropertyInfoProvider propertyInfoProvider;
private IConversionHelper conversionHelper;
private IImmutableTypeSet immutableTypeSet;
public BeanMonitoringSupport(Object bean, IServiceContext beanContext) {
super(bean);
this.beanContext = beanContext;
}
@Override
protected IPropertyInfoProvider getPropertyInfoProvider() {
if (propertyInfoProvider == null) {
propertyInfoProvider = beanContext.getService(IPropertyInfoProvider.class);
}
return propertyInfoProvider;
}
@Override
protected IConversionHelper getConversionHelper() {
if (conversionHelper == null) {
conversionHelper = beanContext.getService(IConversionHelper.class);
}
return conversionHelper;
}
@Override
protected IImmutableTypeSet getImmutableTypeSet() {
if (immutableTypeSet == null) {
immutableTypeSet = beanContext.getService(IImmutableTypeSet.class);
}
return immutableTypeSet;
}
}
|
apache-2.0
|
MikeLx/open-source-search-engine
|
SafeBuf.h
|
13471
|
#ifndef _SAFEBUF_H_
#define _SAFEBUF_H_
//#include "Mem.h"
//#include "Unicode.h"
#include "gb-include.h"
/**
* Safe Char Buffer, or mutable Strings.
* (for java programmers, very similar to the StringBuffer class, with all the speed that c++ allows).
* Most of strings in Gigablast are handled by those.
*/
#include "iana_charset.h"
class SafeBuf {
public:
//*TRUCTORS
SafeBuf();
SafeBuf(int32_t initSize, char *label = NULL);
void constructor();
//be careful with passing in a stackBuf! it could go out
//of scope independently of the safebuf.
SafeBuf(char* stackBuf, int32_t cap);
SafeBuf(char *heapBuf, int32_t bufMax, int32_t bytesInUse, bool ownData);
~SafeBuf();
void setLabel ( char *label );
// CAUTION: BE CAREFUL WHEN USING THE FOLLOWING TWO FUNCTIONS!!
// setBuf() allows you reset the contents of the SafeBuf to either
// a stack buffer or a dynamic buffer. Only pass in true for
// ownData if this is not a stack buffer and you are sure you
// want SafeBuf to free the data for you. Keep in mind, all
// previous content in SafeBuf will be cleared when you pass it
// a new buffer.
bool setBuf(char *newBuf,
int32_t bufMax,
int32_t bytesInUse,
bool ownData,
int16_t encoding = csUTF8 );
// yieldBuf() allows you to take over the buffer in SafeBuf.
// You may only free the data if it was originally owned by
// the SafeBuf.
// Think twice before using this function.
bool yieldBuf(char **bufPtr, int32_t *bufAlloc, int32_t *bytesInUse,
bool *ownData, int16_t *encoding );
// set buffer from another safebuf, stealing it
bool stealBuf ( SafeBuf *sb );
//ACCESSORS
char *getBuf() { return m_buf + m_length; }
char *getBufStart() { return m_buf; }
char *getBufEnd() { return m_buf + m_capacity; }
int32_t getCapacity() { return m_capacity; }
int32_t getAvail() { return m_capacity - m_length; }
int32_t length() { return m_length; }
int32_t getLength() { return m_length; }
int32_t getBufUsed() { return m_length; }
void print() {
if ( write(1,m_buf,m_length) != m_length) { char*xx=NULL;*xx=0;}; }
// . returns bytes written to file, 0 is acceptable if m_length == 0
// . returns -1 on error and sets g_errno
int32_t saveToFile ( char *dir , char *filename ) ;
int32_t dumpToFile(char *filename);
int32_t save ( char *dir, char *fname){return saveToFile(dir,fname); };
int32_t save ( char *fullFilename ) ;
// saves to tmp file and if that succeeds then renames to orig filename
int32_t safeSave (char *filename );
int32_t fillFromFile(char *filename);
int32_t fillFromFile(char *dir,char *filename, char *label=NULL);
int32_t load(char *dir,char *fname,char *label = NULL) {
return fillFromFile(dir,fname,label);};
int32_t load(char *fname) { return fillFromFile(fname);};
void filterTags();
void filterQuotes();
bool truncateLongWords ( char *src, int32_t srcLen , int32_t minmax );
bool safeTruncateEllipsis ( char *src , int32_t maxLen );
bool safeTruncateEllipsis ( char *src , int32_t srcLen, int32_t maxLen );
bool convertJSONtoXML ( int32_t niceness , int32_t startConvertPos );
bool safeDecodeJSONToUtf8 ( char *json, int32_t jsonLen,
int32_t niceness);
// bool decodeAll = false );
bool decodeJSONToUtf8 ( int32_t niceness );
bool decodeJSON ( int32_t niceness );
bool linkify ( int32_t niceness , int32_t startPos );
void truncLen ( int32_t newLen ) {
if ( m_length > newLen ) m_length = newLen; };
bool set ( char *str ) {
purge();
if ( ! str ) return true;
// puts a \0 at the end, but does not include it in m_length:
return safeStrcpy ( str );
};
void removeLastChar ( char lastChar ) {
if ( m_length <= 0 ) return;
if ( m_buf[m_length-1] != lastChar ) return;
m_length--;
m_buf[m_length] = '\0';
};
//MUTATORS
#ifdef _CHECK_FORMAT_STRING_
bool safePrintf(char *formatString, ...)
__attribute__ ((format(printf, 2, 3)));
#else
bool safePrintf(char *formatString, ...);
#endif
bool safeMemcpy(void *s, int32_t len){return safeMemcpy((char *)s,len);};
bool safeMemcpy(char *s, int32_t len);
bool safeMemcpy_nospaces(char *s, int32_t len);
bool safeMemcpy(SafeBuf *c){return safeMemcpy(c->m_buf,c->m_length);};
bool safeMemcpy ( class Words *w , int32_t a , int32_t b ) ;
bool safeStrcpy ( char *s ) ;
//bool safeStrcpyPrettyJSON ( char *decodedJson ) ;
bool safeUtf8ToJSON ( char *utf8 ) ;
bool jsonEncode ( char *utf8 ) { return safeUtf8ToJSON(utf8); };
bool jsonEncode ( char *utf8 , int32_t utf8Len );
bool csvEncode ( char *s , int32_t len , int32_t niceness = 0 );
bool base64Encode ( char *s , int32_t len , int32_t niceness = 0 );
bool base64Decode ( char *src , int32_t srcLen , int32_t niceness = 0 ) ;
bool base64Encode( char *s ) ;
//bool pushLong ( int32_t val ) { return safeMemcpy((char *)&val,4); }
bool cat(SafeBuf& c);
// . only cat the sections/tag that start with "tagFilter"
// . used by Spider.cpp to dump <div class=int16_tdisplay> sections
// to parse-int16_tdisplay.uh64.runid.txt for displaying the
// validation checkboxes in qa.html
bool cat2 ( SafeBuf& c,char *tagFilter1,char *tagFilter2);
void reset() { m_length = 0; }
void purge(); // Clear all data and free all allocated memory
bool advance ( int32_t i ) ;
bool safePrintFilterTagsAndLines ( char *p , int32_t plen ,
bool oneWordPerLine ) ;
// . if clearIt is true we init the new buffer space to zeroes
// . used by Collectiondb.cpp
bool reserve(int32_t i, char *label=NULL , bool clearIt = false );
bool reserve2x(int32_t i, char *label = NULL );
char *makeSpace ( int32_t size ) {
if ( ! reserve ( size ) ) return NULL;
return m_buf + m_length;
};
bool inlineStyleTags();
void incrementLength(int32_t i) {
m_length += i;
// watch out for negative i's
if ( m_length < 0 ) m_length = 0;
};
void setLength(int32_t i) { m_length = i; };
char *getNextLine ( char *p ) ;
int32_t catFile(char *filename) ;
//int32_t load(char *dir,char *filename) {
// return fillFromFile(dir,filename);};
bool safeLatin1ToUtf8(char *s, int32_t len);
bool safeUtf8ToLatin1(char *s, int32_t len);
void detachBuf();
bool insert ( class SafeBuf *c , int32_t insertPos ) ;
bool insert ( char *s , int32_t insertPos ) ;
bool insert2 ( char *s , int32_t slen, int32_t insertPos ) ;
bool replace ( char *src , char *dst ) ; // must be same lengths!
bool removeChunk1 ( char *p , int32_t len ) ;
bool removeChunk2 ( int32_t pos , int32_t len ) ;
bool safeReplace(char *s, int32_t len, int32_t pos, int32_t replaceLen);
bool safeReplace2 ( char *s, int32_t slen,
char *t , int32_t tlen ,
int32_t niceness ,
int32_t startOff = 0 );
bool safeReplace3 ( char *s, char *t , int32_t niceness = 0 ) ;
void replaceChar ( char src , char dst );
bool copyToken(char* s);;
//output encoding
bool setEncoding(int16_t cs);
int16_t getEncoding() { return m_encoding; };
void zeroOut() { memset ( m_buf , 0 , m_capacity ); }
// insert <br>'s to make 's' no more than 'cols' chars per line
bool brify2 ( char *s , int32_t cols , char *sep = "<br>" ,
bool isHtml = true ) ;
bool brify ( char *s , int32_t slen , int32_t niceness , int32_t cols ,
char *sep = "<br>" , bool isHtml = true );
bool fixIsolatedPeriods ( ) ;
bool hasDigits();
// treat safebuf as an array of signed int32_ts and sort them
void sortLongs ( int32_t niceness );
// . like "1 minute ago" "5 hours ago" "3 days ago" etc.
// . "ts" is the delta-t in seconds
bool printTimeAgo ( int32_t ts , int32_t now , bool int16_thand = false ) ;
// . a function for adding Tags to buffer, like from Tagdb.cpp
// . if safebuf is a buffer of Tags from Tagdb.cpp
class Tag *addTag2 ( char *mysite ,
char *tagname ,
int32_t now ,
char *user ,
int32_t ip ,
int32_t val ,
char rdbId );
class Tag *addTag3 ( char *mysite ,
char *tagname ,
int32_t now ,
char *user ,
int32_t ip ,
char *data ,
char rdbId );
// makes the site "%"UINT64".com" where %"UINT64" is userId
class Tag *addFaceookTag ( int64_t userId ,
char *tagname ,
int32_t now ,
int32_t ip ,
char *data ,
int32_t dsize ,
char rdbId ,
bool pushRdbId ) ;
class Tag *addTag ( char *mysite ,
char *tagname ,
int32_t now ,
char *user ,
int32_t ip ,
char *data ,
int32_t dsize ,
char rdbId ,
bool pushRdbId );
bool addTag ( class Tag *tag );
//insert strings in their native encoding
bool encode ( char *s , int32_t len , int32_t niceness=0) {
return utf8Encode2(s,len,false,niceness); };
// htmlEncode default = false
bool utf8Encode2(char *s, int32_t len, bool htmlEncode=false,
int32_t niceness=0);
bool latin1Encode(char *s, int32_t len, bool htmlEncode=false,
int32_t niceness=0);
//bool utf16Encode(UChar *s, int32_t len, bool htmlEncode=false);
//bool utf16Encode(char *s, int32_t len, bool htmlEncode=false) {
// return utf16Encode((UChar*)s, len>>1, htmlEncode); };
//bool utf32Encode(UChar32 c);
bool htmlEncode(char *s, int32_t len,bool encodePoundSign,
int32_t niceness=0 , int32_t truncateLen = -1 );
bool javascriptEncode(char *s, int32_t len );
bool htmlEncode(char *s) ;
//bool convertUtf8CharsToEntity = false ) ;
// html-encode any of the last "len" bytes that need it
bool htmlEncode(int32_t len,int32_t niceness=0);
bool htmlDecode (char *s,
int32_t len,
bool doSpecial = false,
int32_t niceness = 0 );
//bool htmlEncode(int32_t niceness );
bool dequote ( char *t , int32_t tlen );
bool escapeJS ( char *s , int32_t slen ) ;
bool urlEncode (char *s ,
int32_t slen,
bool requestPath = false,
bool encodeApostrophes = false );
bool urlEncode (char *s ) {
return urlEncode ( s,strlen(s),false,false); };
bool urlEncode2 (char *s ,
bool encodeApostrophes ) { // usually false
return urlEncode ( s,strlen(s),false,encodeApostrophes); };
bool urlEncodeAllBuf ( bool spaceToPlus = true );
bool latin1CdataEncode(char *s, int32_t len);
bool utf8CdataEncode(char *s, int32_t len);
// . filter out parentheses and other query operators
// . used by SearchInput.cpp when it constructs the big UOR query
// of facebook interests
bool queryFilter ( char *s , int32_t len );
//bool utf16CdataEncode(UChar *s, int32_t len);
//bool utf16CdataEncode(char *s, int32_t len) {
// return utf16CdataEncode((UChar*)s, len>>1); };
bool latin1HtmlEncode(char *s, int32_t len, int32_t niceness=0);
//bool utf16HtmlEncode(UChar *s, int32_t len);
//bool utf16HtmlEncode(char *s, int32_t len) {
// return utf16HtmlEncode((UChar*)s, len>>1); };
bool htmlEncodeXmlTags ( char *s , int32_t slen , int32_t niceness ) ;
bool cdataEncode ( char *s ) ;
bool cdataEncode ( char *s , int32_t slen ) ;
// . append a \0 but do not inc m_length
// . for null terminating strings
bool nullTerm ( ) {
if(m_length >= m_capacity && !reserve(m_capacity + 1) )
return false;
m_buf[m_length] = '\0';
return true;
};
bool safeCdataMemcpy(char *s, int32_t len);
bool pushChar (char i) {
if(m_length >= m_capacity)
if(!reserve(2*m_capacity + 1))
return false;
m_buf[m_length++] = i;
// let's do this because we kinda expect it when making strings
// and i've been burned by not having this before.
// no, cause if we reserve just the right length, we end up
// doing a realloc!! sux...
//m_buf[m_length] = '\0';
return true;
};
// hack off trailing 0's
bool printFloatPretty ( float f ) ;
bool pushPtr ( void *ptr );
bool pushLong (int32_t i);
bool pushLongLong (int64_t i);
bool pushFloat (float i);
bool pushDouble (double i);
int32_t popLong();
float popFloat();
int32_t pad(const char ch, const int32_t len);
bool printKey(char* key, char ks);
// these use zlib
bool compress();
bool uncompress();
//OPERATORS
//copy numbers into the buffer, *in binary*
//useful for making lists.
bool operator += (uint64_t i);
bool operator += (int64_t i);
//bool operator += (int32_t i);
//bool operator += (uint32_t i);
bool operator += (float i);
bool operator += (double i);
bool operator += (char i);
//bool operator += (uint64_t i);
bool operator += (uint32_t i);
bool operator += (uint16_t i);
bool operator += (uint8_t i);
//bool operator += (int64_t i) { return *this += (uint64_t)i; };
bool operator += (int32_t i) { return *this += (uint32_t)i; };
bool operator += (int16_t i) { return *this += (uint16_t)i; };
bool operator += (int8_t i) { return *this += (uint8_t)i; };
//return a reference so we can use on lhs and rhs.
char& operator[](int32_t i);
public:
int32_t m_capacity;
int32_t m_length;
protected:
char *m_buf;
public:
char *m_label;
bool m_usingStack;
int16_t m_encoding; // output charset
// . a special flag used by PageParser.cpp
// . if this is true it PageParser shows the page in its html form,
// otherwise, if false, it converts the "<" to < etc. so we see the html
// source view.
// . only Words.cpp looks at this flag
char m_renderHtml;
};
#define TOKENPASTE(x, y) x ## y
#define TOKENPASTE2(x, y) TOKENPASTE(x, y)
#define StackBuf(name) char TOKENPASTE2(tmpsafebuf, __LINE__)[1024]; \
SafeBuf name(TOKENPASTE2(tmpsafebuf, __LINE__), 1024)
#endif
|
apache-2.0
|
piibl/elearning-parent
|
elearning-core/src/main/java/fr/iut/csid/empower/elearning/core/service/impl/CourseSessionServiceImpl.java
|
3566
|
package fr.iut.csid.empower.elearning.core.service.impl;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import org.springframework.data.jpa.repository.JpaRepository;
import fr.iut.csid.empower.elearning.core.domain.course.Course;
import fr.iut.csid.empower.elearning.core.domain.course.CourseTeaching;
import fr.iut.csid.empower.elearning.core.domain.course.session.CourseSession;
import fr.iut.csid.empower.elearning.core.dto.impl.CourseSessionDTO;
import fr.iut.csid.empower.elearning.core.exception.CourseNotExistsException;
import fr.iut.csid.empower.elearning.core.service.CourseSessionService;
import fr.iut.csid.empower.elearning.core.service.NotificationService;
import fr.iut.csid.empower.elearning.core.service.dao.course.CourseDAO;
import fr.iut.csid.empower.elearning.core.service.dao.course.CourseTeachingDAO;
import fr.iut.csid.empower.elearning.core.service.dao.course.session.CourseSessionDAO;
/**
*
*/
@Named
public class CourseSessionServiceImpl extends AbstractCrudService<CourseSession, Long> implements CourseSessionService {
@Inject
private CourseSessionDAO courseSessionDAO;
@Inject
private CourseDAO courseDAO;
@Inject
private CourseTeachingDAO courseTeachingDAO;
@Inject
private NotificationService notificationService;
@Override
public CourseSession createFromDTO(CourseSessionDTO entityDTO) {
Course ownerCourse = courseDAO.findOne(Long.valueOf(entityDTO.getOwnerId()));
CourseSession courseSession = new CourseSession(entityDTO.getLabel(), ownerCourse, courseSessionDAO.countByOwnerCourse(ownerCourse) + 1, null, null,
entityDTO.getSummary());
List<CourseTeaching> courseTeachingList = courseTeachingDAO.findByCourse(ownerCourse);
if (ownerCourse != null) {
courseSessionDAO.save(courseSession);
for(CourseTeaching courseTeaching : courseTeachingList){
notificationService.createNotification("Création de session", courseTeaching.getTeacher(),
"La session " + courseSession.getLabel() + " a été créée pour le cours " + ownerCourse.getLabel() + ".");
}
return courseSession;
// entityDTO.getStartDate(), entityDTO.getEndDate()));
}
return null;
}
@Override
public CourseSession saveFromDTO(CourseSessionDTO entityDTO, Long id) {
CourseSession courseSession = courseSessionDAO.findOne(id);
if (courseSession != null) {
// TODO update autres champs ?
courseSession.setLabel(entityDTO.getLabel());
// courseSession.setStartDate(entityDTO.getStartDate());
// courseSession.setEndDate(entityDTO.getEndDate());
return courseSessionDAO.save(courseSession);
}
// TODO erreur globale
throw new CourseNotExistsException();
}
@Override
protected JpaRepository<CourseSession, Long> getDAO() {
return courseSessionDAO;
}
@Override
public List<CourseSession> findByOwner(Long ownerEntityId) {
Course course = courseDAO.findOne(ownerEntityId);
if (course != null) {
return courseSessionDAO.findByOwnerCourseOrderBySessionRankAsc(course);
}
throw new CourseNotExistsException();
}
@Override
public void delete(CourseSession courseSession) {
super.delete(courseSession);
Course ownerCourse = courseSession.getOwnerCourse();
List<CourseTeaching> courseTeachingList = courseTeachingDAO.findByCourse(ownerCourse);
for(CourseTeaching courseTeaching : courseTeachingList){
notificationService.createNotification("Suppression de session", courseTeaching.getTeacher(),
"La session " + courseSession.getLabel() + " a été supprimée pour le cours " + ownerCourse.getLabel() + ".");
}
}
}
|
apache-2.0
|
slimkit/thinksns-plus
|
app/Models/Role.php
|
3639
|
<?php
declare(strict_types=1);
/*
* +----------------------------------------------------------------------+
* | ThinkSNS Plus |
* +----------------------------------------------------------------------+
* | Copyright (c) 2016-Present ZhiYiChuangXiang Technology Co., Ltd. |
* +----------------------------------------------------------------------+
* | This source file is subject to enterprise private license, that is |
* | bundled with this package in the file LICENSE, and is available |
* | through the world-wide-web at the following url: |
* | https://github.com/slimkit/plus/blob/master/LICENSE |
* +----------------------------------------------------------------------+
* | Author: Slim Kit Group <[email protected]> |
* | Homepage: www.thinksns.com |
* +----------------------------------------------------------------------+
*/
namespace Zhiyi\Plus\Models;
// use Illuminate\Cache\TaggableStore;
// use Illuminate\Support\Facades\Cache;
// use Illuminate\Support\Facades\Config;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* Zhiyi\Plus\Models\Role.
*
* @property int $id
* @property string $name
* @property string|null $display_name
* @property string|null $description
* @property int|null $non_delete
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property-read \Illuminate\Database\Eloquent\Collection|\Zhiyi\Plus\Models\Ability[] $abilities
* @property-read int|null $abilities_count
* @property-read \Illuminate\Database\Eloquent\Collection|\Zhiyi\Plus\Models\User[] $users
* @property-read int|null $users_count
* @method static \Illuminate\Database\Eloquent\Builder|Role newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|Role newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|Role query()
* @method static \Illuminate\Database\Eloquent\Builder|Role whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|Role whereDescription($value)
* @method static \Illuminate\Database\Eloquent\Builder|Role whereDisplayName($value)
* @method static \Illuminate\Database\Eloquent\Builder|Role whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Role whereName($value)
* @method static \Illuminate\Database\Eloquent\Builder|Role whereNonDelete($value)
* @method static \Illuminate\Database\Eloquent\Builder|Role whereUpdatedAt($value)
* @mixin \Eloquent
*/
class Role extends Model
{
use HasFactory;
/**
* Get all abilities of the role.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
* @author Seven Du <[email protected]>
*/
public function abilities()
{
return $this->belongsToMany(Ability::class, 'ability_role', 'role_id', 'ability_id');
}
/**
* Get all users of the role.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
* @author Seven Du <[email protected]>
*/
public function users()
{
return $this->belongsToMany(User::class, 'role_user', 'role_id', 'user_id');
}
/**
* Get or check The role ability.
*
* @param string $ability
* @return false|Ability
* @author Seven Du <[email protected]>
*/
public function ability(string $ability)
{
return $this->abilities->keyBy('name')->get($ability, false);
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Chromista/Ochrophyta/Phaeophyceae/Sphacelariales/Sphacelariaceae/Sphacelaria/Sphacelaria brevicornis/README.md
|
203
|
# Sphacelaria brevicornis Setchell & N.L.Gardner, 1924 SPECIES
#### Status
ACCEPTED
#### According to
World Register of Marine Species
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
fredzannarbor/pagekicker-community
|
conf/jobprofiles/seriesdescriptions/wikitop.html
|
344
|
<p>
This MiniBriefing was autonomously created by a member of the PageKicker robot team in response to a demand cue. We're all about addressing the structural mismatch between the demand for ebooks and the supply. We have objective evidence that there's demand on this topic, so we told one of our robots to go out and build a book on it!<p>
|
apache-2.0
|
sip3io/tapir
|
twig/src/main/java/io/sip3/tapir/twig/mongo/Mongo.java
|
3180
|
/*
* Copyright 2017 SIP3.IO CORP.
*
* 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 io.sip3.tapir.twig.mongo;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import io.sip3.tapir.core.partition.Partition;
import io.sip3.tapir.core.partition.PartitionFactory;
import io.sip3.tapir.twig.mongo.query.Query;
import io.sip3.tapir.twig.util.TimeIntervalIterator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Created by agafox.
*/
@Component("m")
public class Mongo {
private final Partition partition;
private final int batchSize;
private final MongoDatabase db;
@Autowired
public Mongo(@Value("${mongo.partition}") String partition,
@Value("${mongo.batchSize}") int batchSize,
MongoDatabase db) {
this.partition = PartitionFactory.ofPattern(partition);
this.batchSize = batchSize;
this.db = db;
}
public <T> Iterator<T> find(String prefix, Query query, Class<T> clazz) {
return new Iterator<T>() {
private final Iterator<Long> intervals = TimeIntervalIterator.of(query.millis(), partition);
private MongoCursor<T> cursor;
@Override
public boolean hasNext() {
if (cursor != null && cursor.hasNext()) {
return true;
}
while (intervals.hasNext()) {
long millis = intervals.next();
String collection = collection(prefix, partition.define(millis, false));
FindIterable<T> fi = db.getCollection(collection, clazz)
.find(query.filter())
.batchSize(batchSize);
if (query.sort() != null) {
fi.sort(query.sort());
}
cursor = fi.iterator();
if (cursor.hasNext()) {
return true;
}
}
return false;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return cursor.next();
}
};
}
private String collection(String prefix, String suffix) {
return prefix + "_" + suffix;
}
}
|
apache-2.0
|
TranscendComputing/TopStackMetricSearch
|
src/com/transcend/monitor/transform/BaseMonitorUnmarshaller.java
|
2416
|
/**
* Transcend Computing, Inc.
* Confidential and Proprietary
* Copyright (c) Transcend Computing, Inc. 2012
* All Rights Reserved.
*/
package com.transcend.monitor.transform;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import com.google.protobuf.Message;
import com.msi.tough.core.Appctx;
import com.msi.tough.monitor.common.MarshallingUtils;
import com.msi.tough.monitor.common.MonitorConstants;
import com.msi.tough.query.ProtobufUtil;
import com.transcend.monitor.message.MetricAlarmMessage.Dimension;
/**
* @author jgardner
*
*/
public abstract class BaseMonitorUnmarshaller<T extends Message> {
private final static Logger logger = Appctx
.getLogger(BaseMonitorUnmarshaller.class.getName());
/**
* General signature for umarshall.
*
* @param in
* @return built object
* @throws Exception
*/
public abstract T unmarshall(Map<String, String[]> in) throws Exception;
/**
* Convenience method to unmarshall common fields.
*
* @param instance
* @param in
* @throws Exception
*/
public T unmarshall(T instance, Map<String, String[]> in) {
String namespace = MarshallingUtils.unmarshallString(in,
MonitorConstants.NODE_NAMESPACE,
logger);
if ("AWS/EC2".equals(namespace)) {
// Since we are AWS compatible, accept AWS namespace, sub our own.
namespace = "MSI/EC2";
}
instance = ProtobufUtil.setRequiredField(instance, "namespace", namespace);
return instance;
}
/**
* @param mapIn
* @return
*/
Collection<Dimension> unmarshallDimensions(
Map<String, String[]> in)
{
List<Dimension> dims = new ArrayList<Dimension>();
int i = 0;
while (true)
{
i++;
String prefix = "Dimensions.member." + i + ".";
final String n[] = in.get(prefix + MonitorConstants.NODE_NAME);
if (n == null)
{
break;
}
final String v[] = in.get(prefix + MonitorConstants.NODE_VALUE);
Dimension.Builder d = Dimension.newBuilder();
d.setName(n[0]);
d.setValue((v != null ? v[0] : ""));
dims.add(d.build());
}
return dims;
}
}
|
apache-2.0
|
reecedantin/homebridge-openhab
|
node_modules/ws/node_modules/utf-8-validate/build/Makefile
|
12935
|
# We borrow heavily from the kernel build setup, though we are simpler since
# we don't have Kconfig tweaking settings on us.
# The implicit make rules have it looking for RCS files, among other things.
# We instead explicitly write all the rules we care about.
# It's even quicker (saves ~200ms) to pass -r on the command line.
MAKEFLAGS=-r
# The source directory tree.
srcdir := ..
abs_srcdir := $(abspath $(srcdir))
# The name of the builddir.
builddir_name ?= .
# The V=1 flag on command line makes us verbosely print command lines.
ifdef V
quiet=
else
quiet=quiet_
endif
# Specify BUILDTYPE=Release on the command line for a release build.
BUILDTYPE ?= Release
# Directory all our build output goes into.
# Note that this must be two directories beneath src/ for unit tests to pass,
# as they reach into the src/ directory for data with relative paths.
builddir ?= $(builddir_name)/$(BUILDTYPE)
abs_builddir := $(abspath $(builddir))
depsdir := $(builddir)/.deps
# Object output directory.
obj := $(builddir)/obj
abs_obj := $(abspath $(obj))
# We build up a list of every single one of the targets so we can slurp in the
# generated dependency rule Makefiles in one pass.
all_deps :=
CC.target ?= $(CC)
CFLAGS.target ?= $(CFLAGS)
CXX.target ?= $(CXX)
CXXFLAGS.target ?= $(CXXFLAGS)
LINK.target ?= $(LINK)
LDFLAGS.target ?= $(LDFLAGS)
AR.target ?= $(AR)
# C++ apps need to be linked with g++.
LINK ?= $(CXX.target)
# TODO(evan): move all cross-compilation logic to gyp-time so we don't need
# to replicate this environment fallback in make as well.
CC.host ?= gcc
CFLAGS.host ?=
CXX.host ?= g++
CXXFLAGS.host ?=
LINK.host ?= $(CXX.host)
LDFLAGS.host ?=
AR.host ?= ar
# Define a dir function that can handle spaces.
# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
# "leading spaces cannot appear in the text of the first argument as written.
# These characters can be put into the argument value by variable substitution."
empty :=
space := $(empty) $(empty)
# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
replace_spaces = $(subst $(space),?,$1)
unreplace_spaces = $(subst ?,$(space),$1)
dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
# Flags to make gcc output dependency info. Note that you need to be
# careful here to use the flags that ccache and distcc can understand.
# We write to a dep file on the side first and then rename at the end
# so we can't end up with a broken dep file.
depfile = $(depsdir)/$(call replace_spaces,$@).d
DEPFLAGS = -MMD -MF $(depfile).raw
# We have to fixup the deps output in a few ways.
# (1) the file output should mention the proper .o file.
# ccache or distcc lose the path to the target, so we convert a rule of
# the form:
# foobar.o: DEP1 DEP2
# into
# path/to/foobar.o: DEP1 DEP2
# (2) we want missing files not to cause us to fail to build.
# We want to rewrite
# foobar.o: DEP1 DEP2 \
# DEP3
# to
# DEP1:
# DEP2:
# DEP3:
# so if the files are missing, they're just considered phony rules.
# We have to do some pretty insane escaping to get those backslashes
# and dollar signs past make, the shell, and sed at the same time.
# Doesn't work with spaces, but that's fine: .d files have spaces in
# their names replaced with other characters.
define fixup_dep
# The depfile may not exist if the input file didn't have any #includes.
touch $(depfile).raw
# Fixup path as in (1).
sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)
# Add extra rules as in (2).
# We remove slashes and replace spaces with new lines;
# remove blank lines;
# delete the first line and append a colon to the remaining lines.
sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\
grep -v '^$$' |\
sed -e 1d -e 's|$$|:|' \
>> $(depfile)
rm $(depfile).raw
endef
# Command definitions:
# - cmd_foo is the actual command to run;
# - quiet_cmd_foo is the brief-output summary of the command.
quiet_cmd_cc = CC($(TOOLSET)) $@
cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_cxx = CXX($(TOOLSET)) $@
cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_touch = TOUCH $@
cmd_touch = touch $@
quiet_cmd_copy = COPY $@
# send stderr to /dev/null to ignore messages when linking directories.
cmd_copy = rm -rf "$@" && cp -af "$<" "$@"
quiet_cmd_alink = AR($(TOOLSET)) $@
cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
quiet_cmd_alink_thin = AR($(TOOLSET)) $@
cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
# Due to circular dependencies between libraries :(, we wrap the
# special "figure out circular dependencies" flags around the entire
# input list during linking.
quiet_cmd_link = LINK($(TOOLSET)) $@
cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS)
# We support two kinds of shared objects (.so):
# 1) shared_library, which is just bundling together many dependent libraries
# into a link line.
# 2) loadable_module, which is generating a module intended for dlopen().
#
# They differ only slightly:
# In the former case, we want to package all dependent code into the .so.
# In the latter case, we want to package just the API exposed by the
# outermost module.
# This means shared_library uses --whole-archive, while loadable_module doesn't.
# (Note that --whole-archive is incompatible with the --start-group used in
# normal linking.)
# Other shared-object link notes:
# - Set SONAME to the library filename so our binaries don't reference
# the local, absolute paths used on the link command-line.
quiet_cmd_solink = SOLINK($(TOOLSET)) $@
cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS)
quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS)
# Define an escape_quotes function to escape single quotes.
# This allows us to handle quotes properly as long as we always use
# use single quotes and escape_quotes.
escape_quotes = $(subst ','\'',$(1))
# This comment is here just to include a ' to unconfuse syntax highlighting.
# Define an escape_vars function to escape '$' variable syntax.
# This allows us to read/write command lines with shell variables (e.g.
# $LD_LIBRARY_PATH), without triggering make substitution.
escape_vars = $(subst $$,$$$$,$(1))
# Helper that expands to a shell command to echo a string exactly as it is in
# make. This uses printf instead of echo because printf's behaviour with respect
# to escape sequences is more portable than echo's across different shells
# (e.g., dash, bash).
exact_echo = printf '%s\n' '$(call escape_quotes,$(1))'
# Helper to compare the command we're about to run against the command
# we logged the last time we ran the command. Produces an empty
# string (false) when the commands match.
# Tricky point: Make has no string-equality test function.
# The kernel uses the following, but it seems like it would have false
# positives, where one string reordered its arguments.
# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \
# $(filter-out $(cmd_$@), $(cmd_$(1))))
# We instead substitute each for the empty string into the other, and
# say they're equal if both substitutions produce the empty string.
# .d files contain ? instead of spaces, take that into account.
command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\
$(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
# Helper that is non-empty when a prerequisite changes.
# Normally make does this implicitly, but we force rules to always run
# so we can check their command lines.
# $? -- new prerequisites
# $| -- order-only dependencies
prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
# Helper that executes all postbuilds until one fails.
define do_postbuilds
@E=0;\
for p in $(POSTBUILDS); do\
eval $$p;\
E=$$?;\
if [ $$E -ne 0 ]; then\
break;\
fi;\
done;\
if [ $$E -ne 0 ]; then\
rm -rf "$@";\
exit $$E;\
fi
endef
# do_cmd: run a command via the above cmd_foo names, if necessary.
# Should always run for a given target to handle command-line changes.
# Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
# Third argument, if non-zero, makes it do POSTBUILDS processing.
# Note: We intentionally do NOT call dirx for depfile, since it contains ? for
# spaces already and dirx strips the ? characters.
define do_cmd
$(if $(or $(command_changed),$(prereq_changed)),
@$(call exact_echo, $($(quiet)cmd_$(1)))
@mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
$(if $(findstring flock,$(word 1,$(cmd_$1))),
@$(cmd_$(1))
@echo " $(quiet_cmd_$(1)): Finished",
@$(cmd_$(1))
)
@$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
@$(if $(2),$(fixup_dep))
$(if $(and $(3), $(POSTBUILDS)),
$(call do_postbuilds)
)
)
endef
# Declare the "all" target first so it is the default,
# even though we don't have the deps yet.
.PHONY: all
all:
# make looks for ways to re-generate included makefiles, but in our case, we
# don't have a direct way. Explicitly telling make that it has nothing to do
# for them makes it go faster.
%.d: ;
# Use FORCE_DO_CMD to force a target to run. Should be coupled with
# do_cmd.
.PHONY: FORCE_DO_CMD
FORCE_DO_CMD:
TOOLSET := target
# Suffix rules, putting all outputs into $(obj).
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
# Try building from generated source, too.
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
$(findstring $(join ^,$(prefix)),\
$(join ^,validation.target.mk)))),)
include validation.target.mk
endif
quiet_cmd_regen_makefile = ACTION Regenerating $@
cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/usr/local/lib/node_modules/homebridge-openhab/node_modules/ws/node_modules/utf-8-validate/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/usr/local/lib/node_modules/homebridge-openhab/node_modules/ws/node_modules/utf-8-validate/.node-gyp/4.2.1/include/node/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/usr/local/lib/node_modules/homebridge-openhab/node_modules/ws/node_modules/utf-8-validate/.node-gyp/4.2.1" "-Dnode_gyp_dir=/usr/local/lib/node_modules/npm/node_modules/node-gyp" "-Dnode_lib_file=node.lib" "-Dmodule_root_dir=/usr/local/lib/node_modules/homebridge-openhab/node_modules/ws/node_modules/utf-8-validate" binding.gyp
Makefile: $(srcdir)/../../../../../npm/node_modules/node-gyp/addon.gypi $(srcdir)/.node-gyp/4.2.1/include/node/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp
$(call do_cmd,regen_makefile)
# "all" is a concatenation of the "all" targets from all the included
# sub-makefiles. This is just here to clarify.
all:
# Add in dependency-tracking rules. $(all_deps) is the list of every single
# target in our tree. Only consider the ones with .d (dependency) info:
d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
ifneq ($(d_files),)
include $(d_files)
endif
|
apache-2.0
|
gds-operations/puppet-graphite
|
spec/classes/graphite/graphite__user_spec.rb
|
455
|
require 'spec_helper'
describe 'graphite', :type => :class do
let(:facts) { {:osfamily => 'Debian'} }
let(:params) {{
:user => 'graphite',
:group => 'graphite',
:manage_user => true,
}}
it { should contain_user('carbon_cache_user').with_ensure('present').
with_name('graphite').
with_gid('graphite')
}
it { should contain_group('carbon_cache_group').with_ensure('present').
with_name('graphite')
}
end
|
apache-2.0
|
apetrucci/katharsis-framework
|
katharsis-security/src/integrationTest/java/ch/adnovum/jcan/katharsis/mock/repository/ProjectRepository.java
|
1176
|
package ch.adnovum.jcan.katharsis.mock.repository;
import java.util.HashMap;
import java.util.Map;
import javax.enterprise.context.ApplicationScoped;
import ch.adnovum.jcan.katharsis.mock.models.Project;
import ch.adnovum.jcan.katharsis.security.ResourcePermissionInformationImpl;
import io.katharsis.queryspec.QuerySpec;
import io.katharsis.repository.ResourceRepositoryBase;
import io.katharsis.resource.list.DefaultResourceList;
import io.katharsis.resource.list.ResourceList;
@ApplicationScoped
public class ProjectRepository extends ResourceRepositoryBase<Project, Long> {
private static final Map<Long, Project> PROJECTS = new HashMap<>();
public ProjectRepository() {
super(Project.class);
}
@Override
public <S extends Project> S save(S entity) {
PROJECTS.put(entity.getId(), entity);
return entity;
}
@Override
public ResourceList<Project> findAll(QuerySpec querySpec) {
DefaultResourceList<Project> list = querySpec.apply(PROJECTS.values());
list.setMeta(new ResourcePermissionInformationImpl());
return list;
}
@Override
public void delete(Long id) {
PROJECTS.remove(id);
}
public static void clear() {
PROJECTS.clear();
}
}
|
apache-2.0
|
stepanovdg/big-data-plugin
|
api/hdfs/src/main/java/org/pentaho/bigdata/api/hdfs/HadoopFileSystemLocator.java
|
1411
|
/*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2002-2017 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* 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.pentaho.bigdata.api.hdfs;
import org.pentaho.big.data.api.cluster.NamedCluster;
import org.pentaho.big.data.api.initializer.ClusterInitializationException;
import java.net.URI;
/**
* Created by bryan on 5/22/15.
*/
public interface HadoopFileSystemLocator {
@Deprecated
HadoopFileSystem getHadoopFilesystem( NamedCluster namedCluster ) throws ClusterInitializationException;
HadoopFileSystem getHadoopFilesystem( NamedCluster namedCluster, URI uri ) throws ClusterInitializationException;
}
|
apache-2.0
|
akhilesh0707/Android-Image-Cropper
|
cropper/src/main/java/com/theartofdev/edmodo/cropper/CropImageView.java
|
23437
|
/*
* Copyright 2013, Edmodo, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License.
* You may obtain a copy of the License in the LICENSE file, or 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 com.theartofdev.edmodo.cropper;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.edmodo.cropper.R;
import com.theartofdev.edmodo.cropper.cropwindow.CropOverlayView;
import com.theartofdev.edmodo.cropper.cropwindow.edge.Edge;
import com.theartofdev.edmodo.cropper.util.ImageViewUtil;
/**
* Custom view that provides cropping capabilities to an image.
*/
public class CropImageView extends FrameLayout {
//region: Fields and Consts
private static final Rect EMPTY_RECT = new Rect();
// Sets the default image guidelines to show when resizing
public static final int DEFAULT_GUIDELINES = 1;
public static final boolean DEFAULT_FIXED_ASPECT_RATIO = false;
public static final int DEFAULT_ASPECT_RATIO_X = 1;
public static final int DEFAULT_ASPECT_RATIO_Y = 1;
public static final int DEFAULT_SCALE_TYPE_INDEX = 0;
public static final int DEFAULT_CROP_SHAPE_INDEX = 0;
private static final int DEFAULT_IMAGE_RESOURCE = 0;
private static final ImageView.ScaleType[] VALID_SCALE_TYPES = new ImageView.ScaleType[]{ImageView.ScaleType.CENTER_INSIDE, ImageView.ScaleType.FIT_CENTER};
private static final CropShape[] VALID_CROP_SHAPES = new CropShape[]{CropShape.RECTANGLE, CropShape.OVAL};
private static final String DEGREES_ROTATED = "DEGREES_ROTATED";
private ImageView mImageView;
private CropOverlayView mCropOverlayView;
private Bitmap mBitmap;
private int mDegreesRotated = 0;
private int mLayoutWidth;
private int mLayoutHeight;
/**
* Instance variables for customizable attributes
*/
private int mGuidelines = DEFAULT_GUIDELINES;
private boolean mFixAspectRatio = DEFAULT_FIXED_ASPECT_RATIO;
private int mAspectRatioX = DEFAULT_ASPECT_RATIO_X;
private int mAspectRatioY = DEFAULT_ASPECT_RATIO_Y;
private int mImageResource = DEFAULT_IMAGE_RESOURCE;
private ImageView.ScaleType mScaleType = VALID_SCALE_TYPES[DEFAULT_SCALE_TYPE_INDEX];
/**
* The shape of the cropping area - rectangle/circular.
*/
private CropImageView.CropShape mCropShape;
/**
* The URI that the image was loaded from (if loaded from URI)
*/
private Uri mLoadedImageUri;
/**
* The sample size the image was loaded by if was loaded by URI
*/
private int mLoadedSampleSize = 1;
//endregion
public CropImageView(Context context) {
super(context);
init(context);
}
public CropImageView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CropImageView, 0, 0);
try {
mGuidelines = ta.getInteger(R.styleable.CropImageView_guidelines, DEFAULT_GUIDELINES);
mFixAspectRatio = ta.getBoolean(R.styleable.CropImageView_fixAspectRatio, DEFAULT_FIXED_ASPECT_RATIO);
mAspectRatioX = ta.getInteger(R.styleable.CropImageView_aspectRatioX, DEFAULT_ASPECT_RATIO_X);
mAspectRatioY = ta.getInteger(R.styleable.CropImageView_aspectRatioY, DEFAULT_ASPECT_RATIO_Y);
mImageResource = ta.getResourceId(R.styleable.CropImageView_imageResource, DEFAULT_IMAGE_RESOURCE);
mScaleType = VALID_SCALE_TYPES[ta.getInt(R.styleable.CropImageView_scaleType, DEFAULT_SCALE_TYPE_INDEX)];
mCropShape = VALID_CROP_SHAPES[ta.getInt(R.styleable.CropImageView_cropShape, DEFAULT_CROP_SHAPE_INDEX)];
} finally {
ta.recycle();
}
init(context);
}
/**
* Set the scale type of the image in the crop view
*/
public ImageView.ScaleType getScaleType() {
return mScaleType;
}
/**
* Set the scale type of the image in the crop view
*/
public void setScaleType(ImageView.ScaleType scaleType) {
mScaleType = scaleType;
if (mImageView != null)
mImageView.setScaleType(mScaleType);
}
/**
* The shape of the cropping area - rectangle/circular.
*/
public CropImageView.CropShape getCropShape() {
return mCropShape;
}
/**
* The shape of the cropping area - rectangle/circular.
*/
public void setCropShape(CropImageView.CropShape cropShape) {
if (cropShape != mCropShape) {
mCropShape = cropShape;
mCropOverlayView.setCropShape(cropShape);
}
}
/**
* Sets whether the aspect ratio is fixed or not; true fixes the aspect ratio, while
* false allows it to be changed.
*
* @param fixAspectRatio Boolean that signals whether the aspect ratio should be
* maintained.
*/
public void setFixedAspectRatio(boolean fixAspectRatio) {
mCropOverlayView.setFixedAspectRatio(fixAspectRatio);
}
/**
* Sets the guidelines for the CropOverlayView to be either on, off, or to show when
* resizing the application.
*
* @param guidelines Integer that signals whether the guidelines should be on, off, or
* only showing when resizing.
*/
public void setGuidelines(int guidelines) {
mCropOverlayView.setGuidelines(guidelines);
}
/**
* Sets the both the X and Y values of the aspectRatio.
*
* @param aspectRatioX int that specifies the new X value of the aspect ratio
* @param aspectRatioY int that specifies the new Y value of the aspect ratio
*/
public void setAspectRatio(int aspectRatioX, int aspectRatioY) {
mAspectRatioX = aspectRatioX;
mCropOverlayView.setAspectRatioX(mAspectRatioX);
mAspectRatioY = aspectRatioY;
mCropOverlayView.setAspectRatioY(mAspectRatioY);
}
/**
* Returns the integer of the imageResource
*/
public int getImageResource() {
return mImageResource;
}
/**
* Sets a Bitmap as the content of the CropImageView.
*
* @param bitmap the Bitmap to set
*/
public void setImageBitmap(Bitmap bitmap) {
// if we allocated the bitmap, release it as fast as possible
if (mBitmap != null && (mImageResource > 0 || mLoadedImageUri != null)) {
mBitmap.recycle();
}
// clean the loaded image flags for new image
mImageResource = 0;
mLoadedImageUri = null;
mLoadedSampleSize = 1;
mDegreesRotated = 0;
mBitmap = bitmap;
mImageView.setImageBitmap(mBitmap);
if (mCropOverlayView != null) {
mCropOverlayView.resetCropOverlayView();
}
}
/**
* Sets a Bitmap and initializes the image rotation according to the EXIT data.<br>
* <br>
* The EXIF can be retrieved by doing the following:
* <code>ExifInterface exif = new ExifInterface(path);</code>
*
* @param bitmap the original bitmap to set; if null, this
* @param exif the EXIF information about this bitmap; may be null
*/
public void setImageBitmap(Bitmap bitmap, ExifInterface exif) {
if (bitmap != null && exif != null) {
ImageViewUtil.RotateBitmapResult result = ImageViewUtil.rotateBitmapByExif(bitmap, exif);
bitmap = result.bitmap;
mDegreesRotated = result.degrees;
}
setImageBitmap(bitmap);
}
/**
* Sets a Drawable as the content of the CropImageView.
*
* @param resId the drawable resource ID to set
*/
public void setImageResource(int resId) {
if (resId != 0) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId);
setImageBitmap(bitmap);
mImageResource = resId;
}
}
/**
* Sets a bitmap loaded from the given Android URI as the content of the CropImageView.<br>
* Can be used with URI from gallery or camera source.<br>
* Will rotate the image by exif data.<br>
*
* @param uri the URI to load the image from
*/
public void setImageUri(Uri uri) {
if (uri != null) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
double densityAdj = metrics.density > 1 ? 1 / metrics.density : 1;
int width = (int) (metrics.widthPixels * densityAdj);
int height = (int) (metrics.heightPixels * densityAdj);
ImageViewUtil.DecodeBitmapResult decodeResult =
ImageViewUtil.decodeSampledBitmap(getContext(), uri, width, height);
ImageViewUtil.RotateBitmapResult rotateResult =
ImageViewUtil.rotateBitmapByExif(getContext(), decodeResult.bitmap, uri);
setImageBitmap(rotateResult.bitmap);
mLoadedImageUri = uri;
mLoadedSampleSize = decodeResult.sampleSize;
mDegreesRotated = rotateResult.degrees;
}
}
/**
* Gets the crop window's position relative to the source Bitmap (not the image
* displayed in the CropImageView).
*
* @return a RectF instance containing cropped area boundaries of the source Bitmap
*/
public Rect getActualCropRect() {
if (mBitmap != null) {
final Rect displayedImageRect = ImageViewUtil.getBitmapRect(mBitmap, mImageView, mScaleType);
// Get the scale factor between the actual Bitmap dimensions and the displayed dimensions for width.
final float actualImageWidth = mBitmap.getWidth();
final float displayedImageWidth = displayedImageRect.width();
final float scaleFactorWidth = actualImageWidth / displayedImageWidth;
// Get the scale factor between the actual Bitmap dimensions and the displayed dimensions for height.
final float actualImageHeight = mBitmap.getHeight();
final float displayedImageHeight = displayedImageRect.height();
final float scaleFactorHeight = actualImageHeight / displayedImageHeight;
// Get crop window position relative to the displayed image.
final float displayedCropLeft = Edge.LEFT.getCoordinate() - displayedImageRect.left;
final float displayedCropTop = Edge.TOP.getCoordinate() - displayedImageRect.top;
final float displayedCropWidth = Edge.getWidth();
final float displayedCropHeight = Edge.getHeight();
// Scale the crop window position to the actual size of the Bitmap.
float actualCropLeft = displayedCropLeft * scaleFactorWidth;
float actualCropTop = displayedCropTop * scaleFactorHeight;
float actualCropRight = actualCropLeft + displayedCropWidth * scaleFactorWidth;
float actualCropBottom = actualCropTop + displayedCropHeight * scaleFactorHeight;
// Correct for floating point errors. Crop rect boundaries should not exceed the source Bitmap bounds.
actualCropLeft = Math.max(0f, actualCropLeft);
actualCropTop = Math.max(0f, actualCropTop);
actualCropRight = Math.min(mBitmap.getWidth(), actualCropRight);
actualCropBottom = Math.min(mBitmap.getHeight(), actualCropBottom);
return new Rect((int) actualCropLeft, (int) actualCropTop, (int) actualCropRight, (int) actualCropBottom);
} else {
return null;
}
}
/**
* Gets the crop window's position relative to the source Bitmap (not the image
* displayed in the CropImageView) and the original rotation.
*
* @return a RectF instance containing cropped area boundaries of the source Bitmap
*/
@SuppressWarnings("SuspiciousNameCombination")
public Rect getActualCropRectNoRotation() {
if (mBitmap != null) {
Rect rect = getActualCropRect();
int rotateSide = mDegreesRotated / 90;
if (rotateSide == 1) {
rect.set(rect.top, mBitmap.getWidth() - rect.right, rect.bottom, mBitmap.getWidth() - rect.left);
} else if (rotateSide == 2) {
rect.set(mBitmap.getWidth() - rect.right, mBitmap.getHeight() - rect.bottom, mBitmap.getWidth() - rect.left, mBitmap.getHeight() - rect.top);
} else if (rotateSide == 3) {
rect.set(mBitmap.getHeight() - rect.bottom, rect.left, mBitmap.getHeight() - rect.top, rect.right);
}
rect.set(rect.left * mLoadedSampleSize, rect.top * mLoadedSampleSize, rect.right * mLoadedSampleSize, rect.bottom * mLoadedSampleSize);
return rect;
} else {
return null;
}
}
/**
* Rotates image by the specified number of degrees clockwise. Cycles from 0 to 360
* degrees.
*
* @param degrees Integer specifying the number of degrees to rotate.
*/
public void rotateImage(int degrees) {
if (mBitmap != null) {
Matrix matrix = new Matrix();
matrix.postRotate(degrees);
Bitmap bitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), matrix, true);
setImageBitmap(bitmap);
mDegreesRotated += degrees;
mDegreesRotated = mDegreesRotated % 360;
}
}
/**
* Gets the cropped image based on the current crop window.
*
* @return a new Bitmap representing the cropped image
*/
public Bitmap getCroppedImage() {
return getCroppedImage(0, 0);
}
/**
* Gets the cropped image based on the current crop window.<br>
* If image loaded from URI will use sample size to fir the requested width and height.
*
* @return a new Bitmap representing the cropped image
*/
public Bitmap getCroppedImage(int reqWidth, int reqHeight) {
if (mBitmap != null) {
if (mLoadedImageUri != null && mLoadedSampleSize > 1) {
Rect rect = getActualCropRectNoRotation();
reqWidth = reqWidth > 0 ? reqWidth : rect.width();
reqHeight = reqHeight > 0 ? reqHeight : rect.height();
ImageViewUtil.DecodeBitmapResult result =
ImageViewUtil.decodeSampledBitmapRegion(getContext(), mLoadedImageUri, rect, reqWidth, reqHeight);
Bitmap bitmap = result.bitmap;
if (mDegreesRotated > 0) {
bitmap = ImageViewUtil.rotateBitmap(bitmap, mDegreesRotated);
}
return bitmap;
} else {
Rect rect = getActualCropRect();
return Bitmap.createBitmap(mBitmap, rect.left, rect.top, rect.width(), rect.height());
}
} else {
return null;
}
}
/**
* Gets the cropped circle image based on the current crop selection.
*
* @return a new Circular Bitmap representing the cropped image
*/
public Bitmap getCroppedOvalImage() {
if (mBitmap != null) {
Bitmap cropped = getCroppedImage();
int width = cropped.getWidth();
int height = cropped.getHeight();
Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
RectF rect = new RectF(0, 0, width, height);
canvas.drawOval(rect, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(cropped, 0, 0, paint);
return output;
} else {
return null;
}
}
//region: Private methods
@Override
public Parcelable onSaveInstanceState() {
final Bundle bundle = new Bundle();
bundle.putParcelable("instanceState", super.onSaveInstanceState());
bundle.putInt(DEGREES_ROTATED, mDegreesRotated);
return bundle;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
final Bundle bundle = (Bundle) state;
if (mBitmap != null) {
// Fixes the rotation of the image when orientation changes.
mDegreesRotated = bundle.getInt(DEGREES_ROTATED);
int tempDegrees = mDegreesRotated;
rotateImage(mDegreesRotated);
mDegreesRotated = tempDegrees;
}
super.onRestoreInstanceState(bundle.getParcelable("instanceState"));
} else {
super.onRestoreInstanceState(state);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (mBitmap != null) {
final Rect bitmapRect = ImageViewUtil.getBitmapRect(mBitmap, this, mScaleType);
mCropOverlayView.setBitmapRect(bitmapRect);
} else {
mCropOverlayView.setBitmapRect(EMPTY_RECT);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (mBitmap != null) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// Bypasses a baffling bug when used within a ScrollView, where
// heightSize is set to 0.
if (heightSize == 0) {
heightSize = mBitmap.getHeight();
}
int desiredWidth;
int desiredHeight;
double viewToBitmapWidthRatio = Double.POSITIVE_INFINITY;
double viewToBitmapHeightRatio = Double.POSITIVE_INFINITY;
// Checks if either width or height needs to be fixed
if (widthSize < mBitmap.getWidth()) {
viewToBitmapWidthRatio = (double) widthSize / (double) mBitmap.getWidth();
}
if (heightSize < mBitmap.getHeight()) {
viewToBitmapHeightRatio = (double) heightSize / (double) mBitmap.getHeight();
}
// If either needs to be fixed, choose smallest ratio and calculate
// from there
if (viewToBitmapWidthRatio != Double.POSITIVE_INFINITY || viewToBitmapHeightRatio != Double.POSITIVE_INFINITY) {
if (viewToBitmapWidthRatio <= viewToBitmapHeightRatio) {
desiredWidth = widthSize;
desiredHeight = (int) (mBitmap.getHeight() * viewToBitmapWidthRatio);
} else {
desiredHeight = heightSize;
desiredWidth = (int) (mBitmap.getWidth() * viewToBitmapHeightRatio);
}
}
// Otherwise, the picture is within frame layout bounds. Desired
// width is
// simply picture size
else {
desiredWidth = mBitmap.getWidth();
desiredHeight = mBitmap.getHeight();
}
int width = getOnMeasureSpec(widthMode, widthSize, desiredWidth);
int height = getOnMeasureSpec(heightMode, heightSize, desiredHeight);
mLayoutWidth = width;
mLayoutHeight = height;
final Rect bitmapRect = ImageViewUtil.getBitmapRect(mBitmap.getWidth(),
mBitmap.getHeight(),
mLayoutWidth,
mLayoutHeight,
mScaleType);
mCropOverlayView.setBitmapRect(bitmapRect);
// MUST CALL THIS
setMeasuredDimension(mLayoutWidth, mLayoutHeight);
} else {
mCropOverlayView.setBitmapRect(EMPTY_RECT);
setMeasuredDimension(widthSize, heightSize);
}
}
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
if (mLayoutWidth > 0 && mLayoutHeight > 0) {
// Gets original parameters, and creates the new parameters
final ViewGroup.LayoutParams origparams = this.getLayoutParams();
origparams.width = mLayoutWidth;
origparams.height = mLayoutHeight;
setLayoutParams(origparams);
}
}
private void init(Context context) {
final LayoutInflater inflater = LayoutInflater.from(context);
final View v = inflater.inflate(R.layout.crop_image_view, this, true);
mImageView = (ImageView) v.findViewById(R.id.ImageView_image);
mImageView.setScaleType(mScaleType);
setImageResource(mImageResource);
mCropOverlayView = (CropOverlayView) v.findViewById(R.id.CropOverlayView);
mCropOverlayView.setInitialAttributeValues(mGuidelines, mFixAspectRatio, mAspectRatioX, mAspectRatioY);
mCropOverlayView.setCropShape(mCropShape);
}
/**
* Determines the specs for the onMeasure function. Calculates the width or height
* depending on the mode.
*
* @param measureSpecMode The mode of the measured width or height.
* @param measureSpecSize The size of the measured width or height.
* @param desiredSize The desired size of the measured width or height.
* @return The final size of the width or height.
*/
private static int getOnMeasureSpec(int measureSpecMode, int measureSpecSize, int desiredSize) {
// Measure Width
int spec;
if (measureSpecMode == MeasureSpec.EXACTLY) {
// Must be this size
spec = measureSpecSize;
} else if (measureSpecMode == MeasureSpec.AT_MOST) {
// Can't be bigger than...; match_parent value
spec = Math.min(desiredSize, measureSpecSize);
} else {
// Be whatever you want; wrap_content
spec = desiredSize;
}
return spec;
}
//endregion
//region: Inner class: CropShape
/**
* The possible cropping area shape
*/
public static enum CropShape {
RECTANGLE,
OVAL
}
//endregion
}
|
apache-2.0
|
relution-io/relution-sdk
|
lib/model/ModelContainer.d.ts
|
4822
|
/// <reference types="lodash" />
/**
* @module model
*/
/** */
import * as _ from 'lodash';
/**
* custom Array type supporting an index lookup.
*
* Beware, the implementation does not support modifications to the data contained.
*/
export interface ArrayLookup<T> extends Array<T> {
/**
* elements keyed by lookup property.
*/
index: _.Dictionary<T>;
/**
* whether an element of key exists.
*
* @param key to check.
* @return {boolean} existance indication.
*
* @see get
*/
has(key: string): boolean;
/**
* accesses an element by key.
*
* Use this method in case it is known that the key is valid.
* An assertion will fire if it is not.
*
* @param key lookup property value.
* @return {T} element of key.
*
* @see has
*/
get(key: string): T;
}
/**
* mirrors ModelContainer of Relution server.
*/
export declare class ModelContainer {
static factory: ModelFactory;
readonly factory: ModelFactory;
uuid: string;
version: number;
bundle: string;
application: string;
aclEntries: string[];
effectivePermissions: string;
createdUser: string;
createdDate: Date;
modifiedUser: string;
modifiedDate: Date;
name: string;
description: string;
models: ArrayLookup<MetaModel>;
constructor(other?: ModelContainer);
fromJSON(json: ModelContainer): this;
}
/**
* mirrors MetaModel of Relution server.
*/
export declare class MetaModel {
static factory: ModelFactory;
readonly factory: ModelFactory;
uuid: string;
version: number;
bundle: string;
aclEntries: string[];
effectivePermissions: string;
containerUuid: string;
name: string;
label: string;
description: string;
parents: string[];
abstrakt: boolean;
icon: any;
fieldDefinitions: ArrayLookup<FieldDefinition>;
propertyMap: any;
constructor(other?: MetaModel);
fromJSON(json: MetaModel): this;
}
/**
* mirrors FieldDefinition of Relution server.
*/
export declare class FieldDefinition {
static factory: ModelFactory;
readonly factory: ModelFactory;
name: string;
label: string;
description: string;
group: string;
tooltip: string;
dataType: string;
defaultValue: string;
enumDefinition: EnumDefinition;
keyField: boolean;
index: boolean;
mandatory: boolean;
minSize: number;
maxSize: number;
regexp: string;
propertyMap: any;
readonly dataTypeNormalized: string;
constructor(other?: FieldDefinition);
fromJSON(json: FieldDefinition): this;
}
/**
* mirrors EnumDefinition of Relution server.
*/
export declare class EnumDefinition {
static factory: ModelFactory;
readonly factory: ModelFactory;
items: ArrayLookup<Item>;
enumerable: string;
strict: boolean;
constructor(other?: EnumDefinition);
fromJSON(json: EnumDefinition): this;
}
/**
* represents a predefined choice of an EnumDefinition.
*/
export interface Item {
value: number | string;
label: string;
url?: string;
}
/**
* constructors of model types must adhere the following interface.
*/
export interface ModelFactoryCtor<T> {
/**
* new-able from JSON literal data.
*
* @param json literal data.
*/
new (other?: T): T;
/**
* static association to factory.
*/
factory: ModelFactory;
}
/**
* construction from JSON literal data.
*
* @example Use the following for creation of a subclasses hierarchy:
* export class SomeModelContainer extends ModelContainer {
* public static factory: SomeModelFactory;
* }
* export class SomeMetaModel extends MetaModel {
* public static factory: SomeModelFactory;
* }
* export class SomeFieldDefinition extends FieldDefinition {
* public static factory: SomeModelFactory;
* }
* export class SomeEnumDefinition extends EnumDefinition {
* public static factory: SomeModelFactory;
* }
* export class SomeModelFactory extends ModelFactory {
* public static instance = new SomeModelFactory(SomeModelContainer, SomeMetaModel,
* SomeFieldDefinition, SomeEnumDefinition);
* }
*/
export declare class ModelFactory {
ModelContainer: ModelFactoryCtor<ModelContainer>;
MetaModel: ModelFactoryCtor<MetaModel>;
FieldDefinition: ModelFactoryCtor<FieldDefinition>;
EnumDefinition: ModelFactoryCtor<EnumDefinition>;
static instance: ModelFactory;
constructor(ModelContainer: ModelFactoryCtor<ModelContainer>, MetaModel: ModelFactoryCtor<MetaModel>, FieldDefinition: ModelFactoryCtor<FieldDefinition>, EnumDefinition: ModelFactoryCtor<EnumDefinition>);
static factoryOf<T>(obj: T): ModelFactory;
fromJSON(json: string): ModelContainer;
fromJSON(json: any): ModelContainer;
}
|
apache-2.0
|
googleinterns/debaised-analysis
|
date_detection/test_all.sh
|
1554
|
# Copyright 2020 Google LLC
# 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
# https://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.
#!/bin/bash
#
# Runs all the tests & stores the results in the array - list_logs
# Displays all the results at the end
# Whenever a new test_file.py is added it should be added here
# function to show errors
err() {
echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')]: $*" >&2
}
# empty array initialized
list_logs=()
if ! python3 test_date_detection.py;
then
# if this test fails echos the error and also stores in an array
err "test_date_detection failed"
list_logs+=("test_date_detection failed")
else
# if this does not fails then just stores in the array
list_logs+=("test_date_detection passed")
fi
if ! python3 util/test_min_max_date.py;
then
err "util/test_min_max_date failed"
list_logs+=("util/test_min_max_date failed")
else
list_logs+=("util/test_min_max_date passed")
fi
echo 'All tests completed '
echo 'Results -'
list_logs_length=${#list_logs[@]}
# Displaying all the results at the end
for ((i=0;i<list_logs_length;i++)); do
echo "${list_logs[i]}"
done
|
apache-2.0
|
j-coll/opencga
|
opencga-catalog/src/main/java/org/opencb/opencga/catalog/utils/UuidUtils.java
|
3545
|
/*
* Copyright 2015-2020 OpenCB
*
* 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.opencb.opencga.catalog.utils;
import java.nio.BufferUnderflowException;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UuidUtils {
// OpenCGA uuid pattern: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
// -------- ----
// time low installation
// ---- ------------
// time mid random
// ----
// version (1 hex digit) + internal version (1 hex digit) + entity (2 hex digit)
public static final Pattern UUID_PATTERN = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-00[0-9a-f]{2}-[0-9a-f]{4}-[0-9a-f]{12}");
public enum Entity {
AUDIT(0),
PROJECT(1),
STUDY(2),
FILE(3),
SAMPLE(4),
COHORT(5),
INDIVIDUAL(6),
FAMILY(7),
JOB(8),
CLINICAL(9),
PANEL(10),
INTERPRETATION(11);
private final int mask;
Entity(int mask) {
this.mask = mask;
}
public int getMask() {
return mask;
}
}
public static String generateOpenCgaUuid(Entity entity) {
return generateOpenCgaUuid(entity, new Date());
}
public static String generateOpenCgaUuid(Entity entity, Date date) {
long mostSignificantBits = getMostSignificantBits(date, entity);
long leastSignificantBits = getLeastSignificantBits();
String s = new UUID(mostSignificantBits, leastSignificantBits).toString();
isOpenCgaUuid(s);
return new UUID(mostSignificantBits, leastSignificantBits).toString();
}
public static boolean isOpenCgaUuid(String token) {
if (token.length() == 36) {
try {
Matcher matcher = UUID_PATTERN.matcher(token);
return matcher.find();
} catch (BufferUnderflowException e) {
return false;
}
}
return false;
}
private static long getMostSignificantBits(Date date, Entity entity) {
long time = date.getTime();
long timeLow = time & 0xffffffffL;
long timeMid = (time >>> 32) & 0xffffL;
// long timeHigh = (time >>> 48) & 0xffffL;
long uuidVersion = /*0xf &*/ 0;
long internalVersion = /*0xf &*/ 0;
long entityBin = 0xffL & (long)entity.getMask();
return (timeLow << 32) | (timeMid << 16) | (uuidVersion << 12) | (internalVersion << 8) | entityBin;
}
private static long getLeastSignificantBits() {
long installation = /*0xffL &*/ 0x1L;
// 12 hex digits random
Random rand = new Random();
long randomNumber = 0xffffffffffffL & rand.nextLong();
return (installation << 48) | randomNumber;
}
}
|
apache-2.0
|
Esri/arcobjects-sdk-community-samples
|
Net/Raster/GetSetKeyProperty/VBNet/Properties/AssemblyInfo.vb
|
2002
|
'Copyright 2019 Esri
'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.
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
<Assembly: AssemblyTitle("GetSetKeyProperty")>
<Assembly: AssemblyDescription("Sample to get and set if needed key properties on a mosaic dataset.")>
<Assembly: AssemblyConfiguration("")>
<Assembly: AssemblyCompany("ESRI")>
<Assembly: AssemblyProduct("GetSetKeyProperty")>
<Assembly: AssemblyCopyright("")>
<Assembly: AssemblyTrademark("")>
<Assembly: AssemblyCulture("")>
' Setting ComVisible to false makes the types in this assembly not visible
' to COM components. If you need to access a type in this assembly from
' COM, set the ComVisible attribute to true on that type.
<Assembly: ComVisible(False)>
' The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("040af61e-e210-4f29-afa8-e80909ac3e35")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' [assembly: AssemblyVersion("1.0.*")]
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
apache-2.0
|
prajyotpro/phpmvc
|
app/models/Location.php
|
178
|
<?php
/**
*
*/
class LocationModel
{
private $state;
public function setState($state) {
$this->state = $state;
}
public function getState() {
return $this->state;
}
}
|
apache-2.0
|
apixandru/intellij-community
|
java/java-impl/src/com/intellij/lang/java/JavaDocumentationProvider.java
|
34288
|
// Copyright 2000-2017 JetBrains s.r.o.
// Use of this source code is governed by the Apache 2.0 license that can be
// found in the LICENSE file.
package com.intellij.lang.java;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.completion.CompletionMemory;
import com.intellij.codeInsight.documentation.DocumentationManagerProtocol;
import com.intellij.codeInsight.documentation.PlatformDocumentationUtil;
import com.intellij.codeInsight.editorActions.CodeDocumentationUtil;
import com.intellij.codeInsight.javadoc.JavaDocExternalFilter;
import com.intellij.codeInsight.javadoc.JavaDocInfoGenerator;
import com.intellij.codeInsight.javadoc.JavaDocInfoGeneratorFactory;
import com.intellij.codeInsight.javadoc.JavaDocUtil;
import com.intellij.lang.CodeDocumentationAwareCommenter;
import com.intellij.lang.LangBundle;
import com.intellij.lang.LanguageCommenters;
import com.intellij.lang.documentation.CodeDocumentationProvider;
import com.intellij.lang.documentation.CompositeDocumentationProvider;
import com.intellij.lang.documentation.DocumentationProviderEx;
import com.intellij.lang.documentation.ExternalDocumentationProvider;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileSystem;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.beanProperties.BeanPropertyElement;
import com.intellij.psi.impl.source.javadoc.PsiDocParamRef;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.psi.util.PsiFormatUtil;
import com.intellij.psi.util.PsiFormatUtilBase;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.SmartList;
import com.intellij.util.Url;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.builtInWebServer.BuiltInWebBrowserUrlProviderKt;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author Maxim.Mossienko
*/
public class JavaDocumentationProvider extends DocumentationProviderEx implements CodeDocumentationProvider, ExternalDocumentationProvider {
private static final Logger LOG = Logger.getInstance(JavaDocumentationProvider.class);
private static final String LINE_SEPARATOR = "\n";
private static final String PARAM_TAG = "@param";
private static final String RETURN_TAG = "@return";
private static final String THROWS_TAG = "@throws";
public static final String HTML_EXTENSION = ".html";
public static final String PACKAGE_SUMMARY_FILE = "package-summary.html";
@Override
public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) {
if (element instanceof PsiClass) {
return generateClassInfo((PsiClass)element);
}
else if (element instanceof PsiMethod) {
return generateMethodInfo((PsiMethod)element, calcSubstitutor(originalElement));
}
else if (element instanceof PsiField) {
return generateFieldInfo((PsiField)element, calcSubstitutor(originalElement));
}
else if (element instanceof PsiVariable) {
return generateVariableInfo((PsiVariable)element);
}
else if (element instanceof PsiPackage) {
return generatePackageInfo((PsiPackage)element);
}
else if (element instanceof BeanPropertyElement) {
return generateMethodInfo(((BeanPropertyElement)element).getMethod(), PsiSubstitutor.EMPTY);
}
else if (element instanceof PsiJavaModule) {
return generateModuleInfo((PsiJavaModule)element);
}
return null;
}
private static PsiSubstitutor calcSubstitutor(PsiElement originalElement) {
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
if (originalElement instanceof PsiReferenceExpression) {
LOG.assertTrue(originalElement.isValid());
substitutor = ((PsiReferenceExpression)originalElement).advancedResolve(true).getSubstitutor();
}
return substitutor;
}
@Override
public List<String> getUrlFor(final PsiElement element, final PsiElement originalElement) {
return getExternalJavaDocUrl(element);
}
private static void newLine(StringBuilder buffer) {
// Don't know why space has to be added after newline for good text alignment...
buffer.append("\n ");
}
private static void generateInitializer(StringBuilder buffer, PsiVariable variable) {
PsiExpression initializer = variable.getInitializer();
if (initializer != null) {
JavaDocInfoGenerator.appendExpressionValue(buffer, initializer, " = ");
PsiExpression constantInitializer = JavaDocInfoGenerator.calcInitializerExpression(variable);
if (constantInitializer != null) {
buffer.append("\n");
JavaDocInfoGenerator.appendExpressionValue(buffer, constantInitializer, CodeInsightBundle.message("javadoc.resolved.value"));
}
}
}
private static void generateModifiers(StringBuilder buffer, PsiModifierListOwner element) {
String modifiers = PsiFormatUtil.formatModifiers(element, PsiFormatUtilBase.JAVADOC_MODIFIERS_ONLY);
if (modifiers.length() > 0) {
buffer.append(modifiers);
buffer.append(" ");
}
}
private static String generatePackageInfo(PsiPackage aPackage) {
return aPackage.getQualifiedName();
}
private static void generateOrderEntryAndPackageInfo(StringBuilder buffer, @NotNull PsiElement element) {
PsiFile file = element.getContainingFile();
if (file != null) {
generateOrderEntryInfo(buffer, file.getVirtualFile(), element.getProject());
}
if (file instanceof PsiJavaFile) {
String packageName = ((PsiJavaFile)file).getPackageName();
if (packageName.length() > 0) {
buffer.append(packageName);
newLine(buffer);
}
}
}
private static void generateOrderEntryInfo(StringBuilder buffer, VirtualFile file, Project project) {
if (file != null) {
ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex();
if (index.isInLibrarySource(file) || index.isInLibraryClasses(file)) {
index.getOrderEntriesForFile(file).stream()
.filter(LibraryOrSdkOrderEntry.class::isInstance).findFirst()
.ifPresent(entry -> buffer.append('[').append(StringUtil.escapeXml(entry.getPresentableName())).append("] "));
}
else {
Module module = index.getModuleForFile(file);
if (module != null) {
buffer.append('[').append(module.getName()).append("] ");
}
}
}
}
@SuppressWarnings({"HardCodedStringLiteral"})
public static String generateClassInfo(PsiClass aClass) {
StringBuilder buffer = new StringBuilder();
if (aClass instanceof PsiAnonymousClass) return LangBundle.message("java.terms.anonymous.class");
generateOrderEntryAndPackageInfo(buffer, aClass);
generateModifiers(buffer, aClass);
final String classString = aClass.isAnnotationType() ? "java.terms.annotation.interface"
: aClass.isInterface()
? "java.terms.interface"
: aClass instanceof PsiTypeParameter
? "java.terms.type.parameter"
: aClass.isEnum() ? "java.terms.enum" : "java.terms.class";
buffer.append(LangBundle.message(classString)).append(" ");
buffer.append(JavaDocUtil.getShortestClassName(aClass, aClass));
generateTypeParameters(aClass, buffer);
if (!aClass.isEnum() && !aClass.isAnnotationType()) {
PsiReferenceList extendsList = aClass.getExtendsList();
writeExtends(aClass, buffer, extendsList == null ? PsiClassType.EMPTY_ARRAY : extendsList.getReferencedTypes());
}
writeImplements(aClass, buffer, aClass.getImplementsListTypes());
return buffer.toString();
}
public static void writeImplements(PsiClass aClass, StringBuilder buffer, PsiClassType[] refs) {
if (refs.length > 0) {
newLine(buffer);
buffer.append("implements ");
writeTypeRefs(aClass, buffer, refs);
}
}
public static void writeExtends(PsiClass aClass, StringBuilder buffer, PsiClassType[] refs) {
if (refs.length > 0 || !aClass.isInterface() && !CommonClassNames.JAVA_LANG_OBJECT.equals(aClass.getQualifiedName())) {
buffer.append(" extends ");
if (refs.length == 0) {
buffer.append("Object");
}
else {
writeTypeRefs(aClass, buffer, refs);
}
}
}
private static void writeTypeRefs(PsiClass aClass, StringBuilder buffer, PsiClassType[] refs) {
for (int i = 0; i < refs.length; i++) {
JavaDocInfoGenerator.generateType(buffer, refs[i], aClass, false, true);
if (i < refs.length - 1) {
buffer.append(", ");
}
}
}
public static void generateTypeParameters(PsiTypeParameterListOwner typeParameterOwner, StringBuilder buffer) {
if (typeParameterOwner.hasTypeParameters()) {
PsiTypeParameter[] params = typeParameterOwner.getTypeParameters();
buffer.append("<");
for (int i = 0; i < params.length; i++) {
PsiTypeParameter p = params[i];
buffer.append(p.getName());
PsiClassType[] refs = p.getExtendsList().getReferencedTypes();
if (refs.length > 0) {
buffer.append(" extends ");
for (int j = 0; j < refs.length; j++) {
JavaDocInfoGenerator.generateType(buffer, refs[j], typeParameterOwner, false, true);
if (j < refs.length - 1) {
buffer.append(" & ");
}
}
}
if (i < params.length - 1) {
buffer.append(", ");
}
}
buffer.append(">");
}
}
@SuppressWarnings({"HardCodedStringLiteral"})
public static String generateMethodInfo(PsiMethod method, PsiSubstitutor substitutor) {
StringBuilder buffer = new StringBuilder();
PsiClass parentClass = method.getContainingClass();
if (parentClass != null && !(parentClass instanceof PsiAnonymousClass)) {
if (method.isConstructor()) {
generateOrderEntryAndPackageInfo(buffer, parentClass);
}
buffer.append(JavaDocUtil.getShortestClassName(parentClass, method));
newLine(buffer);
}
generateModifiers(buffer, method);
generateTypeParameters(method, buffer);
if (method.getReturnType() != null) {
JavaDocInfoGenerator.generateType(buffer, substitutor.substitute(method.getReturnType()), method, false, true);
buffer.append(" ");
}
buffer.append(method.getName());
buffer.append("(");
PsiParameter[] params = method.getParameterList().getParameters();
for (int i = 0; i < params.length; i++) {
PsiParameter param = params[i];
JavaDocInfoGenerator.generateType(buffer, substitutor.substitute(param.getType()), method, false, true);
buffer.append(" ");
if (param.getName() != null) {
buffer.append(param.getName());
}
if (i < params.length - 1) {
buffer.append(", ");
}
}
buffer.append(")");
PsiClassType[] refs = method.getThrowsList().getReferencedTypes();
if (refs.length > 0) {
newLine(buffer);
buffer.append(" throws ");
for (int i = 0; i < refs.length; i++) {
PsiClass throwsClass = refs[i].resolve();
if (throwsClass != null) {
buffer.append(JavaDocUtil.getShortestClassName(throwsClass, method));
}
else {
buffer.append(refs[i].getPresentableText());
}
if (i < refs.length - 1) {
buffer.append(", ");
}
}
}
return buffer.toString();
}
private static String generateFieldInfo(PsiField field, PsiSubstitutor substitutor) {
StringBuilder buffer = new StringBuilder();
PsiClass parentClass = field.getContainingClass();
if (parentClass != null && !(parentClass instanceof PsiAnonymousClass)) {
buffer.append(JavaDocUtil.getShortestClassName(parentClass, field));
newLine(buffer);
}
generateModifiers(buffer, field);
JavaDocInfoGenerator.generateType(buffer, substitutor.substitute(field.getType()), field, false, true);
buffer.append(" ");
buffer.append(field.getName());
generateInitializer(buffer, field);
JavaDocInfoGenerator.enumConstantOrdinal(buffer, field, parentClass, "\n");
return buffer.toString();
}
private static String generateVariableInfo(PsiVariable variable) {
StringBuilder buffer = new StringBuilder();
generateModifiers(buffer, variable);
JavaDocInfoGenerator.generateType(buffer, variable.getType(), variable, false, true);
buffer.append(" ");
buffer.append(variable.getName());
generateInitializer(buffer, variable);
return buffer.toString();
}
private static String generateModuleInfo(PsiJavaModule module) {
StringBuilder sb = new StringBuilder();
VirtualFile file = PsiImplUtil.getModuleVirtualFile(module);
generateOrderEntryInfo(sb, file, module.getProject());
sb.append(LangBundle.message("java.terms.module")).append(' ').append(module.getName());
return sb.toString();
}
@Override
public PsiComment findExistingDocComment(final PsiComment comment) {
if (comment instanceof PsiDocComment) {
final PsiJavaDocumentedElement owner = ((PsiDocComment)comment).getOwner();
if (owner != null) {
return owner.getDocComment();
}
}
return null;
}
@Nullable
@Override
public Pair<PsiElement, PsiComment> parseContext(@NotNull PsiElement startPoint) {
PsiElement docCommentOwner = PsiTreeUtil.findFirstParent(startPoint, e -> {
if (e instanceof PsiDocCommentOwner && !(e instanceof PsiTypeParameter) && !(e instanceof PsiAnonymousClass)) {
return true;
}
return false;
});
if (docCommentOwner == null) return null;
PsiDocComment comment = ((PsiDocCommentOwner)docCommentOwner).getDocComment();
if (docCommentOwner instanceof PsiField) {
docCommentOwner = ((PsiField)docCommentOwner).getModifierList();
}
return Pair.create(docCommentOwner, comment);
}
@Override
public String generateDocumentationContentStub(PsiComment _comment) {
final PsiJavaDocumentedElement commentOwner = ((PsiDocComment)_comment).getOwner();
final Project project = _comment.getProject();
final StringBuilder builder = new StringBuilder();
final CodeDocumentationAwareCommenter commenter =
(CodeDocumentationAwareCommenter)LanguageCommenters.INSTANCE.forLanguage(_comment.getLanguage());
if (commentOwner instanceof PsiMethod) {
PsiMethod psiMethod = (PsiMethod)commentOwner;
generateParametersTakingDocFromSuperMethods(project, builder, commenter, psiMethod);
final PsiTypeParameterList typeParameterList = psiMethod.getTypeParameterList();
if (typeParameterList != null) {
createTypeParamsListComment(builder, project, commenter, typeParameterList);
}
if (psiMethod.getReturnType() != null && !PsiType.VOID.equals(psiMethod.getReturnType())) {
builder.append(CodeDocumentationUtil.createDocCommentLine(RETURN_TAG, _comment.getContainingFile(), commenter));
builder.append(LINE_SEPARATOR);
}
final PsiJavaCodeReferenceElement[] references = psiMethod.getThrowsList().getReferenceElements();
for (PsiJavaCodeReferenceElement reference : references) {
builder.append(CodeDocumentationUtil.createDocCommentLine(THROWS_TAG, _comment.getContainingFile(), commenter));
builder.append(reference.getText());
builder.append(LINE_SEPARATOR);
}
}
else if (commentOwner instanceof PsiClass) {
final PsiTypeParameterList typeParameterList = ((PsiClass)commentOwner).getTypeParameterList();
if (typeParameterList != null) {
createTypeParamsListComment(builder, project, commenter, typeParameterList);
}
}
return builder.length() > 0 ? builder.toString() : null;
}
public static void generateParametersTakingDocFromSuperMethods(Project project,
StringBuilder builder,
CodeDocumentationAwareCommenter commenter, PsiMethod psiMethod) {
final PsiParameter[] parameters = psiMethod.getParameterList().getParameters();
final Map<String, String> param2Description = new HashMap<>();
final PsiMethod[] superMethods = psiMethod.findSuperMethods();
for (PsiMethod superMethod : superMethods) {
final PsiDocComment comment = superMethod.getDocComment();
if (comment != null) {
final PsiDocTag[] params = comment.findTagsByName("param");
for (PsiDocTag param : params) {
final PsiElement[] dataElements = param.getDataElements();
if (dataElements != null) {
String paramName = null;
for (PsiElement dataElement : dataElements) {
if (dataElement instanceof PsiDocParamRef) {
//noinspection ConstantConditions
paramName = dataElement.getReference().getCanonicalText();
break;
}
}
if (paramName != null) {
param2Description.put(paramName, param.getText());
}
}
}
}
}
for (PsiParameter parameter : parameters) {
String description = param2Description.get(parameter.getName());
if (description != null) {
builder.append(CodeDocumentationUtil.createDocCommentLine("", psiMethod.getContainingFile(), commenter));
if (description.indexOf('\n') > -1) description = description.substring(0, description.lastIndexOf('\n'));
builder.append(description);
}
else {
builder.append(CodeDocumentationUtil.createDocCommentLine(PARAM_TAG, psiMethod.getContainingFile(), commenter));
builder.append(parameter.getName());
}
builder.append(LINE_SEPARATOR);
}
}
public static void createTypeParamsListComment(final StringBuilder buffer,
final Project project,
final CodeDocumentationAwareCommenter commenter,
final PsiTypeParameterList typeParameterList) {
final PsiTypeParameter[] typeParameters = typeParameterList.getTypeParameters();
for (PsiTypeParameter typeParameter : typeParameters) {
buffer.append(CodeDocumentationUtil.createDocCommentLine(PARAM_TAG, typeParameterList.getContainingFile(), commenter));
buffer.append("<").append(typeParameter.getName()).append(">");
buffer.append(LINE_SEPARATOR);
}
}
@Override
public String generateDoc(PsiElement element, PsiElement originalElement) {
// for new Class(<caret>) or methodCall(<caret>) proceed from method call or new expression
// same for new Cl<caret>ass() or method<caret>Call()
if (element instanceof PsiExpressionList ||
element instanceof PsiReferenceExpression && element.getParent() instanceof PsiMethodCallExpression) {
element = element.getParent();
originalElement = null;
}
if (element instanceof PsiMethodCallExpression) {
PsiMethod method = CompletionMemory.getChosenMethod((PsiMethodCallExpression)element);
if (method == null) return getMethodCandidateInfo((PsiMethodCallExpression)element);
else element = method;
}
// Try hard for documentation of incomplete new Class instantiation
PsiElement elt = originalElement != null && !(originalElement instanceof PsiPackage) ? PsiTreeUtil.prevLeaf(originalElement): element;
if (elt instanceof PsiErrorElement) elt = elt.getPrevSibling();
else if (elt != null && !(elt instanceof PsiNewExpression)) {
elt = elt.getParent();
}
if (elt instanceof PsiNewExpression) {
PsiClass targetClass = null;
if (element instanceof PsiJavaCodeReferenceElement) { // new Class<caret>
PsiElement resolve = ((PsiJavaCodeReferenceElement)element).resolve();
if (resolve instanceof PsiClass) targetClass = (PsiClass)resolve;
} else if (element instanceof PsiClass) { //Class in completion
targetClass = (PsiClass)element;
} else if (element instanceof PsiNewExpression) { // new Class(<caret>)
PsiJavaCodeReferenceElement reference = ((PsiNewExpression)element).getClassReference();
if (reference != null) {
PsiElement resolve = reference.resolve();
if (resolve instanceof PsiClass) targetClass = (PsiClass)resolve;
}
}
if (targetClass != null) {
PsiMethod[] constructors = targetClass.getConstructors();
if (constructors.length > 0) {
if (constructors.length == 1) return generateDoc(constructors[0], originalElement);
final StringBuilder sb = new StringBuilder();
for(PsiMethod constructor:constructors) {
final String str = PsiFormatUtil.formatMethod(constructor, PsiSubstitutor.EMPTY,
PsiFormatUtilBase.SHOW_NAME |
PsiFormatUtilBase.SHOW_TYPE |
PsiFormatUtilBase.SHOW_PARAMETERS,
PsiFormatUtilBase.SHOW_TYPE | PsiFormatUtilBase.SHOW_NAME);
createElementLink(sb, constructor, StringUtil.escapeXml(str));
}
return CodeInsightBundle.message("javadoc.constructor.candidates", targetClass.getName(), sb);
}
}
}
//external documentation finder
return generateExternalJavadoc(element);
}
@Override
public PsiElement getDocumentationElementForLookupItem(final PsiManager psiManager, final Object object, final PsiElement element) {
return null;
}
@Nullable
public static String generateExternalJavadoc(@NotNull final PsiElement element) {
List<String> docURLs = getExternalJavaDocUrl(element);
return generateExternalJavadoc(element, docURLs);
}
@Nullable
public static String generateExternalJavadoc(@NotNull final PsiElement element, @Nullable List<String> docURLs) {
final JavaDocInfoGenerator javaDocInfoGenerator = JavaDocInfoGeneratorFactory.create(element.getProject(), element);
return generateExternalJavadoc(javaDocInfoGenerator, docURLs);
}
@Nullable
public static String generateExternalJavadoc(@NotNull final PsiElement element, @NotNull JavaDocInfoGenerator generator) {
final List<String> docURLs = getExternalJavaDocUrl(element);
return generateExternalJavadoc(generator, docURLs);
}
@Nullable
private static String generateExternalJavadoc(@NotNull JavaDocInfoGenerator generator, @Nullable List<String> docURLs) {
return JavaDocExternalFilter.filterInternalDocInfo(generator.generateDocInfo(docURLs));
}
@Nullable
private static String fetchExternalJavadoc(final PsiElement element, String fromUrl, @NotNull JavaDocExternalFilter filter) {
try {
String externalDoc = filter.getExternalDocInfoForElement(fromUrl, element);
if (!StringUtil.isEmpty(externalDoc)) {
return externalDoc;
}
}
catch (ProcessCanceledException ignored) {}
catch (Exception e) {
LOG.warn(e);
}
return null;
}
private String getMethodCandidateInfo(PsiMethodCallExpression expr) {
final PsiResolveHelper rh = JavaPsiFacade.getInstance(expr.getProject()).getResolveHelper();
final CandidateInfo[] candidates = rh.getReferencedMethodCandidates(expr, true);
final String text = expr.getText();
if (candidates.length > 0) {
if (candidates.length == 1) {
PsiElement element = candidates[0].getElement();
if (element instanceof PsiMethod) return generateDoc(element, null);
}
final StringBuilder sb = new StringBuilder();
for (final CandidateInfo candidate : candidates) {
final PsiElement element = candidate.getElement();
if (!(element instanceof PsiMethod)) {
continue;
}
final String str = PsiFormatUtil.formatMethod((PsiMethod)element, candidate.getSubstitutor(),
PsiFormatUtilBase.SHOW_NAME |
PsiFormatUtilBase.SHOW_TYPE |
PsiFormatUtilBase.SHOW_PARAMETERS,
PsiFormatUtilBase.SHOW_TYPE);
createElementLink(sb, element, StringUtil.escapeXml(str));
}
return CodeInsightBundle.message("javadoc.candidates", text, sb);
}
return CodeInsightBundle.message("javadoc.candidates.not.found", text);
}
private static void createElementLink(StringBuilder sb, PsiElement element, String str) {
sb.append(" <a href=\"" + DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL);
sb.append(JavaDocUtil.getReferenceText(element.getProject(), element));
sb.append("\">");
sb.append(str);
sb.append("</a>");
sb.append("<br>");
}
@Nullable
public static List<String> getExternalJavaDocUrl(final PsiElement element) {
List<String> urls = null;
if (element instanceof PsiClass) {
urls = findUrlForClass((PsiClass)element);
}
else if (element instanceof PsiField) {
PsiField field = (PsiField)element;
PsiClass aClass = field.getContainingClass();
if (aClass != null) {
urls = findUrlForClass(aClass);
if (urls != null) {
for (int i = 0; i < urls.size(); i++) {
urls.set(i, urls.get(i) + "#" + field.getName());
}
}
}
}
else if (element instanceof PsiMethod) {
PsiMethod method = (PsiMethod)element;
PsiClass aClass = method.getContainingClass();
if (aClass != null) {
List<String> classUrls = findUrlForClass(aClass);
if (classUrls != null) {
urls = ContainerUtil.newSmartList();
final boolean useJava8Format = PsiUtil.isLanguageLevel8OrHigher(method);
final Set<String> signatures = getHtmlMethodSignatures(method, useJava8Format);
for (String signature : signatures) {
for (String classUrl : classUrls) {
urls.add(classUrl + "#" + signature);
}
}
}
}
}
else if (element instanceof PsiPackage) {
urls = findUrlForPackage((PsiPackage)element);
}
else if (element instanceof PsiDirectory) {
PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(((PsiDirectory)element));
if (aPackage != null) {
urls = findUrlForPackage(aPackage);
}
}
if (urls == null || urls.isEmpty()) {
return null;
}
else {
for (int i = 0; i < urls.size(); i++) {
urls.set(i, FileUtil.toSystemIndependentName(urls.get(i)));
}
return urls;
}
}
public static Set<String> getHtmlMethodSignatures(PsiMethod method, boolean java8FormatFirst) {
final Set<String> signatures = new LinkedHashSet<>();
signatures.add(formatMethodSignature(method, true, java8FormatFirst));
signatures.add(formatMethodSignature(method, false, java8FormatFirst));
signatures.add(formatMethodSignature(method, true, !java8FormatFirst));
signatures.add(formatMethodSignature(method, false, !java8FormatFirst));
return signatures;
}
private static String formatMethodSignature(PsiMethod method, boolean raw, boolean java8Format) {
int options = PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_PARAMETERS;
int parameterOptions = PsiFormatUtilBase.SHOW_TYPE | PsiFormatUtilBase.SHOW_FQ_CLASS_NAMES;
if (raw) {
options |= PsiFormatUtilBase.SHOW_RAW_NON_TOP_TYPE;
parameterOptions |= PsiFormatUtilBase.SHOW_RAW_NON_TOP_TYPE;
}
String signature = PsiFormatUtil.formatMethod(method, PsiSubstitutor.EMPTY, options, parameterOptions, 999);
if (java8Format) {
signature = signature.replaceAll("\\(|\\)|, ", "-").replaceAll("\\[\\]", ":A");
}
return signature;
}
@Nullable
public static List<String> findUrlForClass(@NotNull PsiClass aClass) {
String qName = aClass.getQualifiedName();
if (qName == null) return null;
PsiFile file = aClass.getContainingFile();
if (!(file instanceof PsiJavaFile)) return null;
VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile == null) return null;
String packageName = ((PsiJavaFile)file).getPackageName();
String relPath;
if (packageName.isEmpty()) {
relPath = qName + HTML_EXTENSION;
}
else {
relPath = packageName.replace('.', '/') + '/' + qName.substring(packageName.length() + 1) + HTML_EXTENSION;
}
return findUrlForVirtualFile(file.getProject(), virtualFile, relPath);
}
@Nullable
public static List<String> findUrlForVirtualFile(@NotNull Project project, @NotNull VirtualFile virtualFile, @NotNull String relPath) {
final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
Module module = fileIndex.getModuleForFile(virtualFile);
if (module == null) {
final VirtualFileSystem fs = virtualFile.getFileSystem();
if (fs instanceof JarFileSystem) {
final VirtualFile jar = ((JarFileSystem)fs).getVirtualFileForJar(virtualFile);
if (jar != null) {
module = fileIndex.getModuleForFile(jar);
}
}
}
if (module != null) {
String[] javadocPaths = JavaModuleExternalPaths.getInstance(module).getJavadocUrls();
final List<String> httpRoots = PlatformDocumentationUtil.getHttpRoots(javadocPaths, relPath);
// if found nothing and the file is from library classes, fall back to order entries
if (httpRoots != null || !fileIndex.isInLibraryClasses(virtualFile)) {
return httpRoots;
}
}
for (OrderEntry orderEntry : fileIndex.getOrderEntriesForFile(virtualFile)) {
for (VirtualFile root : orderEntry.getFiles(JavadocOrderRootType.getInstance())) {
if (root.getFileSystem() == JarFileSystem.getInstance()) {
VirtualFile file = root.findFileByRelativePath(relPath);
List<Url> urls = file == null ? null : BuiltInWebBrowserUrlProviderKt.getBuiltInServerUrls(file, project, null);
if (!ContainerUtil.isEmpty(urls)) {
List<String> result = new SmartList<>();
for (Url url : urls) {
result.add(url.toExternalForm());
}
return result;
}
}
}
List<String> httpRoot = PlatformDocumentationUtil.getHttpRoots(JavadocOrderRootType.getUrls(orderEntry), relPath);
if (httpRoot != null) {
return httpRoot;
}
}
return null;
}
@Nullable
public static List<String> findUrlForPackage(PsiPackage aPackage) {
String qName = aPackage.getQualifiedName();
qName = qName.replace('.', '/') + '/' + PACKAGE_SUMMARY_FILE;
for (PsiDirectory directory : aPackage.getDirectories()) {
List<String> url = findUrlForVirtualFile(aPackage.getProject(), directory.getVirtualFile(), qName);
if (url != null) {
return url;
}
}
return null;
}
@Override
public PsiElement getDocumentationElementForLink(final PsiManager psiManager, final String link, final PsiElement context) {
return JavaDocUtil.findReferenceTarget(psiManager, link, context);
}
@Override
public String fetchExternalDocumentation(Project project, PsiElement element, List<String> docUrls) {
return fetchExternalJavadoc(element, project, docUrls);
}
@Override
public boolean hasDocumentationFor(PsiElement element, PsiElement originalElement) {
return CompositeDocumentationProvider.hasUrlsFor(this, element, originalElement);
}
@Override
public boolean canPromptToConfigureDocumentation(PsiElement element) {
return false;
}
@Override
public void promptToConfigureDocumentation(PsiElement element) {
}
@Nullable
@Override
public PsiElement getCustomDocumentationElement(@NotNull Editor editor, @NotNull PsiFile file, @Nullable PsiElement contextElement) {
PsiDocComment docComment = PsiTreeUtil.getParentOfType(contextElement, PsiDocComment.class, false);
if (docComment != null && JavaDocUtil.isInsidePackageInfo(docComment)) {
PsiDirectory directory = file.getContainingDirectory();
if (directory != null) {
return JavaDirectoryService.getInstance().getPackage(directory);
}
}
return null;
}
public static String fetchExternalJavadoc(PsiElement element, final Project project, final List<String> docURLs) {
return fetchExternalJavadoc(element, docURLs, new JavaDocExternalFilter(project));
}
public static String fetchExternalJavadoc(PsiElement element, List<String> docURLs, @NotNull JavaDocExternalFilter docFilter) {
if (docURLs != null) {
for (String docURL : docURLs) {
try {
final String javadoc = fetchExternalJavadoc(element, docURL, docFilter);
if (javadoc != null) return javadoc;
}
catch (IndexNotReadyException e) {
throw e;
}
catch (Exception e) {
LOG.info(e); //connection problems should be ignored
}
}
}
return null;
}
}
|
apache-2.0
|
lslewis901/SqlSchemaTool
|
doc/Infor.SST.SQLObjects.UDDTs.Item.html
|
2152
|
<html dir="LTR">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
<title>Item Property </title>
<xml>
</xml>
<link rel="stylesheet" type="text/css" href="MSDN.css" />
</head>
<body id="bodyID" class="dtBODY">
<div id="nsbanner">
<div id="bannerrow1">
<table class="bannerparthead" cellspacing="0">
<tr id="hdr">
<td class="runninghead">SQL Schema Tool Help</td>
<td class="product">
</td>
</tr>
</table>
</div>
<div id="TitleRow">
<h1 class="dtH1">UDDTs.Item Property </h1>
</div>
</div>
<div id="nstext">
<p> Gets the <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemDataDataTableClassTopic.htm">DataTable</a> at the specified index. </p>
<div class="syntax">public virtual <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemDataDataTableClassTopic.htm">System.Data.DataTable</a> this[<br /> <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemInt32ClassTopic.htm">int</a> <i>Index</i><br />] {get;}</div>
<p>
</p>
<h4 class="dtH4">Property Value</h4>
<p>The integer Index to select a DataTable from the DataSet</p>
<h4 class="dtH4">See Also</h4>
<p>
<a href="Infor.SST.SQLObjects.UDDTs.html">UDDTs Class</a> | <a href="Infor.SST.SQLObjects.html">Infor.SST.SQLObjects Namespace</a></p>
<object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
<param name="Keyword" value="Item property">
</param>
<param name="Keyword" value="Item property, UDDTs class">
</param>
<param name="Keyword" value="UDDTs.Item property">
</param>
</object>
<hr />
<div id="footer">
<p>
</p>
<p>Generated from assembly SST [1.0.2118.11998]</p>
</div>
</div>
</body>
</html>
|
apache-2.0
|
xunilrj/sandbox
|
courses/UTAustinX UT.PHP.16.01x/Assignments/Week2/C/Gemm_JI_MRxNRKernel.c
|
838
|
#include <stdio.h>
#include <stdlib.h>
#define alpha( i,j ) A[ (j)*ldA + (i) ] // map alpha( i,j ) to array A
#define beta( i,j ) B[ (j)*ldB + (i) ] // map beta( i,j ) to array B
#define gamma( i,j ) C[ (j)*ldC + (i) ] // map gamma( i,j ) to array C
//#define MR 4
//#define NR 4
void Gemm_MRxNRKernel( int, double *, int, double *, int, double *, int );
void MyGemm( int m, int n, int k, double *A, int ldA,
double *B, int ldB, double *C, int ldC )
{
if ( m % MR != 0 || n % NR != 0 ){
printf( "m and n must be multiples of MR and NR, respectively \n" );
exit( 0 );
}
for ( int j=0; j<n; j+=NR ) /* n is assumed to be a multiple of NR */
for ( int i=0; i<m; i+=MR ) /* m is assumed to be a multiple of MR */
Gemm_MRxNRKernel( k, &alpha( i,0 ), ldA, &beta( 0,j ), ldB, &gamma( i,j ), ldC );
}
|
apache-2.0
|
Vizualizer/VizualizerShop
|
classes/VizualizerShop/Module/Payment/Delete.php
|
1168
|
<?php
/**
* Copyright (C) 2012 Vizualizer All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Naohisa Minagawa <[email protected]>
* @copyright Copyright (c) 2010, Vizualizer
* @license http://www.apache.org/licenses/LICENSE-2.0.html Apache License, Version 2.0
* @since PHP 5.3
* @version 1.0.0
*/
/**
* 決済のデータを削除する。
*
* @package VizualizerShop
* @author Naohisa Minagawa <[email protected]>
*/
class VizualizerShop_Module_Payment_Delete extends Vizualizer_Plugin_Module_Delete
{
function execute($params)
{
$this->executeImpl("Shop", "Payment", "payment_id");
}
}
|
apache-2.0
|
mbrowne/typescript-dci
|
tests/cases/compiler/internalAliasFunctionInsideLocalModuleWithExport.ts
|
220
|
// @declaration: true
export module a {
export function foo(x: number) {
return x;
}
}
export module c {
export import b = a.foo;
export var bVal = b(10);
export var bVal2 = b;
}
|
apache-2.0
|
tanjoc/MyRespository
|
oauth/weixindemo/__init__.py
|
210
|
import web
urls = (
'/wx', 'Handle',
)
class Handle(object):
def GET(self):
return "hello, this is a test"
if __name__ == '__main__':
app = web.application(urls, globals())
app.run()
|
apache-2.0
|
gsantovena/mesos
|
src/master/quota.cpp
|
7795
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "master/quota.hpp"
#include <string>
#include <mesos/mesos.hpp>
#include <mesos/quota/quota.hpp>
#include <mesos/resource_quantities.hpp>
#include <mesos/resources.hpp>
#include <mesos/roles.hpp>
#include <mesos/values.hpp>
#include <stout/error.hpp>
#include <stout/option.hpp>
#include <stout/set.hpp>
#include "common/resources_utils.hpp"
#include "common/validation.hpp"
using google::protobuf::Map;
using google::protobuf::RepeatedPtrField;
using mesos::quota::QuotaConfig;
using mesos::quota::QuotaInfo;
using mesos::quota::QuotaRequest;
using std::string;
namespace mesos {
namespace internal {
namespace master {
namespace quota {
UpdateQuota::UpdateQuota(const QuotaInfo& quotaInfo)
: info(quotaInfo) {}
Try<bool> UpdateQuota::perform(
Registry* registry,
hashset<SlaveID>* /*slaveIDs*/)
{
// If there is already quota stored for the role, update the entry.
foreach (Registry::Quota& quota, *registry->mutable_quotas()) {
if (quota.info().role() == info.role()) {
quota.mutable_info()->CopyFrom(info);
return true; // Mutation.
}
}
// If there is no quota yet for the role, create a new entry.
registry->add_quotas()->mutable_info()->CopyFrom(info);
return true; // Mutation.
}
RemoveQuota::RemoveQuota(const string& _role) : role(_role) {}
Try<bool> RemoveQuota::perform(
Registry* registry,
hashset<SlaveID>* /*slaveIDs*/)
{
// Remove quota for the role if a corresponding entry exists.
for (int i = 0; i < registry->quotas().size(); ++i) {
const Registry::Quota& quota = registry->quotas(i);
if (quota.info().role() == role) {
registry->mutable_quotas()->DeleteSubrange(i, 1);
// NOTE: Multiple entries per role are not allowed.
return true; // Mutation.
}
}
return false;
}
namespace {
QuotaInfo createQuotaInfo(
const string& role,
const RepeatedPtrField<Resource>& guarantee)
{
QuotaInfo quota;
quota.set_role(role);
quota.mutable_guarantee()->CopyFrom(guarantee);
return quota;
}
} // namespace {
QuotaInfo createQuotaInfo(const QuotaRequest& request)
{
return createQuotaInfo(request.role(), request.guarantee());
}
namespace validation {
Option<Error> quotaInfo(const QuotaInfo& quotaInfo)
{
if (!quotaInfo.has_role()) {
return Error("QuotaInfo must specify a role");
}
// Check the provided role is valid.
Option<Error> roleError = roles::validate(quotaInfo.role());
if (roleError.isSome()) {
return Error("QuotaInfo with invalid role: " + roleError->message);
}
// Disallow quota for '*' role.
// TODO(alexr): Consider allowing setting quota for '*' role, see MESOS-3938.
if (quotaInfo.role() == "*") {
return Error("QuotaInfo must not specify the default '*' role");
}
// Check that `QuotaInfo` contains at least one guarantee.
// TODO(alexr): Relaxing this may make sense once quota is the
// only way that we offer non-revocable resources. Setting quota
// with an empty guarantee would mean the role is not entitled to
// get non-revocable offers.
if (quotaInfo.guarantee().empty()) {
return Error("QuotaInfo with empty 'guarantee'");
}
hashset<string> names;
foreach (const Resource& resource, quotaInfo.guarantee()) {
// Check that `resource` does not contain fields that are
// irrelevant for quota.
if (resource.reservations_size() > 0) {
return Error("QuotaInfo must not contain any ReservationInfo");
}
if (resource.has_disk()) {
return Error("QuotaInfo must not contain DiskInfo");
}
if (resource.has_revocable()) {
return Error("QuotaInfo must not contain RevocableInfo");
}
if (resource.type() != Value::SCALAR) {
return Error("QuotaInfo must not include non-scalar resources");
}
// Check that resource names do not repeat.
if (names.contains(resource.name())) {
return Error("QuotaInfo contains duplicate resource name"
" '" + resource.name() + "'");
}
names.insert(resource.name());
}
return None();
}
} // namespace validation {
Option<Error> validate(const QuotaConfig& config)
{
if (!config.has_role()) {
return Error("'QuotaConfig.role' must be set");
}
// Check the provided role is valid.
Option<Error> error = roles::validate(config.role());
if (error.isSome()) {
return Error("Invalid 'QuotaConfig.role': " + error->message);
}
// Disallow quota for '*' role.
if (config.role() == "*") {
return Error(
"Invalid 'QuotaConfig.role': setting quota for the"
" default '*' role is not supported");
}
// Validate scalar values.
foreach (auto&& guarantee, config.guarantees()) {
Option<Error> error =
common::validation::validateInputScalarValue(guarantee.second.value());
if (error.isSome()) {
return Error(
"Invalid guarantee configuration {'" + guarantee.first + "': " +
stringify(guarantee.second) + "}: " + error->message);
}
}
foreach (auto&& limit, config.limits()) {
Option<Error> error =
common::validation::validateInputScalarValue(limit.second.value());
if (error.isSome()) {
return Error(
"Invalid limit configuration {'" + limit.first + "': " +
stringify(limit.second) + "}: " + error->message);
}
}
// Validate guarantees <= limits.
ResourceLimits limits{config.limits()};
ResourceQuantities guarantees{config.guarantees()};
if (!limits.contains(guarantees)) {
return Error(
"'QuotaConfig.guarantees' " + stringify(config.guarantees()) +
" is not contained within the 'QuotaConfig.limits' " +
stringify(config.limits()));
}
return None();
}
} // namespace quota {
} // namespace master {
} // namespace internal {
Quota2::Quota2(const QuotaConfig& config)
{
guarantees = ResourceQuantities(config.guarantees());
limits = ResourceLimits(config.limits());
}
Quota2::Quota2(const QuotaInfo& info)
{
guarantees = ResourceQuantities::fromScalarResources(info.guarantee());
// For legacy `QuotaInfo`, guarantee also acts as limit.
limits = [&info]() {
google::protobuf::Map<string, Value::Scalar> limits;
foreach (const Resource& r, info.guarantee()) {
limits[r.name()] = r.scalar();
}
return ResourceLimits(limits);
}();
}
Quota2::Quota2(const QuotaRequest& request)
{
guarantees = ResourceQuantities::fromScalarResources(request.guarantee());
// For legacy `QuotaInfo`, guarantee also acts as limit.
limits = [&request]() {
google::protobuf::Map<string, Value::Scalar> limits;
foreach (const Resource& r, request.guarantee()) {
limits[r.name()] = r.scalar();
}
return ResourceLimits(limits);
}();
}
bool Quota2::operator==(const Quota2& that) const
{
return guarantees == that.guarantees && limits == that.limits;
}
bool Quota2::operator!=(const Quota2& that) const
{
return guarantees != that.guarantees || limits != that.limits;
}
} // namespace mesos {
|
apache-2.0
|
hurzl/dmix
|
JMPDComm/src/main/java/com/anpmech/mpd/item/FilesystemTreeEntry.java
|
2365
|
/*
* Copyright (C) 2004 Felipe Gustavo de Almeida
* Copyright (C) 2010-2016 The MPDroid Project
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice,this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.anpmech.mpd.item;
/**
* This Interface represents a filesystem entry ({@link Directory}, {@link Entry}, {@link Music} or
* {@link PlaylistFile}) for a MPD protocol item.
*/
public interface FilesystemTreeEntry {
/**
* The full path as given by the MPD protocol.
*
* @return The full path for this entry.
*/
String getFullPath();
/**
* This method returns the last modified time for this entry in Unix time.
*
* <p>The Last-Modified response value is expected to be given in ISO8601.</p>
*
* @return The last modified time for this entry in Unix time.
*/
long getLastModified();
/**
* This returns the size a MPD entry file.
*
* <p><b>This is only available with some MPD command responses.</b></p>
*
* @return The size of a MPD entry file, {@link Integer#MIN_VALUE} if it doesn't exist in this
* response.
*/
long size();
}
|
apache-2.0
|
hschroedl/FluentAST
|
docs/js/main.js
|
966
|
$(function() {
// $('.collapse').collapse('hide');
$('.list-group-item.active').parent().parent('.collapse').collapse('show');
$.ajaxSetup({cache: true});
var fuzzyhound = new FuzzySearch();
function setsource(url, keys) {
$.getJSON(url).then(function (response) {
fuzzyhound.setOptions({
source: response,
keys: keys
})
});
}
setsource(baseurl + '/search.json', ["title"]);
$('#search-box').typeahead({
minLength: 0,
highlight: true
}, {
name: 'pages',
display: 'title',
source: fuzzyhound
});
$('#search-box').bind('typeahead:select', function(ev, suggestion) {
window.location.href = suggestion.url;
});
// Markdown plain out to bootstrap style
$('#markdown-content-container table').addClass('table');
$('#markdown-content-container img').addClass('img-responsive');
});
|
apache-2.0
|
Dempsy/dempsy-commons
|
dempsy-serialization.kryo/src/test/java/net/dempsy/serialization/kryo/TestKryoWithRegistration.java
|
2475
|
package net.dempsy.serialization.kryo;
import static net.dempsy.serialization.kryo.KryoTestUtils.defaultMock3Optimizer;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import net.dempsy.serialization.MockClass;
import net.dempsy.serialization.TestSerializerImplementation;
import net.dempsy.util.SystemPropertyManager;
@RunWith(Parameterized.class)
public class TestKryoWithRegistration extends TestSerializerImplementation {
private final boolean manageExactClass;
public TestKryoWithRegistration(final Boolean manageExactClass) {
super(new KryoSerializer(manageExactClass.booleanValue(), defaultMock3Optimizer, new Registration(MockClass.class.getName()),
new Registration(Mock3.class.getName())), false, manageExactClass.booleanValue());
this.manageExactClass = manageExactClass.booleanValue();
}
@Test(expected = IOException.class)
public void testKryoDeserializeWithRegisterFail() throws Throwable {
final KryoSerializer ser1 = new KryoSerializer(manageExactClass);
final KryoSerializer ser2 = new KryoSerializer(manageExactClass);
ser2.setKryoRegistrationRequired(true);
final byte[] data = ser1.serialize(new MockClass());
ser2.deserialize(data, MockClass.class);
}
@Test
public void testWithRegisterFromResource() throws Throwable {
try(@SuppressWarnings("resource")
SystemPropertyManager p = new SystemPropertyManager()
.set(KryoSerializer.SYS_PROP_REGISTRAION_RESOURCE, "kryo/registration.txt")) {
final KryoSerializer ser1 = new KryoSerializer(manageExactClass);
final KryoSerializer ser2 = new KryoSerializer(manageExactClass);
ser2.setKryoRegistrationRequired(true);
ser1.setKryoRegistrationRequired(true);
final MockClass ser = new MockClass(43, "Yo");
final byte[] data = ser1.serialize(ser);
final MockClass dser = ser2.deserialize(data, MockClass.class);
assertEquals(ser, dser);
}
}
@Parameterized.Parameters(name = "manage exact classes: {0}")
public static Collection<Object[]> manageExactClassParams() {
return Arrays.asList(new Object[][] {
{Boolean.TRUE},
{Boolean.FALSE}
});
}
}
|
apache-2.0
|
leondss/leonds
|
src/main/resources/static/archives/page/2/index.html
|
14400
|
<!DOCTYPE html>
<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">
<link rel="stylesheet" href="/css/main.css?v=7.0.1">
<link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.0.1">
<link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.0.1">
<link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.0.1">
<link rel="mask-icon" href="/images/logo.svg?v=7.0.1" color="#222">
<script id="hexo.configurations">
var NexT = window.NexT || {};
var CONFIG = {
root: '/',
scheme: 'Pisces',
version: '7.0.1',
sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false,"dimmer":false},
fancybox: false,
fastclick: false,
lazyload: false,
tabs: true,
motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
algolia: {
applicationID: '',
apiKey: '',
indexName: '',
hits: {"per_page":10},
labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
}
};
</script>
<meta property="og:type" content="website">
<meta property="og:title" content="Leonds">
<meta property="og:url" content="http://leonds.com/archives/page/2/index.html">
<meta property="og:site_name" content="Leonds">
<meta property="og:locale" content="zh-CN">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Leonds">
<link rel="canonical" href="http://leonds.com/archives/page/2/">
<script id="page.configurations">
CONFIG.page = {
sidebar: "",
};
</script>
<title>归档 | Leonds</title>
<noscript>
<style>
.use-motion .motion-element,
.use-motion .brand,
.use-motion .menu-item,
.sidebar-inner,
.use-motion .post-block,
.use-motion .pagination,
.use-motion .comments,
.use-motion .post-header,
.use-motion .post-body,
.use-motion .collection-title { opacity: initial; }
.use-motion .logo,
.use-motion .site-title,
.use-motion .site-subtitle {
opacity: initial;
top: initial;
}
.use-motion .logo-line-before i { left: initial; }
.use-motion .logo-line-after i { right: initial; }
</style>
</noscript>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">
<div class="container sidebar-position-left page-archive">
<div class="headband"></div>
<header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
<div class="header-inner"><div class="site-brand-wrapper">
<div class="site-meta">
<div class="custom-logo-site-title">
<a href="/" class="brand" rel="start">
<span class="logo-line-before"><i></i></span>
<span class="site-title">Leonds</span>
<span class="logo-line-after"><i></i></span>
</a>
</div>
</div>
<div class="site-nav-toggle">
<button aria-label="切换导航栏">
<span class="btn-bar"></span>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
</button>
</div>
</div>
<nav class="site-nav">
<ul id="menu" class="menu">
<li class="menu-item menu-item-home">
<a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>
</li>
<li class="menu-item menu-item-about">
<a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>
</li>
<li class="menu-item menu-item-tags">
<a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>
</li>
<li class="menu-item menu-item-categories">
<a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>
</li>
<li class="menu-item menu-item-archives menu-item-active">
<a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>
</li>
<li class="menu-item menu-item-schedule">
<a href="/schedule/" rel="section"><i class="menu-item-icon fa fa-fw fa-calendar"></i> <br>日程表</a>
</li>
<li class="menu-item menu-item-sitemap">
<a href="/sitemap.xml" rel="section"><i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br>站点地图</a>
</li>
<li class="menu-item menu-item-commonweal">
<a href="/404/" rel="section"><i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>公益 404</a>
</li>
</ul>
</nav>
</div>
</header>
<main id="main" class="main">
<div class="main-inner">
<div class="content-wrap">
<div id="content" class="content">
<div class="post-block archive">
<div id="posts" class="posts-collapse">
<span class="archive-move-on"></span>
<span class="archive-page-counter">
嗯..! 目前共计 13 篇日志。 继续努力。
</span>
<div class="collection-title">
<h1 class="archive-year" id="archive-year-2019">2019</h1>
</div>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h2 class="post-title">
<a class="post-title-link" href="/2019/03/18/hello-world - 副本 (2)/" itemprop="url">
<span itemprop="name">Hello World</span>
</a>
</h2>
<div class="post-meta">
<time class="post-time" itemprop="dateCreated" datetime="2019-03-18T16:16:52+08:00" content="2019-03-18">
03-18
</time>
</div>
</header>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h2 class="post-title">
<a class="post-title-link" href="/2019/03/18/hello-world - 副本/" itemprop="url">
<span itemprop="name">Hello World</span>
</a>
</h2>
<div class="post-meta">
<time class="post-time" itemprop="dateCreated" datetime="2019-03-18T16:16:52+08:00" content="2019-03-18">
03-18
</time>
</div>
</header>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h2 class="post-title">
<a class="post-title-link" href="/2019/03/18/hello-world/" itemprop="url">
<span itemprop="name">Hello World</span>
</a>
</h2>
<div class="post-meta">
<time class="post-time" itemprop="dateCreated" datetime="2019-03-18T10:19:22+08:00" content="2019-03-18">
03-18
</time>
</div>
</header>
</article>
</div>
</div>
<nav class="pagination">
<a class="extend prev" rel="prev" href="/archives/"><i class="fa fa-angle-left" aria-label="上一页"></i></a><a class="page-number" href="/archives/">1</a><span class="page-number current">2</span>
</nav>
</div>
</div>
<div class="sidebar-toggle">
<div class="sidebar-toggle-line-wrap">
<span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
</div>
</div>
<aside id="sidebar" class="sidebar">
<div class="sidebar-inner">
<div class="site-overview-wrap sidebar-panel sidebar-panel-active">
<div class="site-overview">
<div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
<p class="site-author-name" itemprop="name">Leon</p>
<p class="site-description motion-element" itemprop="description"></p>
</div>
<nav class="site-state motion-element">
<div class="site-state-item site-state-posts">
<a href="/archives/">
<span class="site-state-item-count">13</span>
<span class="site-state-item-name">日志</span>
</a>
</div>
<div class="site-state-item site-state-categories">
<a href="/categories/index.html">
<span class="site-state-item-count">1</span>
<span class="site-state-item-name">分类</span>
</a>
</div>
<div class="site-state-item site-state-tags">
<a href="/tags/index.html">
<span class="site-state-item-count">2</span>
<span class="site-state-item-name">标签</span>
</a>
</div>
</nav>
<div class="links-of-author motion-element">
<span class="links-of-author-item">
<a href="https://github.com/yourname" title="GitHub → https://github.com/yourname" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
</span>
<span class="links-of-author-item">
<a href="mailto:[email protected]" title="E-Mail → mailto:[email protected]" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
</span>
</div>
<div class="links-of-blogroll motion-element links-of-blogroll-block">
<div class="links-of-blogroll-title">
<i class="fa fa-fw fa-link"></i>
Links
</div>
<ul class="links-of-blogroll-list">
<li class="links-of-blogroll-item">
<a href="http://example.com" title="http://example.com" rel="noopener" target="_blank">Title</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</aside>
</div>
</main>
<footer id="footer" class="footer">
<div class="footer-inner">
<div class="copyright">© 2015 – <span itemprop="copyrightYear">2019</span>
<span class="with-love" id="animate">
<i class="fa fa-user"></i>
</span>
<span class="author" itemprop="copyrightHolder">Leon</span>
</div>
<div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.8.0</div>
<span class="post-meta-divider">|</span>
<div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.0.1</div>
</div>
</footer>
<div class="back-to-top">
<i class="fa fa-arrow-up"></i>
</div>
</div>
<script>
if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
window.Promise = null;
}
</script>
<script src="/lib/jquery/index.js?v=2.1.3"></script>
<script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
<script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="/js/src/utils.js?v=7.0.1"></script>
<script src="/js/src/motion.js?v=7.0.1"></script>
<script src="/js/src/affix.js?v=7.0.1"></script>
<script src="/js/src/schemes/pisces.js?v=7.0.1"></script>
<script src="/js/src/bootstrap.js?v=7.0.1"></script>
</body>
</html>
|
apache-2.0
|
envoyproxy/envoy
|
test/test_listener.h
|
1235
|
#pragma once
#include "gtest/gtest.h"
namespace Envoy {
// Provides a test listener to be called after each test method. This offers
// a place to put hooks we'd like to run on every test. There's currently a
// check that all test-scoped singletons have been destroyed. A test-scoped
// singleton might remain at the end of a test if it's transitively referenced
// by a leaked structure or a static.
//
// In the future, we can also add:
// - a test-specific ThreadFactory that enables us to verify there are no
// outstanding threads at the end of each thread.
// - a check that no more bytes of memory are allocated at the end of a test
// than there were at the start of it. This is likely to fail in a few
// places when introduced, but we could add known test overrides for this.
//
// Note: nothing compute-intensive should be put in this class, as it will
// be a tax paid by every test method in the codebase.
class TestListener : public ::testing::EmptyTestEventListener {
public:
TestListener(bool validate_singletons = true) : validate_singletons_(validate_singletons) {}
void OnTestEnd(const ::testing::TestInfo& test_info) override;
private:
bool validate_singletons_;
};
} // namespace Envoy
|
apache-2.0
|
buri17/lambduh-maven-plugin
|
src/main/java/com/github/seanroy/plugins/LambduhMojo.java
|
7545
|
package com.github.seanroy.plugins;
/**
* A Maven plugin allowing a jar built as a part of a Maven project to be
* deployed to AWS lambda.
* @author Sean N. Roy
*/
import java.io.File;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.lambda.AWSLambdaClient;
import com.amazonaws.services.lambda.model.CreateFunctionRequest;
import com.amazonaws.services.lambda.model.CreateFunctionResult;
import com.amazonaws.services.lambda.model.DeleteFunctionRequest;
import com.amazonaws.services.lambda.model.FunctionCode;
import com.amazonaws.services.lambda.model.Runtime;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.Bucket;
@Mojo(name = "deploy-lambda")
public class LambduhMojo extends AbstractMojo {
final Logger logger = LoggerFactory.getLogger(LambduhMojo.class);
@Parameter(property = "accessKey", defaultValue = "${accessKey}")
private String accessKey;
@Parameter(property = "secretKey", defaultValue = "${secretKey}")
private String secretKey;
@Parameter(required = true, defaultValue = "${functionCode}")
private String functionCode;
@Parameter(alias = "region", property = "region", defaultValue = "us-east-1")
private String regionName;
@Parameter(property = "s3Bucket", defaultValue = "lambda-function-code")
private String s3Bucket;
@Parameter(property = "description", defaultValue = "")
private String description;
@Parameter(required = true, defaultValue = "${lambdaRoleArn}")
private String lambdaRoleArn;
@Parameter(property = "functionName", defaultValue = "${functionName}")
private String functionName;
@Parameter(required = true, defaultValue = "${handler}")
private String handler;
@Parameter(property = "runtime", defaultValue = "Java8")
private Runtime runtime;
/**
* Lambda function execution timeout. Defaults to maximum allowed.
*/
@Parameter(property = "timeout", defaultValue = "60")
private int timeout;
@Parameter(property = "memorySize", defaultValue = "128")
private int memorySize;
private String fileName;
private Region region;
private AWSCredentials credentials;
private AmazonS3Client s3Client;
private AWSLambdaClient lambdaClient;
/**
* The entry point into the AWS lambda function.
*/
public void execute() throws MojoExecutionException {
if (accessKey != null && secretKey != null) {
credentials = new BasicAWSCredentials(accessKey, secretKey);
s3Client = new AmazonS3Client(credentials);
lambdaClient = new AWSLambdaClient(credentials);
} else {
s3Client = new AmazonS3Client();
lambdaClient = new AWSLambdaClient();
}
region = Region.getRegion(Regions.fromName(regionName));
lambdaClient.setRegion(region);
String pattern = Pattern.quote(File.separator);
String[] pieces = functionCode.split(pattern);
fileName = pieces[pieces.length - 1];
try {
uploadJarToS3();
deployLambdaFunction();
} catch (Exception e) {
logger.error(e.getMessage());
logger.trace(e.getMessage(), e);
throw new MojoExecutionException(e.getMessage());
}
}
/**
* Makes a create function call on behalf of the caller, deploying the
* function code to AWS lambda.
*
* @return A CreateFunctionResult indicating the success or failure of the
* request.
*/
private CreateFunctionResult createFunction() {
CreateFunctionRequest createFunctionRequest = new CreateFunctionRequest();
createFunctionRequest.setDescription(description);
createFunctionRequest.setRole(lambdaRoleArn);
createFunctionRequest.setFunctionName(functionName);
createFunctionRequest.setHandler(handler);
createFunctionRequest.setRuntime(runtime);
createFunctionRequest.setTimeout(timeout);
createFunctionRequest.setMemorySize(memorySize);
FunctionCode functionCode = new FunctionCode();
functionCode.setS3Bucket(s3Bucket);
functionCode.setS3Key(fileName);
createFunctionRequest.setCode(functionCode);
return lambdaClient.createFunction(createFunctionRequest);
}
/**
* Attempts to delete an existing function of the same name then deploys the
* function code to AWS Lambda. TODO: Attempt to do an update with
* versioning if the function already TODO: exists.
*/
private void deployLambdaFunction() {
// Attempt to delete it first
try {
DeleteFunctionRequest deleteRequest = new DeleteFunctionRequest();
// Why the hell didn't they make this a static method?
deleteRequest = deleteRequest.withFunctionName(functionName);
lambdaClient.deleteFunction(deleteRequest);
} catch (Exception ignored) {
// function didn't exist in the first place.
}
CreateFunctionResult result = createFunction();
logger.info("Function deployed: " + result.getFunctionArn());
}
/**
* The Lambda function will be deployed from AWS S3. This method uploads the
* function code to S3 in preparation of deployment.
*
* @throws Exception
*/
private void uploadJarToS3() throws Exception {
Bucket bucket = getBucket();
if (bucket != null) {
File file = new File(functionCode);
logger.info("Uploading " + functionCode + " to AWS S3 bucket "
+ s3Bucket);
s3Client.putObject(s3Bucket, fileName, file);
logger.info("Upload complete");
} else {
logger.error("Failed to create bucket " + s3Bucket
+ ". try running maven with -X to get full "
+ "debug output");
}
}
/**
* Attempts to return an existing bucket named <code>s3Bucket</code> if it
* exists. If it does not exist, it attempts to create it.
*
* @return An AWS S3 bucket with name <code>s3Bucket</code>
*/
private Bucket getBucket() {
Bucket bucket = getExistingBucket();
if (bucket != null) {
return bucket;
}
try {
bucket = s3Client.createBucket(s3Bucket,
com.amazonaws.services.s3.model.Region.US_Standard);
logger.info("Created bucket " + s3Bucket);
} catch (AmazonServiceException ase) {
logger.error(ase.getMessage());
} catch (AmazonClientException ace) {
logger.error(ace.getMessage());
}
return bucket;
}
private Bucket getExistingBucket() {
List<Bucket> buckets = s3Client.listBuckets();
for (Bucket bucket : buckets) {
if (bucket.getName().equals(s3Bucket)) {
return bucket;
}
}
return null;
}
}
|
apache-2.0
|
jojogreen/Orbital-Mechanix-Suite
|
NetWinCharts/CSharpWinCharts/rotatedarea.cs
|
2394
|
using System;
using ChartDirector;
namespace CSharpChartExplorer
{
public class rotatedarea : DemoModule
{
//Name of demo module
public string getName() { return "Rotated Area Chart"; }
//Number of charts produced in this demo module
public int getNoOfCharts() { return 1; }
//Main code for creating chart.
//Note: the argument chartIndex is unused because this demo only has 1 chart.
public void createChart(WinChartViewer viewer, int chartIndex)
{
// The data for the area chart
double[] data = {30, 28, 40, 55, 75, 68, 54, 60, 50, 62, 75, 65, 75, 89, 60, 55, 53, 35,
50, 66, 56, 48, 52, 65, 62};
// The labels for the area chart
double[] labels = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24};
// Create a XYChart object of size 320 x 320 pixels
XYChart c = new XYChart(320, 320);
// Swap the x and y axis to become a rotated chart
c.swapXY();
// Set the y axis on the top side (right + rotated = top)
c.setYAxisOnRight();
// Reverse the x axis so it is pointing downwards
c.xAxis().setReverse();
// Set the plotarea at (50, 50) and of size 200 x 200 pixels. Enable horizontal and
// vertical grids by setting their colors to grey (0xc0c0c0).
c.setPlotArea(50, 50, 250, 250).setGridColor(0xc0c0c0, 0xc0c0c0);
// Add a line chart layer using the given data
c.addAreaLayer(data, c.gradientColor(50, 0, 300, 0, 0xffffff, 0x0000ff));
// Set the labels on the x axis. Append "m" after the value to show the unit.
c.xAxis().setLabels2(labels, "{value} m");
// Display 1 out of 3 labels.
c.xAxis().setLabelStep(3);
// Add a title to the x axis
c.xAxis().setTitle("Depth");
// Add a title to the y axis
c.yAxis().setTitle("Carbon Dioxide Concentration (ppm)");
// Output the chart
viewer.Chart = c;
//include tool tip for the chart
viewer.ImageMap = c.getHTMLImageMap("clickable", "",
"title='Carbon dioxide concentration at {xLabel}: {value} ppm'");
}
}
}
|
apache-2.0
|
StreamReduce/streamreduce-core
|
core/src/main/java/com/streamreduce/core/model/dto/ConnectionCredentialsSerializer.java
|
2476
|
/*
* Copyright 2012 Nodeable 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.
*/
package com.streamreduce.core.model.dto;
import com.streamreduce.core.model.ConnectionCredentials;
import com.streamreduce.core.model.ConnectionCredentialsEncrypter;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
import java.io.IOException;
public class ConnectionCredentialsSerializer extends JsonSerializer<ConnectionCredentials> {
@Override
public Class<ConnectionCredentials> handledType() {
return ConnectionCredentials.class;
}
@Override
public void serialize(ConnectionCredentials connectionCredentials, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
//Create a copy so we don't encrypt the existing reference
ConnectionCredentials copy = ConnectionCredentials.copyOf(connectionCredentials);
ConnectionCredentialsEncrypter credentialsEncrypter = new ConnectionCredentialsEncrypter();
credentialsEncrypter.encrypt(copy);
jgen.writeStartObject();
if (copy.getIdentity() != null) {
jgen.writeStringField("identity",copy.getIdentity());
}
if (copy.getCredential() != null) {
jgen.writeStringField("credential",copy.getCredential());
}
if (copy.getApiKey() != null) {
jgen.writeStringField("apiKey",copy.getApiKey());
}
if (copy.getOauthToken() != null) {
jgen.writeStringField("oauthToken",copy.getOauthToken());
}
if (copy.getOauthTokenSecret() != null) {
jgen.writeStringField("oauthTokenSecret",copy.getOauthTokenSecret());
}
if (copy.getOauthVerifier() != null) {
jgen.writeStringField("oauthVerifier",copy.getOauthVerifier());
}
jgen.writeEndObject();
}
}
|
apache-2.0
|
neowu/core-ng-project
|
core-ng/src/test/java/core/framework/internal/db/SQLParamsTest.java
|
1772
|
package core.framework.internal.db;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author neo
*/
class SQLParamsTest {
@Test
void appendWithEnum() {
var mapper = new EnumDBMapper();
mapper.registerEnumClass(TestEnum.class);
var params = new SQLParams(mapper, "String", 1, TestEnum.V2, LocalDate.of(2018, 6, 1));
var builder = new StringBuilder();
params.append(builder, Set.of(), 1000);
assertThat(builder.toString())
.isEqualTo("[String, 1, DB_V2, 2018-06-01]");
}
@Test
void appendWithUnregisteredEnum() {
var params = new SQLParams(new EnumDBMapper(), TestEnum.V1);
var builder = new StringBuilder();
params.append(builder, Set.of(), 1000);
assertThat(builder.toString())
.isEqualTo("[V1]");
}
@Test
void appendWithEmpty() {
var params = new SQLParams(null);
var builder = new StringBuilder();
params.append(builder, Set.of(), 1000);
assertThat(builder.toString()).isEqualTo("[]");
}
@Test
void appendWithNull() {
var params = new SQLParams(null, (Object[]) null);
var builder = new StringBuilder();
params.append(builder, Set.of(), 1000);
assertThat(builder.toString())
.isEqualTo("null");
}
@Test
void appendWithTruncation() {
var params = new SQLParams(null, "v1-long-text", "v2-long-text");
var builder = new StringBuilder();
params.append(builder, Set.of(), 20);
assertThat(builder.toString())
.isEqualTo("[v1...(truncated), v2...(truncated)]");
}
}
|
apache-2.0
|
ChinaLHR/JavaQuarkBBS
|
quark-admin/src/main/java/com/quark/admin/service/impl/PostsServiceImpl.java
|
2846
|
package com.quark.admin.service.impl;
import com.quark.admin.service.PostsService;
import com.quark.common.base.BaseServiceImpl;
import com.quark.common.dao.PostsDao;
import com.quark.common.entity.Posts;
import com.quark.common.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @Author LHR
* Create By 2017/9/3
*/
@Service
public class PostsServiceImpl extends BaseServiceImpl<PostsDao,Posts> implements PostsService {
@Override
public Page<Posts> findByPage(Posts posts, int pageNo, int length) {
PageRequest pageable = new PageRequest(pageNo, length);
Sort.Order order = new Sort.Order(Sort.Direction.ASC, "id");
Sort sort = new Sort(order);
Specification<Posts> specification = new Specification<Posts>() {
@Override
public Predicate toPredicate(Root<Posts> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
Path<Integer> $id = root.get("id");
Path<String> $title = root.get("title");
Path<User> $user = root.get("user");
Path<Boolean> $top = root.get("top");
Path<Boolean> $good = root.get("good");
ArrayList<Predicate> list = new ArrayList<>();
if (posts.getId()!=null) list.add(criteriaBuilder.equal($id,posts.getId()));
if (posts.getTitle()!=null) list.add(criteriaBuilder.like($title,"%" + posts.getTitle() + "%"));
if (posts.getUser()!=null) list.add(criteriaBuilder.equal($user,posts.getUser()));
if (posts.getTop()==true) list.add(criteriaBuilder.equal($top,true));
if (posts.getGood()==true) list.add(criteriaBuilder.equal($good,true));
Predicate predicate = criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
return predicate;
}
};
Page<Posts> page = repository.findAll(specification, pageable);
return page;
}
@Override
public void changeTop(Integer[] ids) {
List<Posts> all = findAll(Arrays.asList(ids));
for (Posts p :all) {
if (p.getTop()==false) p.setTop(true);
else p.setTop(false);
}
save(all);
}
@Override
public void changeGood(Integer[] ids) {
List<Posts> all = findAll(Arrays.asList(ids));
for (Posts p :all) {
if (p.getGood()==false) p.setGood(true);
else p.setGood(false);
}
save(all);
}
}
|
apache-2.0
|
zhouyao1994/incubator-superset
|
superset/assets/cypress/integration/sqllab/tabs.js
|
1920
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
export default () => {
describe('SqlLab query tabs', () => {
beforeEach(() => {
cy.login();
cy.server();
cy.visit('/superset/sqllab');
});
it('allows you to create a tab', () => {
cy.get('#a11y-query-editor-tabs > ul > li').then((tabList) => {
const initialTabCount = tabList.length;
// add tab
cy.get('#a11y-query-editor-tabs > ul > li')
.last()
.click();
cy.get('#a11y-query-editor-tabs > ul > li').should('have.length', initialTabCount + 1);
});
});
it('allows you to close a tab', () => {
cy.get('#a11y-query-editor-tabs > ul > li').then((tabListA) => {
const initialTabCount = tabListA.length;
// open the tab dropdown to remove
cy.get('#a11y-query-editor-tabs > ul > li:first button:nth-child(2)').click();
// first item is close
cy.get('#a11y-query-editor-tabs > ul > li:first ul li a')
.eq(0)
.click();
cy.get('#a11y-query-editor-tabs > ul > li').should('have.length', initialTabCount - 1);
});
});
});
};
|
apache-2.0
|
TheLimeGlass/Skellett
|
src/main/java/com/gmail/thelimeglass/Nametags/EffAddPlayerNametag.java
|
1593
|
package com.gmail.thelimeglass.Nametags;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.scoreboard.Scoreboard;
import org.eclipse.jdt.annotation.Nullable;
import com.gmail.thelimeglass.Utils.Annotations.Config;
import com.gmail.thelimeglass.Utils.Annotations.FullConfig;
import com.gmail.thelimeglass.Utils.Annotations.Syntax;
import ch.njol.skript.lang.Effect;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.util.Kleenean;
@Syntax("[skellett] add %player% to [the] [name][ ]tag [(with|of)] [id] %string% [(with|from) [[score][ ]board] %-scoreboard%]")
@Config("Main.Nametags")
@FullConfig
public class EffAddPlayerNametag extends Effect {
private Expression<Player> player;
private Expression<String> nametag;
private Expression<Scoreboard> scoreboard;
@SuppressWarnings("unchecked")
@Override
public boolean init(Expression<?>[] e, int arg1, Kleenean arg2, ParseResult arg3) {
player = (Expression<Player>) e[0];
nametag = (Expression<String>) e[1];
scoreboard = (Expression<Scoreboard>) e[2];
return true;
}
@Override
public String toString(@Nullable Event paramEvent, boolean paramBoolean) {
return "[skellett] add %player% to [the] [name][ ]tag [(with|of)] [id] %string% [[score][ ]board] %-scoreboard%]";
}
@Override
protected void execute(Event e) {
Scoreboard board = null;
if (scoreboard != null && scoreboard.getSingle(e) != null) {
board = scoreboard.getSingle(e);
}
NametagManager.addPlayer(player.getSingle(e), nametag.getSingle(e), board);
}
}
|
apache-2.0
|
waykanza/fasilitas
|
vb/project/import_sm/My Project/Resources.Designer.vb
|
2714
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.1
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("import_sm.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set(ByVal value As Global.System.Globalization.CultureInfo)
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
apache-2.0
|
parthabb/se
|
model/model.php
|
4147
|
<?php
function GetDBHandle($machine, $username, $password, $db_name) {
$con = mysqli_connect($machine, $username, $password, $db_name);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_errno();
$_SESSION['ErrMsg'] = 'Server Error'; // put up a server error page.
return;
}
return $con;
}
class BaseModel {
protected $con;
public function __construct($handle) {
$this->con = $handle;
}
}
class UserModel extends BaseModel {
public function GetUserByEmpIdAndPass($empId, $pass) {
$query = 'SELECT * FROM employee where empId = ' . $empId . ' and ' .
'password = MD5("' . $pass . '")';
return mysqli_query ($this->con, $query);
}
}
class LeavesModel extends BaseModel {
public function GetLeavesForEmpId($empid) {
$query = 'Select * from leaves where empId = ' . $empid;
return mysqli_query($this->con, $query);
}
public function GetLeavesCountByEmdId($empid) {
$query = 'Select * from lcount where empId = ' . $empid;
return mysqli_query($this->con, $query);
}
public function SubmitLeaves($empid, $start_date, $end_date, $type,
$reason) {
mysqli_query($this->con, 'start transaction');
$query = ('Insert into leaves (empId, startDate, endDate, type, reason) ' .
'values (' . $empid . ', "' . $start_date .'", "' . $end_date . '", ' .
'"' . $type . '", "' . $reason . '")');
$result = mysqli_query($this->con, $query);
$new_result = false;
if ($result) {
$new_q = 'update lcount set remaining = remaining - datediff("'
. $end_date . '", "' . $start_date . '") - 1 where ' .
'lcount.empId=' . $empid;
$new_result = mysqli_query($this->con, $new_q);
}
if ($result and $new_result) {
mysqli_query($this->con, 'commit');
} else {
mysqli_query($this->con, 'rollback');
}
return $result and $new_result;
}
public function GetPendingLeavesOfSubordinates($empid) {
// Change query to accomodate juniors.
$query = 'select ID, employee.empId, fName, lName, startDate, endDate, ' .
'status, reason, type from ' .
'employee join leaves where employee.empId !=' . $empid . ' and ' .
'employee.empId=leaves.empId and status="Pending"';
return mysqli_query($this->con, $query);
}
public function ApproveLeaves($decision_map) {
$ids = implode(',', array_keys($decision_map));
$query = 'select * from leaves where ID in (' . $ids . ')';
$old_data = mysqli_query($this->con, $query);
mysqli_query($this->con, 'start transaction');
$query = 'update leaves set status = case ID';
foreach ($decision_map as $key => $value) {
$query .= ' when ' . $key . ' then "' . $value .'"';
}
$query .= ' end where ID in (' . $ids . ')';
$result = mysqli_query($this->con, $query);
$new_result = false;
if ($result) {
$new_dm = array();
while ($row = mysqli_fetch_array($old_data)) {
if (!isset($new_dm[$row['ID']])) {
$new_dm += array($row['empId'] => 0);
}
if (isset($decision_map[(string)$row['ID']]) and $decision_map[
(string)$row['ID']] === 'Rejected') {
$new_dm[$row['empId']] += round(
(strtotime($row['endDate']) - strtotime(
$row['startDate'])) / 86400) + 1;
}
}
$new_q = 'update lcount set remaining = case empId';
foreach ($new_dm as $k => $v) {
$new_q .= ' when ' . $k . ' then remaining + ' . $v;
}
$new_q .= ' end where empId in (' . implode(',', array_keys(
$new_dm)) . ')';
$new_result = mysqli_query($this->con, $new_q);
}
if ($result and $new_result) {
mysqli_query($this->con, 'commit');
} else {
mysqli_query($this->con, 'rollback');
}
return $result and $new_result;
}
}
?>
|
apache-2.0
|
stesind/wetter
|
app/src/androidTest/java/de/sindzinski/wetter/data/TestWeatherContract.java
|
1934
|
/*
* Copyright (C) 2014 The Android Open Source Project
*
* 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 de.sindzinski.wetter.data;
import android.net.Uri;
import android.test.AndroidTestCase;
/*
Students: This is NOT a complete test for the WeatherContract --- just for the functions
that we expect you to write.
*/
public class TestWeatherContract extends AndroidTestCase {
// intentionally includes a slash to make sure Uri is getting quoted correctly
private static final String TEST_WEATHER_LOCATION = "/North Pole";
private static final long TEST_WEATHER_DATE = 1419033600L; // December 20th, 2014
/*
Students: Uncomment this out to test your weather location function.
*/
public void testBuildWeatherLocation() {
Uri locationUri = WeatherContract.WeatherEntry.buildWeatherLocation(TEST_WEATHER_LOCATION);
assertNotNull("Error: Null Uri returned. You must fill-in buildWeatherLocation in " +
"WeatherContract.",
locationUri);
assertEquals("Error: Weather location not properly appended to the end of the Uri",
TEST_WEATHER_LOCATION, locationUri.getLastPathSegment());
assertEquals("Error: Weather location Uri doesn't match our expected result",
locationUri.toString(),
"content://de.sindzinski.wetter/weather/%2FNorth%20Pole");
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Dothideomycetes/Lichenotheliaceae/README.md
|
225
|
# Lichenotheliaceae Henssen FAMILY
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Syst. Ascom. 5: 137 (1986)
#### Original name
Lichenotheliaceae Henssen
### Remarks
null
|
apache-2.0
|
sandor-nemeth/bam
|
bam-ui-angular/src/app/components/webDevTec/webDevTec.service.js
|
2427
|
(function() {
'use strict';
angular
.module('bamUiAngular')
.service('webDevTec', webDevTec);
/** @ngInject */
function webDevTec() {
var data = [
{
'title': 'AngularJS',
'url': 'https://angularjs.org/',
'description': 'HTML enhanced for web apps!',
'logo': 'angular.png'
},
{
'title': 'BrowserSync',
'url': 'http://browsersync.io/',
'description': 'Time-saving synchronised browser testing.',
'logo': 'browsersync.png'
},
{
'title': 'GulpJS',
'url': 'http://gulpjs.com/',
'description': 'The streaming build system.',
'logo': 'gulp.png'
},
{
'title': 'Jasmine',
'url': 'http://jasmine.github.io/',
'description': 'Behavior-Driven JavaScript.',
'logo': 'jasmine.png'
},
{
'title': 'Karma',
'url': 'http://karma-runner.github.io/',
'description': 'Spectacular Test Runner for JavaScript.',
'logo': 'karma.png'
},
{
'title': 'Protractor',
'url': 'https://github.com/angular/protractor',
'description': 'End to end test framework for AngularJS applications built on top of WebDriverJS.',
'logo': 'protractor.png'
},
{
'title': 'Bootstrap',
'url': 'http://getbootstrap.com/',
'description': 'Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web.',
'logo': 'bootstrap.png'
},
{
'title': 'Angular UI Bootstrap',
'url': 'http://angular-ui.github.io/bootstrap/',
'description': 'Bootstrap components written in pure AngularJS by the AngularUI Team.',
'logo': 'ui-bootstrap.png'
},
{
'title': 'Sass (Node)',
'url': 'https://github.com/sass/node-sass',
'description': 'Node.js binding to libsass, the C version of the popular stylesheet preprocessor, Sass.',
'logo': 'node-sass.png'
},
{
'key': 'jade',
'title': 'Jade',
'url': 'http://jade-lang.com/',
'description': 'Jade is a high performance template engine heavily influenced by Haml and implemented with JavaScript for node.',
'logo': 'jade.png'
}
];
this.getTec = getTec;
function getTec() {
return data;
}
}
})();
|
apache-2.0
|
Bigsby/PoC
|
Web/Owin/IISApp/IISApp/Controllers/SimpleController.cs
|
198
|
using System.Web.Http;
namespace IISApp.Controllers
{
public class SimpleController : ApiController
{
public string Get() {
return "In controller";
}
}
}
|
apache-2.0
|
gstevey/gradle
|
subprojects/core/src/main/java/org/gradle/internal/classpath/DefaultCachedClasspathTransformer.java
|
4767
|
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.internal.classpath;
import org.gradle.api.Transformer;
import org.gradle.cache.CacheBuilder;
import org.gradle.cache.CacheRepository;
import org.gradle.cache.FileLockManager;
import org.gradle.cache.PersistentCache;
import org.gradle.internal.Factories;
import org.gradle.internal.Factory;
import org.gradle.internal.UncheckedException;
import org.gradle.internal.file.JarCache;
import org.gradle.util.CollectionUtils;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static org.gradle.cache.internal.filelock.LockOptionsBuilder.mode;
public class DefaultCachedClasspathTransformer implements CachedClasspathTransformer, Closeable {
private final PersistentCache cache;
private final Transformer<File, File> jarFileTransformer;
public DefaultCachedClasspathTransformer(CacheRepository cacheRepository, JarCache jarCache, List<CachedJarFileStore> fileStores) {
this.cache = cacheRepository
.cache("jars-3")
.withDisplayName("jars")
.withCrossVersionCache(CacheBuilder.LockTarget.DefaultTarget)
.withLockOptions(mode(FileLockManager.LockMode.None))
.open();
this.jarFileTransformer = new CachedJarFileTransformer(jarCache, cache, fileStores);
}
@Override
public ClassPath transform(ClassPath classPath) {
return DefaultClassPath.of(CollectionUtils.collect(classPath.getAsFiles(), jarFileTransformer));
}
@Override
public Collection<URL> transform(Collection<URL> urls) {
return CollectionUtils.collect(urls, new Transformer<URL, URL>() {
@Override
public URL transform(URL url) {
if (url.getProtocol().equals("file")) {
try {
return jarFileTransformer.transform(new File(url.toURI())).toURI().toURL();
} catch (URISyntaxException e) {
throw UncheckedException.throwAsUncheckedException(e);
} catch (MalformedURLException e) {
throw UncheckedException.throwAsUncheckedException(e);
}
} else {
return url;
}
}
});
}
@Override
public void close() throws IOException {
cache.close();
}
private static class CachedJarFileTransformer implements Transformer<File, File> {
private final JarCache jarCache;
private final PersistentCache cache;
private final List<String> prefixes;
CachedJarFileTransformer(JarCache jarCache, PersistentCache cache, List<CachedJarFileStore> fileStores) {
this.jarCache = jarCache;
this.cache = cache;
prefixes = new ArrayList<String>(fileStores.size() + 1);
prefixes.add(cache.getBaseDir().getAbsolutePath() + File.separator);
for (CachedJarFileStore fileStore : fileStores) {
for (File rootDir : fileStore.getFileStoreRoots()) {
prefixes.add(rootDir.getAbsolutePath() + File.separator);
}
}
}
@Override
public File transform(final File original) {
if (shouldUseFromCache(original)) {
return cache.useCache(new Factory<File>() {
public File create() {
return jarCache.getCachedJar(original, Factories.constant(cache.getBaseDir()));
}
});
} else {
return original;
}
}
private boolean shouldUseFromCache(File original) {
if (!original.isFile()) {
return false;
}
for (String prefix : prefixes) {
if (original.getAbsolutePath().startsWith(prefix)) {
return false;
}
}
return true;
}
}
}
|
apache-2.0
|
nelsonlyra/webpayments-demo
|
payment-apps/kryptonpay2/pay/index.html
|
4204
|
<!DOCTYPE html>
<html>
<head>
<title>Pay with TommyPay</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<!-- payment form HTML code -->
<div class="kr-embedded">
<div class="kr-pan"></div>
<div class="kr-expiry"></div>
<div class="kr-security-code"></div>
<div class="kr-form-error"></div>
<button class="kr-payment-button kr-text-animated">Shot!</button>
</div>
<pre style="display: none" id="paymentView"></pre>
<!-- Dealing with krypton -->
<script>
var KryponToken = "";
navigator.serviceWorker.addEventListener('message', function(event) {
console.log("NNU : Page got message from SW "+event.data);
//paymentView.textContent = JSON.stringify(event.data, null, ' ');
var ftoken = "";
KR_PAYMENT_HOOK = function(message) { console.dir(message); }
$.ajax({
url: "https://nnu.sandbox.ptitp.eu/krypton",
dataType: "jsonp",
jsonpCallback: 'jsonCallback',
success: function(data) {
ftoken = data.answer.formToken;
},
complete: function(){
$('head').append('<script id="krypton" src="https://secure.payzen.eu/static/js/krypton-client/V3/stable/kr.min.js?formToken='+ftoken+'" kr-public-key="69876357:testpublickey_DEMOPUBLICKEY95me92597fd28tGD4r5" kr-post-url="index_krypton.html" kr-theme="icons-1"></\script>');
}
});
var existCondition = setInterval(function() {
if(typeof KR !== "undefined"){
clearInterval(existCondition);
KR.$(document).ready(function() {
KR.event.handler.listen("paymentDone", function(payment) {
console.log("NNU : paymentDone "+JSON.stringify(payment));
console.log("NNU : paymentDone "+payment.data.kr_billingTransaction);
$(".kr-embedded").hide();
var kr_billingTransaction = payment.data.kr_billingTransaction;
$.ajax({
url: "https://nnu.sandbox.ptitp.eu/krypton_validate/"+kr_billingTransaction,
dataType: "jsonp",
jsonpCallback: 'jsonCallback',
success: function(data) {
console.log("NNU : success "+JSON.stringify(data));
console.log("NNU : success "+data.answer.paymentMethod);
KryponToken = data.answer.paymentMethod;
},
complete: function(){
console.log("NNU : complete "+KryponToken);
event.source.postMessage({
methodName: "https://kryptonpay2.no/pay",
details: {
test: KryponToken
}
});
window.close();
}
});
});
});
}
}, 100);
/*
paymentButton.onclick = function() {
console.log("NNU : Page passing response back to SW ");
event.source.postMessage({
methodName: "https://kryptonpay.no/pay",
details: {
test: KryponToken
}
});
window.close();
}
*/
});
</script>
</body>
</html>
|
apache-2.0
|
lzanol/amphtml
|
src/event-helper.js
|
5533
|
/**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {internalListenImplementation} from './event-helper-listen';
import {user} from './log';
/** @const {string} */
const LOAD_FAILURE_PREFIX = 'Failed to load:';
/**
* Returns a CustomEvent with a given type and detail; supports fallback for IE.
* @param {!Window} win
* @param {string} type
* @param {Object} detail
* @return {!Event}
*/
export function createCustomEvent(win, type, detail) {
if (win.CustomEvent) {
return new win.CustomEvent(type, {detail});
} else {
// Deprecated fallback for IE.
const e = win.document.createEvent('CustomEvent');
e.initCustomEvent(
type, /* canBubble */ false, /* cancelable */ false, detail);
return e;
}
}
/**
* Listens for the specified event on the element.
* @param {!EventTarget} element
* @param {string} eventType
* @param {function(!Event)} listener
* @param {boolean=} opt_capture
* @return {!UnlistenDef}
*/
export function listen(element, eventType, listener, opt_capture) {
return internalListenImplementation(
element, eventType, listener, opt_capture);
}
/**
* Listens for the specified event on the element and removes the listener
* as soon as event has been received.
* @param {!EventTarget} element
* @param {string} eventType
* @param {function(!Event)} listener
* @param {boolean=} opt_capture
* @return {!UnlistenDef}
*/
export function listenOnce(element, eventType, listener, opt_capture) {
let localListener = listener;
const unlisten = internalListenImplementation(element, eventType, event => {
try {
localListener(event);
} finally {
// Ensure listener is GC'd
localListener = null;
unlisten();
}
}, opt_capture);
return unlisten;
}
/**
* Returns a promise that will resolve as soon as the specified event has
* fired on the element.
* @param {!EventTarget} element
* @param {string} eventType
* @param {boolean=} opt_capture
* @param {function(!UnlistenDef)=} opt_cancel An optional function that, when
* provided, will be called with the unlistener. This gives the caller
* access to the unlistener, so it may be called manually when necessary.
* @return {!Promise<!Event>}
*/
export function listenOncePromise(element, eventType, opt_capture, opt_cancel) {
let unlisten;
const eventPromise = new Promise(resolve => {
unlisten = listenOnce(element, eventType, resolve, opt_capture);
});
eventPromise.then(unlisten, unlisten);
if (opt_cancel) {
opt_cancel(unlisten);
}
return eventPromise;
}
/**
* Whether the specified element/window has been loaded already.
* @param {!Element|!Window} eleOrWindow
* @return {boolean}
*/
export function isLoaded(eleOrWindow) {
return !!(eleOrWindow.complete || eleOrWindow.readyState == 'complete'
// If the passed in thing is a Window, infer loaded state from
//
|| (eleOrWindow.document
&& eleOrWindow.document.readyState == 'complete'));
}
/**
* Returns a promise that will resolve or fail based on the eleOrWindow's 'load'
* and 'error' events. Optionally this method takes a timeout, which will reject
* the promise if the resource has not loaded by then.
* @param {T} eleOrWindow Supports both Elements and as a special case Windows.
* @return {!Promise<T>}
* @template T
*/
export function loadPromise(eleOrWindow) {
let unlistenLoad;
let unlistenError;
if (isLoaded(eleOrWindow)) {
return Promise.resolve(eleOrWindow);
}
const loadingPromise = new Promise((resolve, reject) => {
// Listen once since IE 5/6/7 fire the onload event continuously for
// animated GIFs.
const tagName = eleOrWindow.tagName;
if (tagName === 'AUDIO' || tagName === 'VIDEO') {
unlistenLoad = listenOnce(eleOrWindow, 'loadstart', resolve);
} else {
unlistenLoad = listenOnce(eleOrWindow, 'load', resolve);
}
// For elements, unlisten on error (don't for Windows).
if (tagName) {
unlistenError = listenOnce(eleOrWindow, 'error', reject);
}
});
return loadingPromise.then(() => {
if (unlistenError) {
unlistenError();
}
return eleOrWindow;
}, () => {
if (unlistenLoad) {
unlistenLoad();
}
failedToLoad(eleOrWindow);
});
}
/**
* Emit error on load failure.
* @param {!Element|!Window} eleOrWindow Supports both Elements and as a special
* case Windows.
*/
function failedToLoad(eleOrWindow) {
// Report failed loads as user errors so that they automatically go
// into the "document error" bucket.
let target = eleOrWindow;
if (target && target.src) {
target = target.src;
}
throw user().createError(LOAD_FAILURE_PREFIX, target);
}
/**
* Returns true if this error message is was created for a load error.
* @param {string} message An error message
* @return {boolean}
*/
export function isLoadErrorMessage(message) {
return message.indexOf(LOAD_FAILURE_PREFIX) != -1;
}
|
apache-2.0
|
spinnaker/deck
|
packages/cloudfoundry/src/presentation/widgets/accountRegionClusterSelector/AccountRegionClusterSelector.spec.tsx
|
15140
|
import type { IScope } from 'angular';
import { mock, noop } from 'angular';
import { mount, shallow } from 'enzyme';
import React from 'react';
import type { Application, ApplicationDataSource, IMoniker, IServerGroup } from '@spinnaker/core';
import { ApplicationModelBuilder, REACT_MODULE } from '@spinnaker/core';
import type { IAccountRegionClusterSelectorProps } from './AccountRegionClusterSelector';
import { AccountRegionClusterSelector } from './AccountRegionClusterSelector';
describe('<AccountRegionClusterSelector />', () => {
let $scope: IScope;
let application: Application;
function createServerGroup(account: string, cluster: string, name: string, region: string): IServerGroup {
return {
account,
cloudProvider: 'cloud-provider',
cluster,
name,
region,
instances: [{ health: null, id: 'instance-id', launchTime: 0, name: 'instance-name', zone: 'GMT' }],
instanceCounts: { up: 1, down: 0, starting: 0, succeeded: 1, failed: 0, unknown: 0, outOfService: 0 },
moniker: { app: 'my-app', cluster, detail: 'my-detail', stack: 'my-stack', sequence: 1 },
} as IServerGroup;
}
beforeEach(mock.module(REACT_MODULE));
beforeEach(
mock.inject(($rootScope: IScope) => {
$scope = $rootScope.$new();
application = ApplicationModelBuilder.createApplicationForTests('app', {
key: 'serverGroups',
loaded: true,
data: [
createServerGroup('account-name-one', 'app-stack-detailOne', 'app', 'region-one'),
createServerGroup('account-name-two', 'app-stack-detailTwo', 'app', 'region-two'),
createServerGroup('account-name-one', 'app-stack-detailOne', 'app', 'region-three'),
createServerGroup('account-name-one', 'app-stack-detailThree', 'app', 'region-one'),
createServerGroup('account-name-one', 'app-stack-detailFour', 'app', 'region-three'),
createServerGroup('account-name-one', 'app-stack-detailFive', 'app', 'region-two'),
],
defaultData: [] as IServerGroup[],
} as ApplicationDataSource<IServerGroup[]>);
}),
);
it('initializes properly with provided component', () => {
const accountRegionClusterProps: IAccountRegionClusterSelectorProps = {
accounts: [
{
accountId: 'account-id-one',
name: 'account-name-one',
requiredGroupMembership: [],
type: 'account-type',
},
],
application,
cloudProvider: 'cloud-provider',
onComponentUpdate: noop,
component: {
credentials: 'account-name-one',
regions: ['region-one'],
},
};
const component = shallow<AccountRegionClusterSelector>(
<AccountRegionClusterSelector {...accountRegionClusterProps} />,
);
$scope.$digest();
expect(component.state().availableRegions.length).toBe(3, 'number of available regions does not match');
expect(component.state().availableRegions).toContain('region-one');
expect(component.state().availableRegions).toContain('region-two');
expect(component.state().availableRegions).toContain('region-three');
expect(component.state().clusters.length).toBe(2, 'number of clusters does not match');
expect(component.state().clusters).toContain('app-stack-detailOne');
expect(component.state().clusters).toContain('app-stack-detailThree');
expect(component.state().clusterField).toBe('cluster');
expect(component.state().componentName).toBe('');
});
it('retrieves the correct list of regions when account is changed', () => {
let credentials = '';
let region = 'SHOULD-CHANGE';
let regions = ['SHOULD-CHANGE'];
let cluster = 'SHOULD-CHANGE';
const accountRegionClusterProps: IAccountRegionClusterSelectorProps = {
accounts: [
{
accountId: 'account-id-two',
name: 'account-name-two',
requiredGroupMembership: [],
type: 'account-type',
},
{
accountId: 'account-id-one',
name: 'account-name-one',
requiredGroupMembership: [],
type: 'account-type',
},
],
application,
cloudProvider: 'cloud-provider',
onComponentUpdate: (value: any) => {
credentials = value.credentials;
region = value.region;
regions = value.regions;
cluster = value.cluster;
},
component: {
credentials: 'account-name-one',
regions: ['region-one'],
},
};
const component = mount<AccountRegionClusterSelector>(
<AccountRegionClusterSelector {...accountRegionClusterProps} />,
);
$scope.$digest();
expect(component.state().availableRegions.length).toBe(3, 'number of available regions does not match');
expect(component.state().availableRegions).toContain('region-one');
expect(component.state().availableRegions).toContain('region-two');
expect(component.state().availableRegions).toContain('region-three');
expect(component.state().clusters.length).toBe(2, 'number of clusters does not match');
expect(component.state().clusters).toContain('app-stack-detailOne');
expect(component.state().clusters).toContain('app-stack-detailThree');
const accountSelectComponent = component.find('Select[name="credentials"] .Select-control input');
accountSelectComponent.simulate('mouseDown');
accountSelectComponent.simulate('change', { target: { value: 'account-name-two' } });
accountSelectComponent.simulate('keyDown', { keyCode: 9, key: 'Tab' });
$scope.$digest();
expect(component.state().availableRegions.length).toBe(1, 'number of available regions does not match');
expect(component.state().availableRegions).toContain('region-two');
expect(component.state().clusters.length).toBe(0, 'number of clusters does not match');
expect(region).toEqual('', 'selected region is not cleared');
expect(regions.length).toBe(0, 'selected regions list is not cleared');
expect(credentials).toContain('account-name-two');
expect(cluster).toBeUndefined('selected cluster is not cleared');
});
it('retrieves the correct list of clusters when the selector is multi-region and the region is changed', () => {
let regions: string[] = [];
let cluster = 'SHOULD-CHANGE';
const accountRegionClusterProps: IAccountRegionClusterSelectorProps = {
accounts: [
{
accountId: 'account-id-two',
name: 'account-name-two',
requiredGroupMembership: [],
type: 'account-type',
},
{
accountId: 'account-id-one',
name: 'account-name-one',
requiredGroupMembership: [],
type: 'account-type',
},
],
application,
cloudProvider: 'cloud-provider',
clusterField: 'newCluster',
onComponentUpdate: (value: any) => {
regions = value.regions;
cluster = value.newCluster;
},
component: {
credentials: 'account-name-one',
regions: ['region-one'],
},
};
const component = mount<AccountRegionClusterSelector>(
<AccountRegionClusterSelector {...accountRegionClusterProps} />,
);
$scope.$digest();
expect(component.state().availableRegions.length).toBe(3, 'number of available regions does not match');
expect(component.state().availableRegions).toContain('region-one');
expect(component.state().availableRegions).toContain('region-two');
expect(component.state().availableRegions).toContain('region-three');
expect(component.state().clusters.length).toBe(2, 'number of clusters does not match');
expect(component.state().clusters).toContain('app-stack-detailOne');
expect(component.state().clusters).toContain('app-stack-detailThree');
const accountSelectComponent = component.find('Select[name="regions"] .Select-control input');
accountSelectComponent.simulate('mouseDown');
accountSelectComponent.simulate('change', { target: { value: 'region-three' } });
accountSelectComponent.simulate('keyDown', { keyCode: 9, key: 'Tab' });
$scope.$digest();
expect(component.state().clusters.length).toBe(3, 'number of clusters does not match');
expect(component.state().clusters).toContain('app-stack-detailOne');
expect(component.state().clusters).toContain('app-stack-detailThree');
expect(component.state().clusters).toContain('app-stack-detailFour');
expect(cluster).toBeUndefined('selected cluster is not cleared');
expect(regions.length).toBe(2);
expect(regions).toContain('region-one');
expect(regions).toContain('region-three');
});
it('retrieves the correct list of clusters on startup and the selector is single-region', () => {
const accountRegionClusterProps: IAccountRegionClusterSelectorProps = {
accounts: [
{
accountId: 'account-id-two',
name: 'account-name-two',
requiredGroupMembership: [],
type: 'account-type',
},
{
accountId: 'account-id-one',
name: 'account-name-one',
requiredGroupMembership: [],
type: 'account-type',
},
],
application,
cloudProvider: 'cloud-provider',
onComponentUpdate: (_value: any) => {},
component: {
cluster: 'app-stack-detailOne',
credentials: 'account-name-one',
region: 'region-one',
},
isSingleRegion: true,
};
const component = mount<AccountRegionClusterSelector>(
<AccountRegionClusterSelector {...accountRegionClusterProps} />,
);
$scope.$digest();
expect(component.state().availableRegions.length).toBe(3, 'number of available regions does not match');
expect(component.state().availableRegions).toContain('region-one');
expect(component.state().availableRegions).toContain('region-two');
expect(component.state().availableRegions).toContain('region-three');
expect(component.state().clusters.length).toBe(2, 'number of clusters does not match');
expect(component.state().clusters).toContain('app-stack-detailOne');
expect(component.state().clusters).toContain('app-stack-detailThree');
});
it('the cluster value is updated in the component when cluster is changed', () => {
let cluster = '';
let moniker: IMoniker = { app: '' };
const accountRegionClusterProps: IAccountRegionClusterSelectorProps = {
accounts: [
{
accountId: 'account-id-two',
name: 'account-name-two',
requiredGroupMembership: [],
type: 'account-type',
},
{
accountId: 'account-id-one',
name: 'account-name-one',
requiredGroupMembership: [],
type: 'account-type',
},
],
application,
cloudProvider: 'cloud-provider',
clusterField: 'newCluster',
onComponentUpdate: (value: any) => {
cluster = value.newCluster;
moniker = value.moniker;
},
component: {
cluster: 'app-stack-detailOne',
credentials: 'account-name-one',
regions: ['region-one'],
},
};
const expectedMoniker = {
app: 'my-app',
cluster: 'app-stack-detailThree',
detail: 'my-detail',
stack: 'my-stack',
sequence: null,
} as IMoniker;
const component = mount<AccountRegionClusterSelector>(
<AccountRegionClusterSelector {...accountRegionClusterProps} />,
);
$scope.$digest();
expect(component.state().availableRegions.length).toBe(3, 'number of available regions does not match');
expect(component.state().availableRegions).toContain('region-one');
expect(component.state().availableRegions).toContain('region-two');
expect(component.state().availableRegions).toContain('region-three');
expect(component.state().clusters.length).toBe(2, 'number of clusters does not match');
expect(component.state().clusters).toContain('app-stack-detailOne');
expect(component.state().clusters).toContain('app-stack-detailThree');
const clusterSelectComponent = component.find('Select[name="newCluster"] .Select-control input');
clusterSelectComponent.simulate('mouseDown');
clusterSelectComponent.simulate('change', { target: { value: 'app-stack-detailThree' } });
clusterSelectComponent.simulate('keyDown', { keyCode: 9, key: 'Tab' });
$scope.$digest();
expect(cluster).toBe('app-stack-detailThree');
expect(moniker).toEqual(expectedMoniker);
});
it('the cluster value is updated in the component when cluster is changed to freeform value', () => {
let cluster = '';
let moniker: IMoniker = { app: '' };
const accountRegionClusterProps: IAccountRegionClusterSelectorProps = {
accounts: [
{
accountId: 'account-id-two',
name: 'account-name-two',
requiredGroupMembership: [],
type: 'account-type',
},
{
accountId: 'account-id-one',
name: 'account-name-one',
requiredGroupMembership: [],
type: 'account-type',
},
],
application,
cloudProvider: 'cloud-provider',
clusterField: 'newCluster',
onComponentUpdate: (value: any) => {
cluster = value.newCluster;
moniker = value.moniker;
},
component: {
cluster: 'app-stack-detailOne',
credentials: 'account-name-one',
regions: ['region-one'],
},
};
const component = mount<AccountRegionClusterSelector>(
<AccountRegionClusterSelector {...accountRegionClusterProps} />,
);
$scope.$digest();
const clusterSelectComponent = component.find('Select[name="newCluster"] .Select-control input');
clusterSelectComponent.simulate('mouseDown');
clusterSelectComponent.simulate('change', { target: { value: 'app-stack-freeform' } });
clusterSelectComponent.simulate('keyDown', { keyCode: 9, key: 'Tab' });
$scope.$digest();
expect(cluster).toBe('app-stack-freeform');
expect(moniker).toBeUndefined();
expect(component.state().clusters).toContain('app-stack-freeform');
});
it('initialize with form names', () => {
const accountRegionClusterProps: IAccountRegionClusterSelectorProps = {
accounts: [
{
accountId: 'account-id-one',
name: 'account-name-one',
requiredGroupMembership: [],
type: 'account-type',
},
],
application,
cloudProvider: 'cloud-provider',
onComponentUpdate: noop,
componentName: 'form',
component: {
credentials: 'account-name-one',
regions: ['region-one'],
},
};
const component = shallow(<AccountRegionClusterSelector {...accountRegionClusterProps} />);
$scope.$digest();
expect(component.find('Select[name="form.credentials"]').length).toBe(1, 'select for account not found');
expect(component.find('Select[name="form.regions"]').length).toBe(1, 'select for regions not found');
expect(component.find('StageConfigField [name="form.cluster"]').length).toBe(1, 'select for cluster not found');
});
});
|
apache-2.0
|
awajid/daytrader
|
assemblies/javaee/dojo-ui-web/src/main/webapp/widget/Context.js
|
4087
|
<%--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--%>
dojo.provide("dojotrader.widget.Context");
dojo.require("dojo.collections.*");
dojo.require("dojo.lang.timing.Timer");
dojotrader.widget.Context = function(userID){
this._user = userID;
this._quotesCache = new dojo.collections.Dictionary();
this._quotesToUpdate = 0;
this._updateTimer = null;
this.startUpdateTimer = function(interval) {
this._updateTimer = new dojo.lang.timing.Timer(interval);
this._updateTimer.onTick = dojo.lang.hitch(this,this._updateQuotesCache);
this._updateTimer.start();
};
this.stopUpdateTimer = function() {
this._updateTimer.stop();
this._updateTimer = null;
};
this._addQuoteToCache = function(quote) {
this._quotesCache.add(quote.symbol, quote);
//this.onQuoteAddComplete(quote);
};
this.getQuoteFromCache = function(symbol) {
//alert("getQuoteFromCache");
value = null;
if (this._quotesCache.contains(symbol)){
value = this._quotesCache.entry(symbol).value;
} else {
this._getQuoteFromServer(symbol);
}
return value;
};
this._getQuoteFromServer = function(symbol) {
//alert("_getQuoteFromServer");
dojo.io.bind({
method: "GET",
//url: "/proxy/SoapProxy/getQuote?p1=" + symbol.value + "&format=json",
url: "/daytraderProxy/doProxy/getQuote?p1=" + symbol,
mimetype: "text/json",
load: dojo.lang.hitch(this, this._handleQuote),
error: dojo.lang.hitch(this, this._handleError),
useCache: false,
preventCache: true
});
};
this._getQuoteFromServerForUpdate = function(symbol) {
//alert("_getQuoteFromServer");
dojo.io.bind({
method: "GET",
//url: "/proxy/SoapProxy/getQuote?p1=" + symbol.value + "&format=json",
url: "/daytraderProxy/doProxy/getQuote?p1=" + symbol,
mimetype: "text/json",
load: dojo.lang.hitch(this, this._handleQuoteUpdate),
error: dojo.lang.hitch(this, this._handleError),
useCache: false,
preventCache: true
});
};
this._handleQuote = function(type, data, evt) {
//alert("_handleQuote");
this._addQuoteToCache(data.getQuoteReturn);
this.onQuoteAddComplete(data.getQuoteReturn);
dojo.event.topic.publish("/quotes", {action: "add", quote: data.getQuoteReturn});
};
this._handleQuoteUpdate = function(type, data, evt) {
//alert("_handleQuote");
newQuote = data.getQuoteReturn;
// check for quote equality - only update if they are different
oldQuote = this._quotesCache.entry(newQuote.symbol).value;
if (oldQuote.price != newQuote.price || oldQuote.change != newQuote.change) {
this._addQuoteToCache(newQuote);
dojo.event.topic.publish("/quotes", {action: "update", quote: newQuote});
}
this._quotesToUpdate++;
if (this._quotesCache.count == this._quotesToUpdate) {
//alert("Refresh Complete: " + this._quotesCache.count + " - " + this._quotesToUpdate);
this.onQuotesUpdateComplete();
}
};
this._updateQuotesCache = function() {
this._quotesToUpdate = 0;
keys = this._quotesCache.getKeyList();
for (idx = 0; idx < keys.length; idx++) {
this._getQuoteFromServerForUpdate(keys[idx]);
}
};
this.onQuotesUpdateComplete = function() {};
this.onQuoteAddComplete = function() {}
};
|
apache-2.0
|
wateryan/matrix-java
|
src/main/java/com/wateryan/matrix/api/Version.java
|
142
|
package com.wateryan.matrix.api;
public class Version {
public static final String R_0 = "r0";
public static final String V_1 = "v1";
}
|
apache-2.0
|
dcloudio/uni-app
|
packages/uni-template-compiler/__tests__/compiler-mp-kuaishou.spec.js
|
3824
|
const compiler = require('../lib')
function assertCodegen (template, templateCode, renderCode = 'with(this){}', options = {}) {
const res = compiler.compile(template, {
resourcePath: 'test.wxml',
mp: Object.assign({
minified: true,
isTest: true,
platform: 'mp-kuaishou'
}, options)
})
expect(res.template).toBe(templateCode)
if (typeof renderCode === 'function') {
renderCode(res)
} else {
expect(res.render).toBe(renderCode)
}
}
describe('mp:compiler-mp-kuaishou', () => {
it('generate class', () => {
assertCodegen(
'<view class="a external-class c" :class="class1">hello world</view>',
'<view class="{{[\'a\',\'external-class\',\'c\',class1]}}">hello world</view>'
)
})
it('generate scoped slot', () => {
assertCodegen(
'<foo><template slot-scope="{bar}">{{ bar.foo }}</template></foo>',
'<foo generic:scoped-slots-default="test-foo-default" vue-id="551070e6-1" bind:__l="__l" vue-slots="{{[\'default\']}}"></foo>',
function (res) {
expect(res.generic[0]).toBe('test-foo-default')
}
)
assertCodegen(
'<foo><view slot-scope="{bar}">{{ bar.foo }}</view></foo>',
'<foo generic:scoped-slots-default="test-foo-default" vue-id="551070e6-1" bind:__l="__l" vue-slots="{{[\'default\']}}"></foo>',
function (res) {
expect(res.generic[0]).toBe('test-foo-default')
}
)
})
it('generate named scoped slot', () => {
assertCodegen(
'<foo><template slot="foo" slot-scope="{bar}">{{ bar.foo }}</template></foo>',
'<foo generic:scoped-slots-foo="test-foo-foo" vue-id="551070e6-1" bind:__l="__l" vue-slots="{{[\'foo\']}}"></foo>',
function (res) {
expect(res.generic[0]).toBe('test-foo-foo')
}
)
assertCodegen(
'<foo><view slot="foo" slot-scope="{bar}">{{ bar.foo }}</view></foo>',
'<foo generic:scoped-slots-foo="test-foo-foo" vue-id="551070e6-1" bind:__l="__l" vue-slots="{{[\'foo\']}}"></foo>',
function (res) {
expect(res.generic[0]).toBe('test-foo-foo')
}
)
})
it('generate scoped slot with multiline v-if', () => {
assertCodegen(
'<foo><template v-if="\nshow\n" slot-scope="{bar}">{{ bar.foo }}</template></foo>',
'<foo generic:scoped-slots-default="test-foo-default" vue-id="551070e6-1" bind:__l="__l" vue-slots="{{[\'default\']}}"></foo>',
function (res) {
expect(res.generic[0]).toBe('test-foo-default')
}
)
assertCodegen(
'<foo><view v-if="\nshow\n" slot="foo" slot-scope="{bar}">{{ bar.foo }}</view></foo>',
'<foo generic:scoped-slots-foo="test-foo-foo" vue-id="551070e6-1" bind:__l="__l" vue-slots="{{[\'foo\']}}"></foo>',
function (res) {
expect(res.generic[0]).toBe('test-foo-foo')
}
)
})
it('generate scoped slot', () => {
assertCodegen(// TODO vue-id
'<span><slot v-bind:user="user">{{ user.lastName }}</slot></span>',
'<label class="_span"><block ks:if="{{$slots.default}}"><slot></slot><scoped-slots-default user="{{user}}" bind:__l="__l"></scoped-slots-default></block><block ks:else>{{user.lastName}}</block></label>',
function (res) {
expect(res.componentGenerics['scoped-slots-default']).toBe(true)
}
)
assertCodegen(
'<span><slot name="header" v-bind:user="user">{{ user.lastName }}</slot></span>',
'<label class="_span"><block ks:if="{{$slots.header}}"><slot name="header"></slot><scoped-slots-header user="{{user}}" bind:__l="__l"></scoped-slots-header></block><block ks:else>{{user.lastName}}</block></label>',
function (res) {
expect(res.componentGenerics['scoped-slots-header']).toBe(true)
}
)
})
})
|
apache-2.0
|
LorenzReinhart/ONOSnew
|
drivers/cisco/netconf/src/main/java/org/onosproject/drivers/cisco/TextBlockParserCisco.java
|
11067
|
/*
* Copyright 2016-present Open Networking Laboratory
*
* 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.onosproject.drivers.cisco;
import com.google.common.collect.Lists;
import org.onosproject.net.AnnotationKeys;
import org.onosproject.net.DefaultAnnotations;
import org.onosproject.net.PortNumber;
import org.onosproject.net.device.DefaultPortDescription;
import org.onosproject.net.device.PortDescription;
import java.util.Arrays;
import java.util.List;
import static org.onosproject.net.Port.Type;
/**
*Parser for Netconf XML configurations and replys as plain text.
*/
final class TextBlockParserCisco {
private static final String PHRASE = "bytes of memory.";
private static final String VERSION = "Version ";
private static final String EOF_VERSION1 = "Software";
private static final String EOF_VERSION2 = "Software,";
private static final String EOF_VERSION3 = "RELEASE";
private static final String PROCESSOR_BOARD = "Processor board ID ";
private static final String BANDWIDTH = "BW ";
private static final String SPEED = " Kbit/sec";
private static final String ETHERNET = "Eth";
private static final String FASTETHERNET = "Fas";
private static final String GIGABITETHERNET = "Gig";
private static final String FDDI = "Fdd";
private static final String POS = "POS";
private static final String SERIAL = "Ser";
private static final String NEWLINE_SPLITTER = "\n";
private static final String PORT_DELIMITER = "/";
private static final String SPACE = " ";
private static final String IS_UP = "is up, line protocol is up";
private static final List INTERFACES = Arrays.asList(ETHERNET, FASTETHERNET, GIGABITETHERNET, SERIAL, FDDI, POS);
private static final List FIBERINTERFACES = Arrays.asList(FDDI, POS);
private TextBlockParserCisco() {
//not called
}
/**
* Adding information in an array for CiscoIosDeviceDescriptin call.
* @param version the return of show version command
* @return the array with the information
*/
static String[] parseCiscoIosDeviceDetails(String version) {
String[] details = new String[4];
details[0] = getManufacturer(version);
details[1] = getHwVersion(version);
details[2] = getSwVersion(version);
details[3] = serialNumber(version);
return details;
}
/**
* Retrieving manufacturer of device.
* @param version the return of show version command
* @return the manufacturer of the device
*/
private static String getManufacturer(String version) {
int i;
String[] textStr = version.split(NEWLINE_SPLITTER);
String[] lineStr = textStr[0].trim().split(SPACE);
return lineStr[0];
}
/**
* Retrieving hardware version of device.
* @param version the return of show version command
* @return the hardware version of the device
*/
private static String getHwVersion(String version) {
String[] textStr = version.split(NEWLINE_SPLITTER);
String processor = SPACE;
int i;
for (i = 0; i < textStr.length; i++) {
if (textStr[i].indexOf(PHRASE) > 0) {
String[] lineStr = textStr[i].trim().split(SPACE);
processor = lineStr[1];
break;
} else {
processor = SPACE;
}
}
return processor;
}
/**
* Retrieving software version of device.
* @param version the return of show version command
* @return the software version of the device
*/
private static String getSwVersion(String version) {
String[] textStr = version.split(NEWLINE_SPLITTER);
int i;
for (i = 0; i < textStr.length; i++) {
if (textStr[i].indexOf(VERSION) > 0) {
break;
}
}
String[] lineStr = textStr[i].trim().split(SPACE);
StringBuilder sw = new StringBuilder();
for (int j = 0; j < lineStr.length; j++) {
if (lineStr[j].equals(EOF_VERSION1) || lineStr[j].equals(EOF_VERSION2)
) {
sw.append(lineStr[j - 1]).append(SPACE);
} else if (lineStr[j].equals(EOF_VERSION3)) {
sw.append(lineStr[j - 1]);
sw.setLength(sw.length() - 1);
}
}
return sw.toString();
}
/**
* Retrieving serial number of device.
* @param version the return of show version command
* @return the serial number of the device
*/
private static String serialNumber(String version) {
String[] textStr = version.split(NEWLINE_SPLITTER);
int i;
for (i = 0; i < textStr.length; i++) {
if (textStr[i].indexOf(PROCESSOR_BOARD) > 0) {
break;
}
}
return textStr[i].substring(textStr[i].indexOf(PROCESSOR_BOARD) + PROCESSOR_BOARD.length(),
textStr[i].length());
}
/**
* Calls methods to create information about Ports.
* @param interfacesReply the interfaces as plain text
* @return the Port description list
*/
public static List<PortDescription> parseCiscoIosPorts(String interfacesReply) {
String parentInterface;
String[] parentArray;
String tempString;
List<PortDescription> portDesc = Lists.newArrayList();
int interfacesCounter = interfacesCounterMethod(interfacesReply);
for (int i = 0; i < interfacesCounter; i++) {
parentInterface = parentInterfaceMethod(interfacesReply);
portDesc.add(findPortInfo(parentInterface));
parentArray = parentInterface.split(SPACE);
tempString = parentArray[0] + SPACE;
interfacesReply = interfacesReply.replace(tempString, SPACE + tempString);
}
return portDesc;
}
/**
* Creates the port information object.
* @param interfaceTree the interfaces as plain text
* @return the Port description object
*/
private static DefaultPortDescription findPortInfo(String interfaceTree) {
String[] textStr = interfaceTree.split(NEWLINE_SPLITTER);
String[] firstLine = textStr[0].split(SPACE);
String firstWord = firstLine[0];
Type type = getPortType(textStr);
boolean isEnabled = getIsEnabled(textStr);
String port = getPort(textStr);
long portSpeed = getPortSpeed(textStr);
DefaultAnnotations.Builder annotations = DefaultAnnotations.builder()
.set(AnnotationKeys.PORT_NAME, firstWord);
return "-1".equals(port) ? null : new DefaultPortDescription(PortNumber.portNumber(port),
isEnabled, type, portSpeed, annotations.build());
}
/**
* Counts the number of existing interfaces.
* @param interfacesReply the interfaces as plain text
* @return interfaces counter
*/
private static int interfacesCounterMethod(String interfacesReply) {
int counter;
String first3Characters;
String[] textStr = interfacesReply.split(NEWLINE_SPLITTER);
int lastLine = textStr.length - 1;
counter = 0;
for (int i = 1; i < lastLine; i++) {
first3Characters = textStr[i].substring(0, 3);
if (INTERFACES.contains(first3Characters)) {
counter++;
}
}
return counter;
}
/**
* Parses the text and seperates to Parent Interfaces.
* @param interfacesReply the interfaces as plain text
* @return Parent interface
*/
private static String parentInterfaceMethod(String interfacesReply) {
String firstCharacter;
String first3Characters;
boolean isChild = false;
StringBuilder anInterface = new StringBuilder("");
String[] textStr = interfacesReply.split("\\n");
int lastLine = textStr.length - 1;
for (int i = 1; i < lastLine; i++) {
firstCharacter = textStr[i].substring(0, 1);
first3Characters = textStr[i].substring(0, 3);
if (!(firstCharacter.equals(SPACE)) && isChild) {
break;
} else if (firstCharacter.equals(SPACE) && isChild) {
anInterface.append(textStr[i]).append(NEWLINE_SPLITTER);
} else if (INTERFACES.contains(first3Characters)) {
isChild = true;
anInterface.append(textStr[i]).append(NEWLINE_SPLITTER);
}
}
return anInterface.toString();
}
/**
* Get the port type for an interface.
* @param textStr interface splitted as an array
* @return Port type
*/
private static Type getPortType(String[] textStr) {
String first3Characters;
first3Characters = textStr[0].substring(0, 3);
return FIBERINTERFACES.contains(first3Characters) ? Type.FIBER : Type.COPPER;
}
/**
* Get the state for an interface.
* @param textStr interface splitted as an array
* @return isEnabled state
*/
private static boolean getIsEnabled(String[] textStr) {
return textStr[0].contains(IS_UP);
}
/**
* Get the port number for an interface.
* @param textStr interface splitted as an array
* @return port number
*/
private static String getPort(String[] textStr) {
String port;
try {
if (textStr[0].indexOf(PORT_DELIMITER) > 0) {
port = textStr[0].substring(textStr[0].lastIndexOf(PORT_DELIMITER) + 1,
textStr[0].indexOf(SPACE));
} else {
port = "-1";
}
} catch (RuntimeException e) {
port = "-1";
}
return port;
}
/**
* Get the port speed for an interface.
* @param textStr interface splitted as an array
* @return port speed
*/
private static long getPortSpeed(String[] textStr) {
long portSpeed = 0;
String result;
int lastLine = textStr.length - 1;
for (int i = 0; i < lastLine; i++) {
if ((textStr[i].indexOf(BANDWIDTH) > 0) && (textStr[i].indexOf(SPEED) > 0)) {
result = textStr[i].substring(textStr[i].indexOf(BANDWIDTH) + 3, textStr[i].indexOf(SPEED));
portSpeed = Long.valueOf(result);
break;
}
}
return portSpeed;
}
}
|
apache-2.0
|
Hincoin/folly
|
folly/Uri.h
|
4076
|
/*
* Copyright 2016 Facebook, 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.
*/
#ifndef FOLLY_URI_H_
#define FOLLY_URI_H_
#include <folly/String.h>
#include <vector>
namespace folly {
/**
* Class representing a URI.
*
* Consider http://www.facebook.com/foo/bar?key=foo#anchor
*
* The URI is broken down into its parts: scheme ("http"), authority
* (ie. host and port, in most cases: "www.facebook.com"), path
* ("/foo/bar"), query ("key=foo") and fragment ("anchor"). The scheme is
* lower-cased.
*
* If this Uri represents a URL, note that, to prevent ambiguity, the component
* parts are NOT percent-decoded; you should do this yourself with
* uriUnescape() (for the authority and path) and uriUnescape(...,
* UriEscapeMode::QUERY) (for the query, but probably only after splitting at
* '&' to identify the individual parameters).
*/
class Uri {
public:
/**
* Parse a Uri from a string. Throws std::invalid_argument on parse error.
*/
explicit Uri(StringPiece str);
const fbstring& scheme() const { return scheme_; }
const fbstring& username() const { return username_; }
const fbstring& password() const { return password_; }
/**
* Get host part of URI. If host is an IPv6 address, square brackets will be
* returned, for example: "[::1]".
*/
const fbstring& host() const { return host_; }
/**
* Get host part of URI. If host is an IPv6 address, square brackets will not
* be returned, for exmaple "::1"; otherwise it returns the same thing as
* host().
*
* hostname() is what one needs to call if passing the host to any other tool
* or API that connects to that host/port; e.g. getaddrinfo() only understands
* IPv6 host without square brackets
*/
fbstring hostname() const;
uint16_t port() const { return port_; }
const fbstring& path() const { return path_; }
const fbstring& query() const { return query_; }
const fbstring& fragment() const { return fragment_; }
fbstring authority() const;
template <class String>
String toString() const;
std::string str() const { return toString<std::string>(); }
fbstring fbstr() const { return toString<fbstring>(); }
void setPort(uint16_t port) {
hasAuthority_ = true;
port_ = port;
}
/**
* Get query parameters as key-value pairs.
* e.g. for URI containing query string: key1=foo&key2=&key3&=bar&=bar=
* In returned list, there are 3 entries:
* "key1" => "foo"
* "key2" => ""
* "key3" => ""
* Parts "=bar" and "=bar=" are ignored, as they are not valid query
* parameters. "=bar" is missing parameter name, while "=bar=" has more than
* one equal signs, we don't know which one is the delimiter for key and
* value.
*
* Note, this method is not thread safe, it might update internal state, but
* only the first call to this method update the state. After the first call
* is finished, subsequent calls to this method are thread safe.
*
* @return query parameter key-value pairs in a vector, each element is a
* pair of which the first element is parameter name and the second
* one is parameter value
*/
const std::vector<std::pair<fbstring, fbstring>>& getQueryParams();
private:
fbstring scheme_;
fbstring username_;
fbstring password_;
fbstring host_;
bool hasAuthority_;
uint16_t port_;
fbstring path_;
fbstring query_;
fbstring fragment_;
std::vector<std::pair<fbstring, fbstring>> queryParams_;
};
} // namespace folly
#include <folly/Uri-inl.h>
#endif /* FOLLY_URI_H_ */
|
apache-2.0
|
bitExpert/etcetera
|
src/bitExpert/Etcetera/Reader/File/Excel/LegacyExcelReader.php
|
3095
|
<?php
declare(strict_types = 1);
/*
* This file is part of the Etcetera package.
*
* (c) bitExpert AG
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace bitExpert\Etcetera\Reader\File\Excel;
/**
* Generic implementation of an {@link \bitExpert\Etcetera\Reader\Reader} for
* legacy Microsoft Excel files.
*/
class LegacyExcelReader extends AbstractExcelReader
{
/**
* {@inheritDoc}
*/
public function read()
{
$inputFileName = $this->filename;
try {
$inputFileType = \PHPExcel_IOFactory::identify($inputFileName);
$objReader = \PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch (\Exception $e) {
die(sprintf(
'Error loading file "%s": %s',
pathinfo($inputFileName, PATHINFO_BASENAME),
$e->getMessage()
));
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
if (0 !== $this->offset) {
//@todo implement
throw new \InvalidArgumentException('Offset is not yet supported');
}
$properties = [];
for ($rowIndex = 1; $rowIndex <= $highestRow; $rowIndex++) {
$values = $sheet->rangeToArray(
'A' . $rowIndex . ':' . $highestColumn . $rowIndex,
null,
null,
false
);
$values = $values[0];
if ($this->headerDetector->isHeader($rowIndex, $values)) {
$properties = $this->describeProperties($values);
continue;
}
if ($rowIndex < $this->offset) {
continue;
}
if (!count($properties)) {
continue;
}
$this->processValues($properties, $values);
}
}
/**
* @param string $filename
* @return \PHPExcel_Reader_IReader
*/
protected function getPhpExcelReader(string $filename)
{
$this->setPhpExcelConfigurations();
$reader = \PHPExcel_IOFactory::createReaderForFile($filename);
$instanceName = \get_class($reader);
switch ($instanceName) {
case 'PHPExcel_Reader_Excel2007':
case 'PHPExcel_Reader_Excel5':
case 'PHPExcel_Reader_OOCalc':
/* @var $reader \PHPExcel_Reader_Excel2007 */
$reader->setReadDataOnly(true);
break;
}
$phpExcel = $reader->load($filename);
return $phpExcel;
}
/**
* Set PHP Excel configurations
*/
protected function setPhpExcelConfigurations()
{
// set caching configuration
$cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_in_memory;
\PHPExcel_Settings::setCacheStorageMethod(
$cacheMethod
);
}
}
|
apache-2.0
|
afs/jena-workspace
|
src/main/java/rdf_star/DevRDFStar.java
|
10152
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rdf_star;
import java.util.function.Predicate;
import org.apache.jena.atlas.lib.NotImplemented;
import org.apache.jena.atlas.lib.StrUtils;
import org.apache.jena.atlas.lib.tuple.Tuple;
import org.apache.jena.atlas.logging.LogCtl;
import org.apache.jena.graph.Graph;
import org.apache.jena.graph.GraphUtil;
import org.apache.jena.graph.Node;
import org.apache.jena.graph.Triple;
import org.apache.jena.graph.impl.GraphPlain;
import org.apache.jena.query.*;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.RIOT;
import org.apache.jena.sparql.core.DatasetGraph;
import org.apache.jena.sparql.core.DatasetGraphFactory;
import org.apache.jena.sparql.core.Quad;
import org.apache.jena.sparql.engine.binding.Binding;
import org.apache.jena.sparql.engine.binding.BindingFactory;
import org.apache.jena.sparql.engine.main.solver.SolverRX3;
import org.apache.jena.sparql.engine.main.solver.SolverRX4;
import org.apache.jena.sparql.sse.SSE;
import org.apache.jena.sparql.util.QueryExecUtils;
import org.apache.jena.sys.JenaSystem;
import org.apache.jena.system.Txn;
import org.apache.jena.tdb.TDBFactory;
import org.apache.jena.tdb2.DatabaseMgr;
import org.apache.jena.tdb2.TDB2Factory;
import org.apache.jena.tdb2.solver.BindingNodeId;
import org.apache.jena.tdb2.store.NodeId;
import org.apache.jena.tdb2.sys.SystemTDB;
public class DevRDFStar {
static {
JenaSystem.init();
LogCtl.setLog4j2();
RIOT.getContext().set(RIOT.symTurtleDirectiveStyle, "sparql");
}
public static void main(String...a) {
// runFile();
// runInline();
// System.exit(0);
//runDataAccess();
runInline();
System.exit(0);
}
public static void runInline(String...a) {
Dataset dataset = TDB2Factory.createDataset();
Predicate<Tuple<NodeId>> filter = tuple -> false;
DatasetGraph dsgtdb2 = dataset.asDatasetGraph();
dsgtdb2.getContext().set(SystemTDB.symTupleFilter, filter);
String data = StrUtils.strjoinNL("(dataset"
," (_ <<:a :b :c>> :p 'abc')"
,")");
String qs = "SELECT * { <<?a ?b ?c>> ?p 'abc'}";
Query query = QueryFactory.create(qs);
Txn.executeWrite(dataset, ()->{
DatasetGraph dsg = SSE.parseDatasetGraph(data);
dataset.asDatasetGraph().addAll(dsg);
QueryExecution qExec = QueryExecutionFactory.create(query, dataset);
//qExec.getContext().set(TDB2.symUnionDefaultGraph, true);
QueryExecUtils.executeQuery(qExec);
});
}
public static void runFile() {
//Dataset dataset = TDB2Factory.createDataset();
Dataset dataset = DatasetFactory.create();
// String DIR = "/home/afs/W3C/rdf-star/tests/sparql/eval/";
// String DATA = DIR+"data-4.trig";
// String QUERY = DIR+"sparql-star-graphs-1.rq";
String DIR = "/home/afs/ASF/afs-jena/jena-arq/testing/ARQ/ExprBuiltIns";
String DATA = DIR+"/data-builtin-2.ttl";
String QUERY = DIR+"/q-lang-3.rq"; // Dataset general only?
Query query = QueryFactory.read(QUERY);
System.out.println(query);
Txn.executeWrite(dataset, ()->{
Graph plain = GraphPlain.plain();
RDFDataMgr.read(plain, DATA);
Dataset dataset2 = DatasetFactory.wrap(DatasetGraphFactory.wrap(plain));
//RDFDataMgr.read(dataset, DATA);
//Dataset dataset2 = dataset;
//GraphPlain
QueryExecution qExec = QueryExecutionFactory.create(query, dataset2);
QueryExecUtils.executeQuery(qExec);
});
arq.sparql.main("--data="+DATA, "--query="+QUERY);
System.exit(0);
}
public static void mainEngine(String...a) {
boolean USE_TDB2_QUERY = true;
boolean USE_TDB1_QUERY = true;
// Temp - force term into the node table.
String dataStr =
StrUtils.strjoinNL("(prefix ((: <http://example/>))",
" (graph",
" (:s :p :o )",
" (:s1 :p1 :o1 )",
" (:s2 :p2 :o2 )",
"))");
Graph terms = SSE.parseGraph(dataStr);
Graph graph1 = SSE.parseGraph("(prefix ((: <http://example/>)) (graph (<<:s :p :o >> :q :z) ))");
Graph graph2 = SSE.parseGraph("(prefix ((: <http://example/>)) (graph (<<:s0 :p0 :o0 >> :q :z) (<<:s :p :o >> :q :z) ( :s :p :o ) ( :s1 :p1 :o1 ) ))");
graph1.getPrefixMapping().setNsPrefix("", "http://example/");
graph2.getPrefixMapping().setNsPrefix("", "http://example/");
//String pattern = "{ <<:s ?p :o>> ?q :z . BIND('A' AS ?A) }";
// BIND(<<?s ?p ?o>> AS ?T)
//String pattern = "{ ?s ?p ?o {| :q ?z |} }";
String pattern = "{ <<:s :p ?o >> ?q ?z . }";
String qs = "PREFIX : <http://example/> SELECT * "+pattern;
Query query = QueryFactory.create(qs);
Graph graph = graph1;
// // In-memory
if ( false )
{
// TEST
System.out.println("== Basic test");
Triple tData = SSE.parseTriple("(<<:s :p :o >> :q :z)");
Triple tPattern = SSE.parseTriple("(<<:s ?p ?o >> ?q ?z)");
//Binding input = BindingFactory.binding(Var.alloc("p"), SSE.parseNode(":pz"));
Binding input = BindingFactory.binding();
Binding b1 = SolverRX3.matchTriple(input, tData, tPattern);
System.out.println(b1);
Quad qData = SSE.parseQuad("(:g <<:s :p :o >> :q :z)");
Node qGraph = SSE.parseNode(":g");
Triple qPattern = tPattern;
Binding b2 = SolverRX4.matchQuad(input, qData, qGraph, qPattern);
System.out.println(b2);
System.exit(0);
}
{
System.out.println("== In-memory");
QueryExecution qExec = QueryExecutionFactory.create(query, DatasetGraphFactory.wrap(graph));
QueryExecUtils.executeQuery(qExec);
}
if ( USE_TDB2_QUERY ) {
System.out.println("== TDB2/Query");
Predicate<BindingNodeId> filter = bnid -> true;
DatasetGraph dsgtdb2 = DatabaseMgr.createDatasetGraph();
dsgtdb2.getContext().set(SystemTDB.symTupleFilter, filter);
Txn.executeWrite(dsgtdb2, ()->GraphUtil.addInto(dsgtdb2.getDefaultGraph(), graph));
Txn.executeRead(dsgtdb2, ()->{
QueryExecution qExec = QueryExecutionFactory.create(query, dsgtdb2);
QueryExecUtils.executeQuery(qExec);
});
}
if ( USE_TDB1_QUERY ) {
System.out.println("== TDB1/Query");
try {
DatasetGraph dsgtdb1 = TDBFactory.createDatasetGraph();
Txn.executeWrite(dsgtdb1, ()-> GraphUtil.addInto(dsgtdb1.getDefaultGraph(), graph));
Txn.executeRead(dsgtdb1, ()->{
QueryExecution qExec = QueryExecutionFactory.create(query, dsgtdb1);
QueryExecUtils.executeQuery(qExec);
});
} catch (NotImplemented ex) {
System.out.println("Exception: "+ex.getClass().getName()+" : "+ex.getMessage());
}
}
}
// [RDFx]
// public static void main1(String...a) {
// // To/From NodeId space.
// //SolverRX.
//
// DatasetGraph dsg = DatasetGraphFactory.createTxnMem();
// RX.MODE_SA = false;
// RDFDataMgr.read(dsg, "/home/afs/tmp/D.ttl");
// String PREFIXES = "PREFIX : <http://example/>\n";
// String qs = PREFIXES+"SELECT * { <<:s ?p ?o >> :q :z . BIND('A' AS ?A) }";
// Query query = QueryFactory.create(qs);
// System.out.println("==== Query 1 ====");
// QueryExecution qExec1 = QueryExecutionFactory.create(query, dsg);
// QueryExecUtils.executeQuery(qExec1);
//
// System.out.println("==== Query 2 ====");
// RX.MODE_SA = true;
// QueryExecution qExec2 = QueryExecutionFactory.create(query, dsg);
// QueryExecUtils.executeQuery(qExec2);
//
//
// System.exit(0);
//
// ARQConstants.getGlobalPrefixMap().setNsPrefix("ex", "http://example/");
//
//// dwim(":x", "?v");
//// dwim("<< :s :p :o>>", "?v");
//// dwim("<< :s :p :o>>", "<< ?s ?p ?o>>");
//// dwim("<< <<:x :q :z>> :p :o>>", "<< ?s ?p ?o>>");
//// dwim("<< <<:x :q :z>> :p :o>>", "<< <<?x ?q ?z>> ?p ?o>>");
//
//// dwim("<< :s :p :o>>", "<< ?s :q ?o>>");
//// dwim("<< :s :p :o>>", "<< ?x ?p ?x>>");
//
//// dwim("<< <<:x :q :z>> :p :z>>", "<< <<?x ?q ?z>> ?p ?z>>");
//
// dwim("<< <<:x1 :q :z1>> :p <<:x2 :q :z2>> >>", "<< ?s :p <<?s2 ?q ?o2>> >>");
//
// }
//
// private static void dwim(String dataStr, String patternStr) {
// Node data = SSE.parseNode(dataStr);
// Node pattern = SSE.parseNode(patternStr);
// Binding r = RX_SA.match(BindingFactory.root(), data, pattern);
// //r.vars().forEachRemaining(v->
// System.out.println(NodeFmtLib.displayStr(data));
// System.out.println(NodeFmtLib.displayStr(pattern));
// System.out.println(" "+r);
// }
}
|
apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.