code stringlengths 5 1.01M | repo_name stringlengths 5 84 | path stringlengths 4 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 5 1.01M | input_ids listlengths 502 502 | token_type_ids listlengths 502 502 | attention_mask listlengths 502 502 | labels listlengths 502 502 |
|---|---|---|---|---|---|---|---|---|---|
#pragma once
#include "saiga/core/camera/camera.h"
#include "saiga/opengl/shader/basic_shaders.h"
#include "saiga/opengl/vertex.h"
#include "saiga/opengl/vertexBuffer.h"
#include "LinearMath/btIDebugDraw.h"
#include "btBulletDynamicsCommon.h"
namespace Saiga
{
class GLDebugDrawer : public btIDebugDraw
{
private:
int m_debugMode;
std::shared_ptr<MVPShader> lineShader;
VertexBuffer<VertexNC> lines;
std::vector<VertexNC> vertices;
public:
GLDebugDrawer();
virtual ~GLDebugDrawer();
void render(btDynamicsWorld* world, Camera* cam);
virtual void drawLine(const btVector3& from, const btVector3& to, const btVector3& fromColor,
const btVector3& toColor);
virtual void drawLine(const btVector3& from, const btVector3& to, const btVector3& color);
virtual void drawSphere(const btVector3& p, btScalar radius, const btVector3& color);
virtual void drawTriangle(const btVector3& a, const btVector3& b, const btVector3& c, const btVector3& color,
btScalar alpha);
virtual void drawContactPoint(const btVector3& PointOnB, const btVector3& normalOnB, btScalar distance,
int lifeTime, const btVector3& color);
virtual void reportErrorWarning(const char* warningString);
virtual void draw3dText(const btVector3& location, const char* textString);
virtual void setDebugMode(int debugMode);
virtual int getDebugMode() const { return m_debugMode; }
};
} // namespace Saiga
| darglein/saiga | samples/opengl/simpleBullet/bulletDebugDrawer.h | C | mit | 1,542 | [
30522,
1001,
10975,
8490,
2863,
2320,
1001,
2421,
1000,
18952,
3654,
1013,
4563,
1013,
4950,
1013,
4950,
1012,
1044,
30524,
19449,
1012,
1044,
1000,
1001,
2421,
1000,
18952,
3654,
1013,
2330,
23296,
1013,
19449,
8569,
12494,
1012,
1044,
100... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
* This file is part of the TA Buddy project.
* Copyright (c) 2013 Alexey Aksenov ezh@ezh.msk.ru
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Global License version 3
* as published by the Free Software Foundation with the addition of the
* following permission added to Section 15 as permitted in Section 7(a):
* FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED
* BY Limited Liability Company «MEZHGALAKTICHESKIJ TORGOVYJ ALIANS»,
* Limited Liability Company «MEZHGALAKTICHESKIJ TORGOVYJ ALIANS» DISCLAIMS
* THE WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Global License for more details.
* You should have received a copy of the GNU Affero General Global License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA, 02110-1301 USA, or download the license from the following URL:
* http://www.gnu.org/licenses/agpl.html
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Global License.
*
* In accordance with Section 7(b) of the GNU Affero General Global License,
* you must retain the producer line in every report, form or document
* that is created or manipulated using TA Buddy.
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial activities involving the TA Buddy software without
* disclosing the source code of your own applications.
* These activities include: offering paid services to customers,
* serving files in a web or/and network application,
* shipping TA Buddy with a closed source product.
*
* For more information, please contact Digimead Team at this
* address: ezh@ezh.msk.ru
*/
package org.digimead.tabuddy.desktop.logic.ui.wizard
import java.io.File
import java.net.URI
import java.util.concurrent.{ Callable, CancellationException, Exchanger }
import org.digimead.digi.lib.aop.log
import org.digimead.digi.lib.log.api.XLoggable
import org.digimead.tabuddy.desktop.core.definition.Operation
import org.digimead.tabuddy.desktop.core.support.App
import org.digimead.tabuddy.desktop.core.ui.definition.INewWizard
import org.digimead.tabuddy.desktop.core.{ Messages ⇒ CMessages }
import org.digimead.tabuddy.desktop.logic.Messages
import org.digimead.tabuddy.desktop.logic.operation.graph.OperationGraphNew
import org.digimead.tabuddy.desktop.logic.payload.marker.GraphMarker
import org.digimead.tabuddy.desktop.logic.payload.marker.api.XGraphMarker
import org.digimead.tabuddy.desktop.logic.payload.marker.serialization.encryption.Encryption
import org.digimead.tabuddy.desktop.logic.ui.support.digest.DigestAdapter
import org.digimead.tabuddy.desktop.logic.ui.support.encryption.EncryptionAdapter
import org.digimead.tabuddy.desktop.logic.ui.support.signature.SignatureAdapter
import org.digimead.tabuddy.model.Model
import org.digimead.tabuddy.model.graph.Graph
import org.eclipse.core.runtime.jobs.Job
import org.eclipse.jface.dialogs.ErrorDialog
import org.eclipse.jface.wizard.Wizard
/**
* New graph wizard.
*/
class NewGraphWizard extends Wizard with INewWizard with XLoggable {
/** The only available page. */
lazy val one = new NewGraphWizardPageOne()
setWindowTitle(Messages.NewGraphWizard_shellTitleEmpty_text)
/**
* Adds any last-minute pages to this wizard.
* <p>
* This method is called just before the wizard becomes visible, to give the
* wizard the opportunity to add any lazily created pages.
* </p>
*/
override def addPages() {
addPage(one)
}
/** This method is invoked before wizard opening. */
def init(argument: AnyRef) {}
/**
* Performs any actions appropriate in response to the user
* having pressed the Finish button, or refuse if finishing
* now is not permitted.
*
* Normally this method is only called on the container's
* current wizard. However if the current wizard is a nested wizard
* this method will also be called on all wizards in its parent chain.
* Such parents may use this notification to save state etc. However,
* the value the parents return from this method is ignored.
*
* @return <code>true</code> to indicate the finish request
* was accepted, and <code>false</code> to indicate
* that the finish request was refused
*/
@log
def performFinish() = {
try {
one.getGraphParameters() match {
case Some((graphName, graphContainer, containerEncryption, contentEncryption, digestAcquireField, digestFreezeField,
serializationType, signatureAcquireField, signatureFreezeField)) ⇒
/*
* Return Callable[GraphMarker] since OperationGraphNew blocks UI thread
*/
result = Some(new Callable[GraphMarker] {
def call = {
val exchanger = new Exchanger[Operation.Result[Graph[_ <: Model.Like]]]()
OperationGraphNew(graphName, new File(graphContainer), serializationType).foreach { operation ⇒
operation.getExecuteJob() match {
case Some(job) ⇒
job.setPriority(Job.LONG)
job.onComplete(exchanger.exchange).schedule()
case None ⇒
throw new RuntimeException(s"Unable to create job for ${operation}.")
}
}
exchanger.exchange(null) match {
case Operation.Result.OK(Some(graph), message) ⇒
val marker = GraphMarker(graph)
// containerEncryption
val containerEncryptionArgument = containerEncryption match {
case (EncryptionAdapter.Empty.identifier, _) ⇒ Map[URI, Encryption.Parameters]()
case (identifier, Some(parameters)) ⇒ Map[URI, Encryption.Parameters](marker.graphPath.toURI() -> parameters)
case (_, _) ⇒ Map[URI, Encryption.Parameters]()
}
marker.containerEncryption = XGraphMarker.Encryption(containerEncryptionArgument)
// contentEncryption
val contentEncryptionArgument = contentEncryption match {
case (EncryptionAdapter.Empty.identifier, _) ⇒ Map[URI, Encryption.Parameters]()
case (identifier, Some(parameters)) ⇒ Map[URI, Encryption.Parameters](marker.graphPath.toURI() -> parameters)
case (_, _) ⇒ Map[URI, Encryption.Parameters]()
}
marker.contentEncryption = XGraphMarker.Encryption(contentEncryptionArgument)
// digest
val digestAquire = digestAcquireField
val digestFreeze = digestFreezeField match {
case (DigestAdapter.Empty.identifier, _) ⇒ None
case (identifier, Some(parameters)) ⇒ Some(Map(marker.graphPath.toURI() -> parameters))
case (_, _) ⇒ None
}
marker.digest = XGraphMarker.Digest(digestAcquireField, digestFreeze)
// signature
val signatureAquire = signatureAcquireField match {
case NewGraphWizardPageOne.Acquire.Signature.SelectionRequired ⇒ None
case NewGraphWizardPageOne.Acquire.Signature.Disabled ⇒ None
case validator ⇒ Some(validator.id)
}
val signatureFreeze = signatureFreezeField match {
case (SignatureAdapter.Empty.identifier, _) ⇒ None
case (identifier, Some(parameters)) ⇒ Some(Map(marker.graphPath.toURI() -> parameters))
case (_, _) ⇒ None
}
marker.signature = XGraphMarker.Signature(signatureAquire, signatureFreeze)
log.info(s"Operation completed successfully.")
marker
case Operation.Result.OK(None, message) ⇒
throw new CancellationException(s"Operation canceled, reason: ${message}.")
case Operation.Result.Cancel(message) ⇒
throw new CancellationException(s"Operation canceled, reason: ${message}.")
case err: Operation.Result.Error[_] ⇒
throw err
case other ⇒
throw new RuntimeException(s"Unable to complete operation: ${other}.")
}
}
})
true
case None ⇒
log.fatal("Unable to get graph parameters.")
}
true
} catch {
case e: Throwable ⇒
val status = App.throwableToMultiStatus(e, App.bundle(getClass))
ErrorDialog.openError(one.getShell(), CMessages.error_text + ".",
Messages.NewGraphWizardPageOne_creationError_text, status)
false
}
}
}
| digimead/digi-TABuddy-desktop | part-logic/src/main/scala/org/digimead/tabuddy/desktop/logic/ui/wizard/NewGraphWizard.scala | Scala | agpl-3.0 | 9,371 | [
30522,
1013,
1008,
1008,
1008,
2023,
5371,
2003,
2112,
1997,
1996,
11937,
8937,
2622,
1012,
1008,
9385,
1006,
1039,
1007,
2286,
4074,
3240,
17712,
5054,
4492,
1041,
27922,
1030,
1041,
27922,
1012,
5796,
2243,
1012,
21766,
1008,
1008,
2023,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
"use strict";
System.register([], function (_export, _context) {
"use strict";
var ClickCounter;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
return {
setters: [],
execute: function () {
_export("ClickCounter", ClickCounter = function () {
function ClickCounter() {
_classCallCheck(this, ClickCounter);
this.count = 0;
}
ClickCounter.prototype.increment = function increment() {
this.count++;
};
return ClickCounter;
}());
_export("ClickCounter", ClickCounter);
}
};
}); | Hochfrequenz/aurelia-openui5-bridge | dist/system/click-counter.js | JavaScript | mit | 713 | [
30522,
1000,
2224,
9384,
1000,
1025,
2291,
1012,
4236,
1006,
1031,
1033,
1010,
3853,
1006,
1035,
9167,
1010,
1035,
6123,
1007,
1063,
1000,
2224,
9384,
1000,
1025,
13075,
11562,
3597,
16671,
2121,
1025,
3853,
1035,
2465,
9289,
29358,
11012,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#include <stdio.h>
#include "lame.h"
int main(int argc, char **argv) {
printf("get_lame_version(): %s\n", get_lame_version());
return 0;
}
| olliwang/makegyp | tests/lame/test.c | C | lgpl-3.0 | 146 | [
30522,
1001,
2421,
1026,
2358,
20617,
1012,
1044,
1028,
1001,
2421,
1000,
20342,
1012,
1044,
1000,
20014,
2364,
1006,
20014,
12098,
18195,
1010,
25869,
1008,
1008,
12098,
2290,
2615,
1007,
1063,
6140,
2546,
1006,
1000,
2131,
1035,
20342,
10... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#include <assert.h>
#include <pthread.h>
#include <stdint.h>
#include <time.h>
#include "../lib/includes.h"
#include "../lib/blacklist.h"
#include "../lib/logger.h"
#include "../lib/xalloc.h"
#include "iterator.h"
#include "aesrand.h"
#include "shard.h"
#include "state.h"
struct iterator {
cycle_t cycle;
uint8_t num_threads;
shard_t *thread_shards;
uint8_t *complete;
pthread_mutex_t mutex;
uint32_t curr_threads;
};
void shard_complete(uint8_t thread_id, void *arg)
{
iterator_t *it = (iterator_t *) arg;
assert(thread_id < it->num_threads);
pthread_mutex_lock(&it->mutex);
it->complete[thread_id] = 1;
it->curr_threads--;
shard_t *s = &it->thread_shards[thread_id];
zsend.sent += s->state.sent;
zsend.blacklisted += s->state.blacklisted;
zsend.whitelisted += s->state.whitelisted;
zsend.sendto_failures += s->state.failures;
uint8_t done = 1;
for (uint8_t i = 0; done && (i < it->num_threads); ++i) {
done = done && it->complete[i];
}
if (done) {
zsend.finish = now();
zsend.complete = 1;
zsend.first_scanned = it->thread_shards[0].state.first_scanned;
}
pthread_mutex_unlock(&it->mutex);
}
iterator_t* iterator_init(uint8_t num_threads, uint8_t shard,
uint8_t num_shards)
{
uint64_t num_addrs = blacklist_count_allowed();
iterator_t *it = xmalloc(sizeof(struct iterator));
const cyclic_group_t *group = get_group(num_addrs);
if (num_addrs > (1LL << 32)) {
zsend.max_index = 0xFFFFFFFF;
} else {
zsend.max_index = (uint32_t) num_addrs;
}
it->cycle = make_cycle(group, zconf.aes);
it->num_threads = num_threads;
it->curr_threads = num_threads;
it->thread_shards = xcalloc(num_threads, sizeof(shard_t));
it->complete = xcalloc(it->num_threads, sizeof(uint8_t));
pthread_mutex_init(&it->mutex, NULL);
for (uint8_t i = 0; i < num_threads; ++i) {
shard_init(&it->thread_shards[i],
shard,
num_shards,
i,
num_threads,
&it->cycle,
shard_complete,
it
);
}
zconf.generator = it->cycle.generator;
return it;
}
uint32_t iterator_get_sent(iterator_t *it)
{
uint32_t sent = 0;
for (uint8_t i = 0; i < it->num_threads; ++i) {
sent += it->thread_shards[i].state.sent;
}
return sent;
}
shard_t* get_shard(iterator_t *it, uint8_t thread_id)
{
assert(thread_id < it->num_threads);
return &it->thread_shards[thread_id];
}
uint32_t iterator_get_curr_send_threads(iterator_t *it)
{
assert(it);
return it->curr_threads;
}
| scarito/zmap-android | src/iterator.c | C | apache-2.0 | 2,428 | [
30522,
1001,
2421,
1026,
20865,
1012,
1044,
1028,
1001,
2421,
1026,
13866,
28362,
4215,
1012,
1044,
1028,
1001,
2421,
1026,
2358,
8718,
2102,
1012,
1044,
1028,
1001,
2421,
1026,
2051,
1012,
1044,
1028,
1001,
2421,
1000,
1012,
1012,
1013,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/* Minibuffer input and completion.
Copyright (C) 1985-1986, 1993-2013 Free Software Foundation, Inc.
This file is part of GNU Emacs.
GNU Emacs is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
#include <errno.h>
#include <stdio.h>
#include "lisp.h"
#include "commands.h"
#include "character.h"
#include "buffer.h"
#include "dispextern.h"
#include "keyboard.h"
#include "frame.h"
#include "window.h"
#include "syntax.h"
#include "intervals.h"
#include "keymap.h"
#include "termhooks.h"
/* List of buffers for use as minibuffers.
The first element of the list is used for the outermost minibuffer
invocation, the next element is used for a recursive minibuffer
invocation, etc. The list is extended at the end as deeper
minibuffer recursions are encountered. */
Lisp_Object Vminibuffer_list;
/* Data to remember during recursive minibuffer invocations. */
static Lisp_Object minibuf_save_list;
/* Depth in minibuffer invocations. */
EMACS_INT minibuf_level;
/* The maximum length of a minibuffer history. */
static Lisp_Object Qhistory_length;
/* Fread_minibuffer leaves the input here as a string. */
Lisp_Object last_minibuf_string;
static Lisp_Object Qminibuffer_history, Qbuffer_name_history;
static Lisp_Object Qread_file_name_internal;
/* Normal hooks for entry to and exit from minibuffer. */
static Lisp_Object Qminibuffer_setup_hook;
static Lisp_Object Qminibuffer_exit_hook;
Lisp_Object Qcompletion_ignore_case;
static Lisp_Object Qminibuffer_completion_table;
static Lisp_Object Qminibuffer_completion_predicate;
static Lisp_Object Qminibuffer_completion_confirm;
static Lisp_Object Qcustom_variable_p;
static Lisp_Object Qminibuffer_default;
static Lisp_Object Qcurrent_input_method, Qactivate_input_method;
static Lisp_Object Qcase_fold_search;
static Lisp_Object Qread_expression_history;
/* Prompt to display in front of the mini-buffer contents. */
static Lisp_Object minibuf_prompt;
/* Width of current mini-buffer prompt. Only set after display_line
of the line that contains the prompt. */
static ptrdiff_t minibuf_prompt_width;
/* Put minibuf on currently selected frame's minibuffer.
We do this whenever the user starts a new minibuffer
or when a minibuffer exits. */
static void
choose_minibuf_frame (void)
{
if (FRAMEP (selected_frame)
&& FRAME_LIVE_P (XFRAME (selected_frame))
&& !EQ (minibuf_window, XFRAME (selected_frame)->minibuffer_window))
{
struct frame *sf = XFRAME (selected_frame);
Lisp_Object buffer;
/* I don't think that any frames may validly have a null minibuffer
window anymore. */
if (NILP (sf->minibuffer_window))
emacs_abort ();
/* Under X, we come here with minibuf_window being the
minibuffer window of the unused termcap window created in
init_window_once. That window doesn't have a buffer. */
buffer = XWINDOW (minibuf_window)->contents;
if (BUFFERP (buffer))
/* Use set_window_buffer instead of Fset_window_buffer (see
discussion of bug#11984, bug#12025, bug#12026). */
set_window_buffer (sf->minibuffer_window, buffer, 0, 0);
minibuf_window = sf->minibuffer_window;
}
/* Make sure no other frame has a minibuffer as its selected window,
because the text would not be displayed in it, and that would be
confusing. Only allow the selected frame to do this,
and that only if the minibuffer is active. */
{
Lisp_Object tail, frame;
FOR_EACH_FRAME (tail, frame)
if (MINI_WINDOW_P (XWINDOW (FRAME_SELECTED_WINDOW (XFRAME (frame))))
&& !(EQ (frame, selected_frame)
&& minibuf_level > 0))
Fset_frame_selected_window (frame, Fframe_first_window (frame), Qnil);
}
}
DEFUN ("active-minibuffer-window", Factive_minibuffer_window,
Sactive_minibuffer_window, 0, 0, 0,
doc: /* Return the currently active minibuffer window, or nil if none. */)
(void)
{
return minibuf_level ? minibuf_window : Qnil;
}
DEFUN ("set-minibuffer-window", Fset_minibuffer_window,
Sset_minibuffer_window, 1, 1, 0,
doc: /* Specify which minibuffer window to use for the minibuffer.
This affects where the minibuffer is displayed if you put text in it
without invoking the usual minibuffer commands. */)
(Lisp_Object window)
{
CHECK_WINDOW (window);
if (! MINI_WINDOW_P (XWINDOW (window)))
error ("Window is not a minibuffer window");
minibuf_window = window;
return window;
}
/* Actual minibuffer invocation. */
static void read_minibuf_unwind (void);
static void run_exit_minibuf_hook (void);
/* Read a Lisp object from VAL and return it. If VAL is an empty
string, and DEFALT is a string, read from DEFALT instead of VAL. */
static Lisp_Object
string_to_object (Lisp_Object val, Lisp_Object defalt)
{
struct gcpro gcpro1, gcpro2;
Lisp_Object expr_and_pos;
ptrdiff_t pos;
GCPRO2 (val, defalt);
if (STRINGP (val) && SCHARS (val) == 0)
{
if (STRINGP (defalt))
val = defalt;
else if (CONSP (defalt) && STRINGP (XCAR (defalt)))
val = XCAR (defalt);
}
expr_and_pos = Fread_from_string (val, Qnil, Qnil);
pos = XINT (Fcdr (expr_and_pos));
if (pos != SCHARS (val))
{
/* Ignore trailing whitespace; any other trailing junk
is an error. */
ptrdiff_t i;
pos = string_char_to_byte (val, pos);
for (i = pos; i < SBYTES (val); i++)
{
int c = SREF (val, i);
if (c != ' ' && c != '\t' && c != '\n')
error ("Trailing garbage following expression");
}
}
val = Fcar (expr_and_pos);
RETURN_UNGCPRO (val);
}
/* Like read_minibuf but reading from stdin. This function is called
from read_minibuf to do the job if noninteractive. */
static Lisp_Object
read_minibuf_noninteractive (Lisp_Object map, Lisp_Object initial,
Lisp_Object prompt, Lisp_Object backup_n,
bool expflag,
Lisp_Object histvar, Lisp_Object histpos,
Lisp_Object defalt,
bool allow_props, bool inherit_input_method)
{
ptrdiff_t size, len;
char *line;
Lisp_Object val;
int c;
fprintf (stdout, "%s", SDATA (prompt));
fflush (stdout);
val = Qnil;
size = 100;
len = 0;
line = xmalloc (size);
while ((c = getchar ()) != '\n')
{
if (c == EOF)
{
if (errno != EINTR)
break;
}
else
{
if (len == size)
{
if (STRING_BYTES_BOUND / 2 < size)
memory_full (SIZE_MAX);
size *= 2;
line = xrealloc (line, size);
}
line[len++] = c;
}
}
if (len || c == '\n')
{
val = make_string (line, len);
xfree (line);
}
else
{
xfree (line);
error ("Error reading from stdin");
}
/* If Lisp form desired instead of string, parse it. */
if (expflag)
val = string_to_object (val, CONSP (defalt) ? XCAR (defalt) : defalt);
return val;
}
DEFUN ("minibufferp", Fminibufferp,
Sminibufferp, 0, 1, 0,
doc: /* Return t if BUFFER is a minibuffer.
No argument or nil as argument means use current buffer as BUFFER.
BUFFER can be a buffer or a buffer name. */)
(Lisp_Object buffer)
{
Lisp_Object tem;
if (NILP (buffer))
buffer = Fcurrent_buffer ();
else if (STRINGP (buffer))
buffer = Fget_buffer (buffer);
else
CHECK_BUFFER (buffer);
tem = Fmemq (buffer, Vminibuffer_list);
return ! NILP (tem) ? Qt : Qnil;
}
DEFUN ("minibuffer-prompt-end", Fminibuffer_prompt_end,
Sminibuffer_prompt_end, 0, 0, 0,
doc: /* Return the buffer position of the end of the minibuffer prompt.
Return (point-min) if current buffer is not a minibuffer. */)
(void)
{
/* This function is written to be most efficient when there's a prompt. */
Lisp_Object beg, end, tem;
beg = make_number (BEGV);
tem = Fmemq (Fcurrent_buffer (), Vminibuffer_list);
if (NILP (tem))
return beg;
end = Ffield_end (beg, Qnil, Qnil);
if (XINT (end) == ZV && NILP (Fget_char_property (beg, Qfield, Qnil)))
return beg;
else
return end;
}
DEFUN ("minibuffer-contents", Fminibuffer_contents,
Sminibuffer_contents, 0, 0, 0,
doc: /* Return the user input in a minibuffer as a string.
If the current buffer is not a minibuffer, return its entire contents. */)
(void)
{
ptrdiff_t prompt_end = XINT (Fminibuffer_prompt_end ());
return make_buffer_string (prompt_end, ZV, 1);
}
DEFUN ("minibuffer-contents-no-properties", Fminibuffer_contents_no_properties,
Sminibuffer_contents_no_properties, 0, 0, 0,
doc: /* Return the user input in a minibuffer as a string, without text-properties.
If the current buffer is not a minibuffer, return its entire contents. */)
(void)
{
ptrdiff_t prompt_end = XINT (Fminibuffer_prompt_end ());
return make_buffer_string (prompt_end, ZV, 0);
}
DEFUN ("minibuffer-completion-contents", Fminibuffer_completion_contents,
Sminibuffer_completion_contents, 0, 0, 0,
doc: /* Return the user input in a minibuffer before point as a string.
That is what completion commands operate on.
If the current buffer is not a minibuffer, return its entire contents. */)
(void)
{
ptrdiff_t prompt_end = XINT (Fminibuffer_prompt_end ());
if (PT < prompt_end)
error ("Cannot do completion in the prompt");
return make_buffer_string (prompt_end, PT, 1);
}
/* Read from the minibuffer using keymap MAP and initial contents INITIAL,
putting point minus BACKUP_N bytes from the end of INITIAL,
prompting with PROMPT (a string), using history list HISTVAR
with initial position HISTPOS. INITIAL should be a string or a
cons of a string and an integer. BACKUP_N should be <= 0, or
Qnil, which is equivalent to 0. If INITIAL is a cons, BACKUP_N is
ignored and replaced with an integer that puts point at one-indexed
position N in INITIAL, where N is the CDR of INITIAL, or at the
beginning of INITIAL if N <= 0.
Normally return the result as a string (the text that was read),
but if EXPFLAG, read it and return the object read.
If HISTVAR is given, save the value read on that history only if it doesn't
match the front of that history list exactly. The value is pushed onto
the list as the string that was read.
DEFALT specifies the default value for the sake of history commands.
If ALLOW_PROPS, do not throw away text properties.
if INHERIT_INPUT_METHOD, the minibuffer inherits the
current input method. */
static Lisp_Object
read_minibuf (Lisp_Object map, Lisp_Object initial, Lisp_Object prompt,
bool expflag,
Lisp_Object histvar, Lisp_Object histpos, Lisp_Object defalt,
bool allow_props, bool inherit_input_method)
{
Lisp_Object val;
ptrdiff_t count = SPECPDL_INDEX ();
Lisp_Object mini_frame, ambient_dir, minibuffer, input_method;
struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
Lisp_Object enable_multibyte;
EMACS_INT pos = 0;
/* String to add to the history. */
Lisp_Object histstring;
Lisp_Object empty_minibuf;
Lisp_Object dummy, frame;
specbind (Qminibuffer_default, defalt);
specbind (intern ("inhibit-read-only"), Qnil);
/* If Vminibuffer_completing_file_name is `lambda' on entry, it was t
in previous recursive minibuffer, but was not set explicitly
to t for this invocation, so set it to nil in this minibuffer.
Save the old value now, before we change it. */
specbind (intern ("minibuffer-completing-file-name"), Vminibuffer_completing_file_name);
if (EQ (Vminibuffer_completing_file_name, Qlambda))
Vminibuffer_completing_file_name = Qnil;
#ifdef HAVE_WINDOW_SYSTEM
if (display_hourglass_p)
cancel_hourglass ();
#endif
if (!NILP (initial))
{
if (CONSP (initial))
{
Lisp_Object backup_n = XCDR (initial);
initial = XCAR (initial);
CHECK_STRING (initial);
if (!NILP (backup_n))
{
CHECK_NUMBER (backup_n);
/* Convert to distance from end of input. */
if (XINT (backup_n) < 1)
/* A number too small means the beginning of the string. */
pos = - SCHARS (initial);
else
pos = XINT (backup_n) - 1 - SCHARS (initial);
}
}
else
CHECK_STRING (initial);
}
val = Qnil;
ambient_dir = BVAR (current_buffer, directory);
input_method = Qnil;
enable_multibyte = Qnil;
/* Don't need to protect PROMPT, HISTVAR, and HISTPOS because we
store them away before we can GC. Don't need to protect
BACKUP_N because we use the value only if it is an integer. */
GCPRO5 (map, initial, val, ambient_dir, input_method);
if (!STRINGP (prompt))
prompt = empty_unibyte_string;
if (!enable_recursive_minibuffers
&& minibuf_level > 0)
{
if (EQ (selected_window, minibuf_window))
error ("Command attempted to use minibuffer while in minibuffer");
else
/* If we're in another window, cancel the minibuffer that's active. */
Fthrow (Qexit,
build_string ("Command attempted to use minibuffer while in minibuffer"));
}
if ((noninteractive
/* In case we are running as a daemon, only do this before
detaching from the terminal. */
|| (IS_DAEMON && (daemon_pipe[1] >= 0)))
&& NILP (Vexecuting_kbd_macro))
{
val = read_minibuf_noninteractive (map, initial, prompt,
make_number (pos),
expflag, histvar, histpos, defalt,
allow_props, inherit_input_method);
UNGCPRO;
return unbind_to (count, val);
}
/* Choose the minibuffer window and frame, and take action on them. */
/* Prepare for restoring the current buffer since choose_minibuf_frame
calling Fset_frame_selected_window may change it (Bug#12766). */
record_unwind_protect (restore_buffer, Fcurrent_buffer ());
choose_minibuf_frame ();
record_unwind_protect_void (choose_minibuf_frame);
record_unwind_protect (restore_window_configuration,
Fcurrent_window_configuration (Qnil));
/* If the minibuffer window is on a different frame, save that
frame's configuration too. */
mini_frame = WINDOW_FRAME (XWINDOW (minibuf_window));
if (!EQ (mini_frame, selected_frame))
record_unwind_protect (restore_window_configuration,
Fcurrent_window_configuration (mini_frame));
/* If the minibuffer is on an iconified or invisible frame,
make it visible now. */
Fmake_frame_visible (mini_frame);
if (minibuffer_auto_raise)
Fraise_frame (mini_frame);
temporarily_switch_to_single_kboard (XFRAME (mini_frame));
/* We have to do this after saving the window configuration
since that is what restores the current buffer. */
/* Arrange to restore a number of minibuffer-related variables.
We could bind each variable separately, but that would use lots of
specpdl slots. */
minibuf_save_list
= Fcons (Voverriding_local_map,
Fcons (minibuf_window,
minibuf_save_list));
minibuf_save_list
= Fcons (minibuf_prompt,
Fcons (make_number (minibuf_prompt_width),
Fcons (Vhelp_form,
Fcons (Vcurrent_prefix_arg,
Fcons (Vminibuffer_history_position,
Fcons (Vminibuffer_history_variable,
minibuf_save_list))))));
record_unwind_protect_void (read_minibuf_unwind);
minibuf_level++;
/* We are exiting the minibuffer one way or the other, so run the hook.
It should be run before unwinding the minibuf settings. Do it
separately from read_minibuf_unwind because we need to make sure that
read_minibuf_unwind is fully executed even if exit-minibuffer-hook
signals an error. --Stef */
record_unwind_protect_void (run_exit_minibuf_hook);
/* Now that we can restore all those variables, start changing them. */
minibuf_prompt_width = 0;
minibuf_prompt = Fcopy_sequence (prompt);
Vminibuffer_history_position = histpos;
Vminibuffer_history_variable = histvar;
Vhelp_form = Vminibuffer_help_form;
/* If this minibuffer is reading a file name, that doesn't mean
recursive ones are. But we cannot set it to nil, because
completion code still need to know the minibuffer is completing a
file name. So use `lambda' as intermediate value meaning
"t" in this minibuffer, but "nil" in next minibuffer. */
if (!NILP (Vminibuffer_completing_file_name))
Vminibuffer_completing_file_name = Qlambda;
if (inherit_input_method)
{
/* `current-input-method' is buffer local. So, remember it in
INPUT_METHOD before changing the current buffer. */
input_method = Fsymbol_value (Qcurrent_input_method);
enable_multibyte = BVAR (current_buffer, enable_multibyte_characters);
}
/* Switch to the minibuffer. */
minibuffer = get_minibuffer (minibuf_level);
Fset_buffer (minibuffer);
/* Defeat (setq-default truncate-lines t), since truncated lines do
not work correctly in minibuffers. (Bug#5715, etc) */
bset_truncate_lines (current_buffer, Qnil);
/* If appropriate, copy enable-multibyte-characters into the minibuffer. */
if (inherit_input_method)
bset_enable_multibyte_characters (current_buffer, enable_multibyte);
/* The current buffer's default directory is usually the right thing
for our minibuffer here. However, if you're typing a command at
a minibuffer-only frame when minibuf_level is zero, then buf IS
the current_buffer, so reset_buffer leaves buf's default
directory unchanged. This is a bummer when you've just started
up Emacs and buf's default directory is Qnil. Here's a hack; can
you think of something better to do? Find another buffer with a
better directory, and use that one instead. */
if (STRINGP (ambient_dir))
bset_directory (current_buffer, ambient_dir);
else
{
Lisp_Object tail, buf;
FOR_EACH_LIVE_BUFFER (tail, buf)
if (STRINGP (BVAR (XBUFFER (buf), directory)))
{
bset_directory (current_buffer,
BVAR (XBUFFER (buf), directory));
break;
}
}
if (!EQ (mini_frame, selected_frame))
Fredirect_frame_focus (selected_frame, mini_frame);
Vminibuf_scroll_window = selected_window;
if (minibuf_level == 1 || !EQ (minibuf_window, selected_window))
minibuf_selected_window = selected_window;
/* Empty out the minibuffers of all frames other than the one
where we are going to display one now.
Set them to point to ` *Minibuf-0*', which is always empty. */
empty_minibuf = get_minibuffer (0);
FOR_EACH_FRAME (dummy, frame)
{
Lisp_Object root_window = Fframe_root_window (frame);
Lisp_Object mini_window = XWINDOW (root_window)->next;
if (! NILP (mini_window) && ! EQ (mini_window, minibuf_window)
&& !NILP (Fwindow_minibuffer_p (mini_window)))
/* Use set_window_buffer instead of Fset_window_buffer (see
discussion of bug#11984, bug#12025, bug#12026). */
set_window_buffer (mini_window, empty_minibuf, 0, 0);
}
/* Display this minibuffer in the proper window. */
/* Use set_window_buffer instead of Fset_window_buffer (see
discussion of bug#11984, bug#12025, bug#12026). */
set_window_buffer (minibuf_window, Fcurrent_buffer (), 0, 0);
Fselect_window (minibuf_window, Qnil);
XWINDOW (minibuf_window)->hscroll = 0;
Fmake_local_variable (Qprint_escape_newlines);
print_escape_newlines = 1;
/* Erase the buffer. */
{
ptrdiff_t count1 = SPECPDL_INDEX ();
specbind (Qinhibit_read_only, Qt);
specbind (Qinhibit_modification_hooks, Qt);
Ferase_buffer ();
if (!NILP (BVAR (current_buffer, enable_multibyte_characters))
&& ! STRING_MULTIBYTE (minibuf_prompt))
minibuf_prompt = Fstring_make_multibyte (minibuf_prompt);
/* Insert the prompt, record where it ends. */
Finsert (1, &minibuf_prompt);
if (PT > BEG)
{
Fput_text_property (make_number (BEG), make_number (PT),
Qfront_sticky, Qt, Qnil);
Fput_text_property (make_number (BEG), make_number (PT),
Qrear_nonsticky, Qt, Qnil);
Fput_text_property (make_number (BEG), make_number (PT),
Qfield, Qt, Qnil);
Fadd_text_properties (make_number (BEG), make_number (PT),
Vminibuffer_prompt_properties, Qnil);
}
unbind_to (count1, Qnil);
}
minibuf_prompt_width = current_column ();
/* Put in the initial input. */
if (!NILP (initial))
{
Finsert (1, &initial);
Fforward_char (make_number (pos));
}
clear_message (1, 1);
bset_keymap (current_buffer, map);
/* Turn on an input method stored in INPUT_METHOD if any. */
if (STRINGP (input_method) && !NILP (Ffboundp (Qactivate_input_method)))
call1 (Qactivate_input_method, input_method);
Frun_hooks (1, &Qminibuffer_setup_hook);
/* Don't allow the user to undo past this point. */
bset_undo_list (current_buffer, Qnil);
recursive_edit_1 ();
/* If cursor is on the minibuffer line,
show the user we have exited by putting it in column 0. */
if (XWINDOW (minibuf_window)->cursor.vpos >= 0
&& !noninteractive)
{
XWINDOW (minibuf_window)->cursor.hpos = 0;
XWINDOW (minibuf_window)->cursor.x = 0;
XWINDOW (minibuf_window)->must_be_updated_p = 1;
update_frame (XFRAME (selected_frame), 1, 1);
flush_frame (XFRAME (XWINDOW (minibuf_window)->frame));
}
/* Make minibuffer contents into a string. */
Fset_buffer (minibuffer);
if (allow_props)
val = Fminibuffer_contents ();
else
val = Fminibuffer_contents_no_properties ();
/* VAL is the string of minibuffer text. */
last_minibuf_string = val;
/* Choose the string to add to the history. */
if (SCHARS (val) != 0)
histstring = val;
else if (STRINGP (defalt))
histstring = defalt;
else if (CONSP (defalt) && STRINGP (XCAR (defalt)))
histstring = XCAR (defalt);
else
histstring = Qnil;
/* Add the value to the appropriate history list, if any. */
if (!NILP (Vhistory_add_new_input)
&& SYMBOLP (Vminibuffer_history_variable)
&& !NILP (histstring))
{
/* If the caller wanted to save the value read on a history list,
then do so if the value is not already the front of the list. */
Lisp_Object histval;
/* If variable is unbound, make it nil. */
histval = find_symbol_value (Vminibuffer_history_variable);
if (EQ (histval, Qunbound))
Fset (Vminibuffer_history_variable, Qnil);
/* The value of the history variable must be a cons or nil. Other
values are unacceptable. We silently ignore these values. */
if (NILP (histval)
|| (CONSP (histval)
/* Don't duplicate the most recent entry in the history. */
&& (NILP (Fequal (histstring, Fcar (histval))))))
{
Lisp_Object length;
if (history_delete_duplicates) Fdelete (histstring, histval);
histval = Fcons (histstring, histval);
Fset (Vminibuffer_history_variable, histval);
/* Truncate if requested. */
length = Fget (Vminibuffer_history_variable, Qhistory_length);
if (NILP (length)) length = Vhistory_length;
if (INTEGERP (length))
{
if (XINT (length) <= 0)
Fset (Vminibuffer_history_variable, Qnil);
else
{
Lisp_Object temp;
temp = Fnthcdr (Fsub1 (length), histval);
if (CONSP (temp)) Fsetcdr (temp, Qnil);
}
}
}
}
/* If Lisp form desired instead of string, parse it. */
if (expflag)
val = string_to_object (val, defalt);
/* The appropriate frame will get selected
in set-window-configuration. */
UNGCPRO;
return unbind_to (count, val);
}
/* Return a buffer to be used as the minibuffer at depth `depth'.
depth = 0 is the lowest allowed argument, and that is the value
used for nonrecursive minibuffer invocations. */
Lisp_Object
get_minibuffer (EMACS_INT depth)
{
Lisp_Object tail, num, buf;
char name[sizeof " *Minibuf-*" + INT_STRLEN_BOUND (EMACS_INT)];
XSETFASTINT (num, depth);
tail = Fnthcdr (num, Vminibuffer_list);
if (NILP (tail))
{
tail = list1 (Qnil);
Vminibuffer_list = nconc2 (Vminibuffer_list, tail);
}
buf = Fcar (tail);
if (NILP (buf) || !BUFFER_LIVE_P (XBUFFER (buf)))
{
buf = Fget_buffer_create
(make_formatted_string (name, " *Minibuf-%"pI"d*", depth));
/* Although the buffer's name starts with a space, undo should be
enabled in it. */
Fbuffer_enable_undo (buf);
XSETCAR (tail, buf);
}
else
{
ptrdiff_t count = SPECPDL_INDEX ();
/* We have to empty both overlay lists. Otherwise we end
up with overlays that think they belong to this buffer
while the buffer doesn't know about them any more. */
delete_all_overlays (XBUFFER (buf));
reset_buffer (XBUFFER (buf));
record_unwind_current_buffer ();
Fset_buffer (buf);
if (!NILP (Ffboundp (intern ("minibuffer-inactive-mode"))))
call0 (intern ("minibuffer-inactive-mode"));
else
Fkill_all_local_variables ();
unbind_to (count, Qnil);
}
return buf;
}
static void
run_exit_minibuf_hook (void)
{
safe_run_hooks (Qminibuffer_exit_hook);
}
/* This function is called on exiting minibuffer, whether normally or
not, and it restores the current window, buffer, etc. */
static void
read_minibuf_unwind (void)
{
Lisp_Object old_deactivate_mark;
Lisp_Object window;
/* If this was a recursive minibuffer,
tie the minibuffer window back to the outer level minibuffer buffer. */
minibuf_level--;
window = minibuf_window;
/* To keep things predictable, in case it matters, let's be in the
minibuffer when we reset the relevant variables. */
Fset_buffer (XWINDOW (window)->contents);
/* Restore prompt, etc, from outer minibuffer level. */
minibuf_prompt = Fcar (minibuf_save_list);
minibuf_save_list = Fcdr (minibuf_save_list);
minibuf_prompt_width = XFASTINT (Fcar (minibuf_save_list));
minibuf_save_list = Fcdr (minibuf_save_list);
Vhelp_form = Fcar (minibuf_save_list);
minibuf_save_list = Fcdr (minibuf_save_list);
Vcurrent_prefix_arg = Fcar (minibuf_save_list);
minibuf_save_list = Fcdr (minibuf_save_list);
Vminibuffer_history_position = Fcar (minibuf_save_list);
minibuf_save_list = Fcdr (minibuf_save_list);
Vminibuffer_history_variable = Fcar (minibuf_save_list);
minibuf_save_list = Fcdr (minibuf_save_list);
Voverriding_local_map = Fcar (minibuf_save_list);
minibuf_save_list = Fcdr (minibuf_save_list);
#if 0
temp = Fcar (minibuf_save_list);
if (FRAME_LIVE_P (XFRAME (WINDOW_FRAME (XWINDOW (temp)))))
minibuf_window = temp;
#endif
minibuf_save_list = Fcdr (minibuf_save_list);
/* Erase the minibuffer we were using at this level. */
{
ptrdiff_t count = SPECPDL_INDEX ();
/* Prevent error in erase-buffer. */
specbind (Qinhibit_read_only, Qt);
specbind (Qinhibit_modification_hooks, Qt);
old_deactivate_mark = Vdeactivate_mark;
Ferase_buffer ();
Vdeactivate_mark = old_deactivate_mark;
unbind_to (count, Qnil);
}
/* When we get to the outmost level, make sure we resize the
mini-window back to its normal size. */
if (minibuf_level == 0)
resize_mini_window (XWINDOW (window), 0);
/* Enforce full redisplay. FIXME: make it more selective. */
windows_or_buffers_changed++;
/* In case the previous minibuffer displayed in this miniwindow is
dead, we may keep displaying this buffer (tho it's inactive), so reset it,
to make sure we don't leave around bindings and stuff which only
made sense during the read_minibuf invocation. */
call0 (intern ("minibuffer-inactive-mode"));
}
DEFUN ("read-from-minibuffer", Fread_from_minibuffer,
Sread_from_minibuffer, 1, 7, 0,
doc: /* Read a string from the minibuffer, prompting with string PROMPT.
The optional second arg INITIAL-CONTENTS is an obsolete alternative to
DEFAULT-VALUE. It normally should be nil in new code, except when
HIST is a cons. It is discussed in more detail below.
Third arg KEYMAP is a keymap to use whilst reading;
if omitted or nil, the default is `minibuffer-local-map'.
If fourth arg READ is non-nil, interpret the result as a Lisp object
and return that object:
in other words, do `(car (read-from-string INPUT-STRING))'
Fifth arg HIST, if non-nil, specifies a history list and optionally
the initial position in the list. It can be a symbol, which is the
history list variable to use, or a cons cell (HISTVAR . HISTPOS).
In that case, HISTVAR is the history list variable to use, and
HISTPOS is the initial position for use by the minibuffer history
commands. For consistency, you should also specify that element of
the history as the value of INITIAL-CONTENTS. Positions are counted
starting from 1 at the beginning of the list.
Sixth arg DEFAULT-VALUE, if non-nil, should be a string, which is used
as the default to `read' if READ is non-nil and the user enters
empty input. But if READ is nil, this function does _not_ return
DEFAULT-VALUE for empty input! Instead, it returns the empty string.
Whatever the value of READ, DEFAULT-VALUE is made available via the
minibuffer history commands. DEFAULT-VALUE can also be a list of
strings, in which case all the strings are available in the history,
and the first string is the default to `read' if READ is non-nil.
Seventh arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
the current input method and the setting of `enable-multibyte-characters'.
If the variable `minibuffer-allow-text-properties' is non-nil,
then the string which is returned includes whatever text properties
were present in the minibuffer. Otherwise the value has no text properties.
The remainder of this documentation string describes the
INITIAL-CONTENTS argument in more detail. It is only relevant when
studying existing code, or when HIST is a cons. If non-nil,
INITIAL-CONTENTS is a string to be inserted into the minibuffer before
reading input. Normally, point is put at the end of that string.
However, if INITIAL-CONTENTS is \(STRING . POSITION), the initial
input is STRING, but point is placed at _one-indexed_ position
POSITION in the minibuffer. Any integer value less than or equal to
one puts point at the beginning of the string. *Note* that this
behavior differs from the way such arguments are used in `completing-read'
and some related functions, which use zero-indexing for POSITION. */)
(Lisp_Object prompt, Lisp_Object initial_contents, Lisp_Object keymap, Lisp_Object read, Lisp_Object hist, Lisp_Object default_value, Lisp_Object inherit_input_method)
{
Lisp_Object histvar, histpos, val;
struct gcpro gcpro1;
CHECK_STRING (prompt);
if (NILP (keymap))
keymap = Vminibuffer_local_map;
else
keymap = get_keymap (keymap, 1, 0);
if (SYMBOLP (hist))
{
histvar = hist;
histpos = Qnil;
}
else
{
histvar = Fcar_safe (hist);
histpos = Fcdr_safe (hist);
}
if (NILP (histvar))
histvar = Qminibuffer_history;
if (NILP (histpos))
XSETFASTINT (histpos, 0);
GCPRO1 (default_value);
val = read_minibuf (keymap, initial_contents, prompt,
!NILP (read),
histvar, histpos, default_value,
minibuffer_allow_text_properties,
!NILP (inherit_input_method));
UNGCPRO;
return val;
}
/* Functions that use the minibuffer to read various things. */
DEFUN ("read-string", Fread_string, Sread_string, 1, 5, 0,
doc: /* Read a string from the minibuffer, prompting with string PROMPT.
If non-nil, second arg INITIAL-INPUT is a string to insert before reading.
This argument has been superseded by DEFAULT-VALUE and should normally
be nil in new code. It behaves as in `read-from-minibuffer'. See the
documentation string of that function for details.
The third arg HISTORY, if non-nil, specifies a history list
and optionally the initial position in the list.
See `read-from-minibuffer' for details of HISTORY argument.
Fourth arg DEFAULT-VALUE is the default value or the list of default values.
If non-nil, it is used for history commands, and as the value (or the first
element of the list of default values) to return if the user enters the
empty string.
Fifth arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
the current input method and the setting of `enable-multibyte-characters'. */)
(Lisp_Object prompt, Lisp_Object initial_input, Lisp_Object history, Lisp_Object default_value, Lisp_Object inherit_input_method)
{
Lisp_Object val;
ptrdiff_t count = SPECPDL_INDEX ();
/* Just in case we're in a recursive minibuffer, make it clear that the
previous minibuffer's completion table does not apply to the new
minibuffer.
FIXME: `minibuffer-completion-table' should be buffer-local instead. */
specbind (Qminibuffer_completion_table, Qnil);
val = Fread_from_minibuffer (prompt, initial_input, Qnil,
Qnil, history, default_value,
inherit_input_method);
if (STRINGP (val) && SCHARS (val) == 0 && ! NILP (default_value))
val = CONSP (default_value) ? XCAR (default_value) : default_value;
return unbind_to (count, val);
}
DEFUN ("read-no-blanks-input", Fread_no_blanks_input, Sread_no_blanks_input, 1, 3, 0,
doc: /* Read a string from the terminal, not allowing blanks.
Prompt with PROMPT. Whitespace terminates the input. If INITIAL is
non-nil, it should be a string, which is used as initial input, with
point positioned at the end, so that SPACE will accept the input.
\(Actually, INITIAL can also be a cons of a string and an integer.
Such values are treated as in `read-from-minibuffer', but are normally
not useful in this function.)
Third arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
the current input method and the setting of`enable-multibyte-characters'. */)
(Lisp_Object prompt, Lisp_Object initial, Lisp_Object inherit_input_method)
{
CHECK_STRING (prompt);
return read_minibuf (Vminibuffer_local_ns_map, initial, prompt,
0, Qminibuffer_history, make_number (0), Qnil, 0,
!NILP (inherit_input_method));
}
DEFUN ("read-command", Fread_command, Sread_command, 1, 2, 0,
doc: /* Read the name of a command and return as a symbol.
Prompt with PROMPT. By default, return DEFAULT-VALUE or its first element
if it is a list. */)
(Lisp_Object prompt, Lisp_Object default_value)
{
Lisp_Object name, default_string;
if (NILP (default_value))
default_string = Qnil;
else if (SYMBOLP (default_value))
default_string = SYMBOL_NAME (default_value);
else
default_string = default_value;
name = Fcompleting_read (prompt, Vobarray, Qcommandp, Qt,
Qnil, Qnil, default_string, Qnil);
if (NILP (name))
return name;
return Fintern (name, Qnil);
}
#ifdef NOTDEF
DEFUN ("read-function", Fread_function, Sread_function, 1, 1, 0,
doc: /* One arg PROMPT, a string. Read the name of a function and return as a symbol.
Prompt with PROMPT. */)
(Lisp_Object prompt)
{
return Fintern (Fcompleting_read (prompt, Vobarray, Qfboundp, Qt, Qnil, Qnil, Qnil, Qnil),
Qnil);
}
#endif /* NOTDEF */
DEFUN ("read-variable", Fread_variable, Sread_variable, 1, 2, 0,
doc: /* Read the name of a user option and return it as a symbol.
Prompt with PROMPT. By default, return DEFAULT-VALUE or its first element
if it is a list.
A user option, or customizable variable, is one for which
`custom-variable-p' returns non-nil. */)
(Lisp_Object prompt, Lisp_Object default_value)
{
Lisp_Object name, default_string;
if (NILP (default_value))
default_string = Qnil;
else if (SYMBOLP (default_value))
default_string = SYMBOL_NAME (default_value);
else
default_string = default_value;
name = Fcompleting_read (prompt, Vobarray,
Qcustom_variable_p, Qt,
Qnil, Qnil, default_string, Qnil);
if (NILP (name))
return name;
return Fintern (name, Qnil);
}
DEFUN ("read-buffer", Fread_buffer, Sread_buffer, 1, 3, 0,
doc: /* Read the name of a buffer and return as a string.
Prompt with PROMPT.
Optional second arg DEF is value to return if user enters an empty line.
If DEF is a list of default values, return its first element.
Optional third arg REQUIRE-MATCH determines whether non-existing
buffer names are allowed. It has the same meaning as the
REQUIRE-MATCH argument of `completing-read'.
The argument PROMPT should be a string ending with a colon and a space.
If `read-buffer-completion-ignore-case' is non-nil, completion ignores
case while reading the buffer name.
If `read-buffer-function' is non-nil, this works by calling it as a
function, instead of the usual behavior. */)
(Lisp_Object prompt, Lisp_Object def, Lisp_Object require_match)
{
Lisp_Object args[4], result;
char *s;
ptrdiff_t len;
ptrdiff_t count = SPECPDL_INDEX ();
if (BUFFERP (def))
def = BVAR (XBUFFER (def), name);
specbind (Qcompletion_ignore_case,
read_buffer_completion_ignore_case ? Qt : Qnil);
if (NILP (Vread_buffer_function))
{
if (!NILP (def))
{
/* A default value was provided: we must change PROMPT,
editing the default value in before the colon. To achieve
this, we replace PROMPT with a substring that doesn't
contain the terminal space and colon (if present). They
are then added back using Fformat. */
if (STRINGP (prompt))
{
s = SSDATA (prompt);
len = SBYTES (prompt);
if (len >= 2 && s[len - 2] == ':' && s[len - 1] == ' ')
len = len - 2;
else if (len >= 1 && (s[len - 1] == ':' || s[len - 1] == ' '))
len--;
prompt = make_specified_string (s, -1, len,
STRING_MULTIBYTE (prompt));
}
args[0] = build_string ("%s (default %s): ");
args[1] = prompt;
args[2] = CONSP (def) ? XCAR (def) : def;
prompt = Fformat (3, args);
}
result = Fcompleting_read (prompt, intern ("internal-complete-buffer"),
Qnil, require_match, Qnil,
Qbuffer_name_history, def, Qnil);
}
else
{
args[0] = Vread_buffer_function;
args[1] = prompt;
args[2] = def;
args[3] = require_match;
result = Ffuncall (4, args);
}
return unbind_to (count, result);
}
static Lisp_Object
minibuf_conform_representation (Lisp_Object string, Lisp_Object basis)
{
if (STRING_MULTIBYTE (string) == STRING_MULTIBYTE (basis))
return string;
if (STRING_MULTIBYTE (string))
return Fstring_make_unibyte (string);
else
return Fstring_make_multibyte (string);
}
DEFUN ("try-completion", Ftry_completion, Stry_completion, 2, 3, 0,
doc: /* Return common substring of all completions of STRING in COLLECTION.
Test each possible completion specified by COLLECTION
to see if it begins with STRING. The possible completions may be
strings or symbols. Symbols are converted to strings before testing,
see `symbol-name'.
All that match STRING are compared together; the longest initial sequence
common to all these matches is the return value.
If there is no match at all, the return value is nil.
For a unique match which is exact, the return value is t.
If COLLECTION is an alist, the keys (cars of elements) are the
possible completions. If an element is not a cons cell, then the
element itself is the possible completion.
If COLLECTION is a hash-table, all the keys that are strings or symbols
are the possible completions.
If COLLECTION is an obarray, the names of all symbols in the obarray
are the possible completions.
COLLECTION can also be a function to do the completion itself.
It receives three arguments: the values STRING, PREDICATE and nil.
Whatever it returns becomes the value of `try-completion'.
If optional third argument PREDICATE is non-nil,
it is used to test each possible match.
The match is a candidate only if PREDICATE returns non-nil.
The argument given to PREDICATE is the alist element
or the symbol from the obarray. If COLLECTION is a hash-table,
predicate is called with two arguments: the key and the value.
Additionally to this predicate, `completion-regexp-list'
is used to further constrain the set of candidates. */)
(Lisp_Object string, Lisp_Object collection, Lisp_Object predicate)
{
Lisp_Object bestmatch, tail, elt, eltstring;
/* Size in bytes of BESTMATCH. */
ptrdiff_t bestmatchsize = 0;
/* These are in bytes, too. */
ptrdiff_t compare, matchsize;
enum { function_table, list_table, obarray_table, hash_table}
type = (HASH_TABLE_P (collection) ? hash_table
: VECTORP (collection) ? obarray_table
: ((NILP (collection)
|| (CONSP (collection)
&& (!SYMBOLP (XCAR (collection))
|| NILP (XCAR (collection)))))
? list_table : function_table));
ptrdiff_t idx = 0, obsize = 0;
int matchcount = 0;
ptrdiff_t bindcount = -1;
Lisp_Object bucket, zero, end, tem;
struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
CHECK_STRING (string);
if (type == function_table)
return call3 (collection, string, predicate, Qnil);
bestmatch = bucket = Qnil;
zero = make_number (0);
/* If COLLECTION is not a list, set TAIL just for gc pro. */
tail = collection;
if (type == obarray_table)
{
collection = check_obarray (collection);
obsize = ASIZE (collection);
bucket = AREF (collection, idx);
}
while (1)
{
/* Get the next element of the alist, obarray, or hash-table. */
/* Exit the loop if the elements are all used up. */
/* elt gets the alist element or symbol.
eltstring gets the name to check as a completion. */
if (type == list_table)
{
if (!CONSP (tail))
break;
elt = XCAR (tail);
eltstring = CONSP (elt) ? XCAR (elt) : elt;
tail = XCDR (tail);
}
else if (type == obarray_table)
{
if (!EQ (bucket, zero))
{
if (!SYMBOLP (bucket))
error ("Bad data in guts of obarray");
elt = bucket;
eltstring = elt;
if (XSYMBOL (bucket)->next)
XSETSYMBOL (bucket, XSYMBOL (bucket)->next);
else
XSETFASTINT (bucket, 0);
}
else if (++idx >= obsize)
break;
else
{
bucket = AREF (collection, idx);
continue;
}
}
else /* if (type == hash_table) */
{
while (idx < HASH_TABLE_SIZE (XHASH_TABLE (collection))
&& NILP (HASH_HASH (XHASH_TABLE (collection), idx)))
idx++;
if (idx >= HASH_TABLE_SIZE (XHASH_TABLE (collection)))
break;
else
elt = eltstring = HASH_KEY (XHASH_TABLE (collection), idx++);
}
/* Is this element a possible completion? */
if (SYMBOLP (eltstring))
eltstring = Fsymbol_name (eltstring);
if (STRINGP (eltstring)
&& SCHARS (string) <= SCHARS (eltstring)
&& (tem = Fcompare_strings (eltstring, zero,
make_number (SCHARS (string)),
string, zero, Qnil,
completion_ignore_case ? Qt : Qnil),
EQ (Qt, tem)))
{
/* Yes. */
Lisp_Object regexps;
/* Ignore this element if it fails to match all the regexps. */
{
for (regexps = Vcompletion_regexp_list; CONSP (regexps);
regexps = XCDR (regexps))
{
if (bindcount < 0) {
bindcount = SPECPDL_INDEX ();
specbind (Qcase_fold_search,
completion_ignore_case ? Qt : Qnil);
}
tem = Fstring_match (XCAR (regexps), eltstring, zero);
if (NILP (tem))
break;
}
if (CONSP (regexps))
continue;
}
/* Ignore this element if there is a predicate
and the predicate doesn't like it. */
if (!NILP (predicate))
{
if (EQ (predicate, Qcommandp))
tem = Fcommandp (elt, Qnil);
else
{
if (bindcount >= 0)
{
unbind_to (bindcount, Qnil);
bindcount = -1;
}
GCPRO4 (tail, string, eltstring, bestmatch);
tem = (type == hash_table
? call2 (predicate, elt,
HASH_VALUE (XHASH_TABLE (collection),
idx - 1))
: call1 (predicate, elt));
UNGCPRO;
}
if (NILP (tem)) continue;
}
/* Update computation of how much all possible completions match */
if (NILP (bestmatch))
{
matchcount = 1;
bestmatch = eltstring;
bestmatchsize = SCHARS (eltstring);
}
else
{
compare = min (bestmatchsize, SCHARS (eltstring));
tem = Fcompare_strings (bestmatch, zero,
make_number (compare),
eltstring, zero,
make_number (compare),
completion_ignore_case ? Qt : Qnil);
matchsize = EQ (tem, Qt) ? compare : eabs (XINT (tem)) - 1;
if (completion_ignore_case)
{
/* If this is an exact match except for case,
use it as the best match rather than one that is not an
exact match. This way, we get the case pattern
of the actual match. */
if ((matchsize == SCHARS (eltstring)
&& matchsize < SCHARS (bestmatch))
||
/* If there is more than one exact match ignoring case,
and one of them is exact including case,
prefer that one. */
/* If there is no exact match ignoring case,
prefer a match that does not change the case
of the input. */
((matchsize == SCHARS (eltstring))
==
(matchsize == SCHARS (bestmatch))
&& (tem = Fcompare_strings (eltstring, zero,
make_number (SCHARS (string)),
string, zero,
Qnil,
Qnil),
EQ (Qt, tem))
&& (tem = Fcompare_strings (bestmatch, zero,
make_number (SCHARS (string)),
string, zero,
Qnil,
Qnil),
! EQ (Qt, tem))))
bestmatch = eltstring;
}
if (bestmatchsize != SCHARS (eltstring)
|| bestmatchsize != matchsize)
/* Don't count the same string multiple times. */
matchcount += matchcount <= 1;
bestmatchsize = matchsize;
if (matchsize <= SCHARS (string)
/* If completion-ignore-case is non-nil, don't
short-circuit because we want to find the best
possible match *including* case differences. */
&& !completion_ignore_case
&& matchcount > 1)
/* No need to look any further. */
break;
}
}
}
if (bindcount >= 0) {
unbind_to (bindcount, Qnil);
bindcount = -1;
}
if (NILP (bestmatch))
return Qnil; /* No completions found. */
/* If we are ignoring case, and there is no exact match,
and no additional text was supplied,
don't change the case of what the user typed. */
if (completion_ignore_case && bestmatchsize == SCHARS (string)
&& SCHARS (bestmatch) > bestmatchsize)
return minibuf_conform_representation (string, bestmatch);
/* Return t if the supplied string is an exact match (counting case);
it does not require any change to be made. */
if (matchcount == 1 && !NILP (Fequal (bestmatch, string)))
return Qt;
XSETFASTINT (zero, 0); /* Else extract the part in which */
XSETFASTINT (end, bestmatchsize); /* all completions agree. */
return Fsubstring (bestmatch, zero, end);
}
DEFUN ("all-completions", Fall_completions, Sall_completions, 2, 4, 0,
doc: /* Search for partial matches to STRING in COLLECTION.
Test each of the possible completions specified by COLLECTION
to see if it begins with STRING. The possible completions may be
strings or symbols. Symbols are converted to strings before testing,
see `symbol-name'.
The value is a list of all the possible completions that match STRING.
If COLLECTION is an alist, the keys (cars of elements) are the
possible completions. If an element is not a cons cell, then the
element itself is the possible completion.
If COLLECTION is a hash-table, all the keys that are strings or symbols
are the possible completions.
If COLLECTION is an obarray, the names of all symbols in the obarray
are the possible completions.
COLLECTION can also be a function to do the completion itself.
It receives three arguments: the values STRING, PREDICATE and t.
Whatever it returns becomes the value of `all-completions'.
If optional third argument PREDICATE is non-nil,
it is used to test each possible match.
The match is a candidate only if PREDICATE returns non-nil.
The argument given to PREDICATE is the alist element
or the symbol from the obarray. If COLLECTION is a hash-table,
predicate is called with two arguments: the key and the value.
Additionally to this predicate, `completion-regexp-list'
is used to further constrain the set of candidates.
An obsolete optional fourth argument HIDE-SPACES is still accepted for
backward compatibility. If non-nil, strings in COLLECTION that start
with a space are ignored unless STRING itself starts with a space. */)
(Lisp_Object string, Lisp_Object collection, Lisp_Object predicate, Lisp_Object hide_spaces)
{
Lisp_Object tail, elt, eltstring;
Lisp_Object allmatches;
int type = HASH_TABLE_P (collection) ? 3
: VECTORP (collection) ? 2
: NILP (collection) || (CONSP (collection)
&& (!SYMBOLP (XCAR (collection))
|| NILP (XCAR (collection))));
ptrdiff_t idx = 0, obsize = 0;
ptrdiff_t bindcount = -1;
Lisp_Object bucket, tem, zero;
struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
CHECK_STRING (string);
if (type == 0)
return call3 (collection, string, predicate, Qt);
allmatches = bucket = Qnil;
zero = make_number (0);
/* If COLLECTION is not a list, set TAIL just for gc pro. */
tail = collection;
if (type == 2)
{
collection = check_obarray (collection);
obsize = ASIZE (collection);
bucket = AREF (collection, idx);
}
while (1)
{
/* Get the next element of the alist, obarray, or hash-table. */
/* Exit the loop if the elements are all used up. */
/* elt gets the alist element or symbol.
eltstring gets the name to check as a completion. */
if (type == 1)
{
if (!CONSP (tail))
break;
elt = XCAR (tail);
eltstring = CONSP (elt) ? XCAR (elt) : elt;
tail = XCDR (tail);
}
else if (type == 2)
{
if (!EQ (bucket, zero))
{
if (!SYMBOLP (bucket))
error ("Bad data in guts of obarray");
elt = bucket;
eltstring = elt;
if (XSYMBOL (bucket)->next)
XSETSYMBOL (bucket, XSYMBOL (bucket)->next);
else
XSETFASTINT (bucket, 0);
}
else if (++idx >= obsize)
break;
else
{
bucket = AREF (collection, idx);
continue;
}
}
else /* if (type == 3) */
{
while (idx < HASH_TABLE_SIZE (XHASH_TABLE (collection))
&& NILP (HASH_HASH (XHASH_TABLE (collection), idx)))
idx++;
if (idx >= HASH_TABLE_SIZE (XHASH_TABLE (collection)))
break;
else
elt = eltstring = HASH_KEY (XHASH_TABLE (collection), idx++);
}
/* Is this element a possible completion? */
if (SYMBOLP (eltstring))
eltstring = Fsymbol_name (eltstring);
if (STRINGP (eltstring)
&& SCHARS (string) <= SCHARS (eltstring)
/* If HIDE_SPACES, reject alternatives that start with space
unless the input starts with space. */
&& (NILP (hide_spaces)
|| (SBYTES (string) > 0
&& SREF (string, 0) == ' ')
|| SREF (eltstring, 0) != ' ')
&& (tem = Fcompare_strings (eltstring, zero,
make_number (SCHARS (string)),
string, zero,
make_number (SCHARS (string)),
completion_ignore_case ? Qt : Qnil),
EQ (Qt, tem)))
{
/* Yes. */
Lisp_Object regexps;
/* Ignore this element if it fails to match all the regexps. */
{
for (regexps = Vcompletion_regexp_list; CONSP (regexps);
regexps = XCDR (regexps))
{
if (bindcount < 0) {
bindcount = SPECPDL_INDEX ();
specbind (Qcase_fold_search,
completion_ignore_case ? Qt : Qnil);
}
tem = Fstring_match (XCAR (regexps), eltstring, zero);
if (NILP (tem))
break;
}
if (CONSP (regexps))
continue;
}
/* Ignore this element if there is a predicate
and the predicate doesn't like it. */
if (!NILP (predicate))
{
if (EQ (predicate, Qcommandp))
tem = Fcommandp (elt, Qnil);
else
{
if (bindcount >= 0) {
unbind_to (bindcount, Qnil);
bindcount = -1;
}
GCPRO4 (tail, eltstring, allmatches, string);
tem = type == 3
? call2 (predicate, elt,
HASH_VALUE (XHASH_TABLE (collection), idx - 1))
: call1 (predicate, elt);
UNGCPRO;
}
if (NILP (tem)) continue;
}
/* Ok => put it on the list. */
allmatches = Fcons (eltstring, allmatches);
}
}
if (bindcount >= 0) {
unbind_to (bindcount, Qnil);
bindcount = -1;
}
return Fnreverse (allmatches);
}
DEFUN ("completing-read", Fcompleting_read, Scompleting_read, 2, 8, 0,
doc: /* Read a string in the minibuffer, with completion.
PROMPT is a string to prompt with; normally it ends in a colon and a space.
COLLECTION can be a list of strings, an alist, an obarray or a hash table.
COLLECTION can also be a function to do the completion itself.
PREDICATE limits completion to a subset of COLLECTION.
See `try-completion' and `all-completions' for more details
on completion, COLLECTION, and PREDICATE.
REQUIRE-MATCH can take the following values:
- t means that the user is not allowed to exit unless
the input is (or completes to) an element of COLLECTION or is null.
- nil means that the user can exit with any input.
- `confirm' means that the user can exit with any input, but she needs
to confirm her choice if the input is not an element of COLLECTION.
- `confirm-after-completion' means that the user can exit with any
input, but she needs to confirm her choice if she called
`minibuffer-complete' right before `minibuffer-complete-and-exit'
and the input is not an element of COLLECTION.
- anything else behaves like t except that typing RET does not exit if it
does non-null completion.
If the input is null, `completing-read' returns DEF, or the first element
of the list of default values, or an empty string if DEF is nil,
regardless of the value of REQUIRE-MATCH.
If INITIAL-INPUT is non-nil, insert it in the minibuffer initially,
with point positioned at the end.
If it is (STRING . POSITION), the initial input is STRING, but point
is placed at _zero-indexed_ position POSITION in STRING. (*Note*
that this is different from `read-from-minibuffer' and related
functions, which use one-indexing for POSITION.) This feature is
deprecated--it is best to pass nil for INITIAL-INPUT and supply the
default value DEF instead. The user can yank the default value into
the minibuffer easily using \\<minibuffer-local-map>\\[next-history-element].
HIST, if non-nil, specifies a history list and optionally the initial
position in the list. It can be a symbol, which is the history list
variable to use, or it can be a cons cell (HISTVAR . HISTPOS). In
that case, HISTVAR is the history list variable to use, and HISTPOS
is the initial position (the position in the list used by the
minibuffer history commands). For consistency, you should also
specify that element of the history as the value of
INITIAL-INPUT. (This is the only case in which you should use
INITIAL-INPUT instead of DEF.) Positions are counted starting from
1 at the beginning of the list. The variable `history-length'
controls the maximum length of a history list.
DEF, if non-nil, is the default value or the list of default values.
If INHERIT-INPUT-METHOD is non-nil, the minibuffer inherits
the current input method and the setting of `enable-multibyte-characters'.
Completion ignores case if the ambient value of
`completion-ignore-case' is non-nil.
See also `completing-read-function'. */)
(Lisp_Object prompt, Lisp_Object collection, Lisp_Object predicate, Lisp_Object require_match, Lisp_Object initial_input, Lisp_Object hist, Lisp_Object def, Lisp_Object inherit_input_method)
{
Lisp_Object args[9];
args[0] = Fsymbol_value (intern ("completing-read-function"));
args[1] = prompt;
args[2] = collection;
args[3] = predicate;
args[4] = require_match;
args[5] = initial_input;
args[6] = hist;
args[7] = def;
args[8] = inherit_input_method;
return Ffuncall (9, args);
}
/* Test whether TXT is an exact completion. */
DEFUN ("test-completion", Ftest_completion, Stest_completion, 2, 3, 0,
doc: /* Return non-nil if STRING is a valid completion.
Takes the same arguments as `all-completions' and `try-completion'.
If COLLECTION is a function, it is called with three arguments:
the values STRING, PREDICATE and `lambda'. */)
(Lisp_Object string, Lisp_Object collection, Lisp_Object predicate)
{
Lisp_Object regexps, tail, tem = Qnil;
ptrdiff_t i = 0;
CHECK_STRING (string);
if ((CONSP (collection)
&& (!SYMBOLP (XCAR (collection)) || NILP (XCAR (collection))))
|| NILP (collection))
{
tem = Fassoc_string (string, collection, completion_ignore_case ? Qt : Qnil);
if (NILP (tem))
return Qnil;
}
else if (VECTORP (collection))
{
/* Bypass intern-soft as that loses for nil. */
tem = oblookup (collection,
SSDATA (string),
SCHARS (string),
SBYTES (string));
if (!SYMBOLP (tem))
{
if (STRING_MULTIBYTE (string))
string = Fstring_make_unibyte (string);
else
string = Fstring_make_multibyte (string);
tem = oblookup (collection,
SSDATA (string),
SCHARS (string),
SBYTES (string));
}
if (completion_ignore_case && !SYMBOLP (tem))
{
for (i = ASIZE (collection) - 1; i >= 0; i--)
{
tail = AREF (collection, i);
if (SYMBOLP (tail))
while (1)
{
if (EQ (Fcompare_strings (string, make_number (0), Qnil,
Fsymbol_name (tail),
make_number (0) , Qnil, Qt),
Qt))
{
tem = tail;
break;
}
if (XSYMBOL (tail)->next == 0)
break;
XSETSYMBOL (tail, XSYMBOL (tail)->next);
}
}
}
if (!SYMBOLP (tem))
return Qnil;
}
else if (HASH_TABLE_P (collection))
{
struct Lisp_Hash_Table *h = XHASH_TABLE (collection);
Lisp_Object key = Qnil;
i = hash_lookup (h, string, NULL);
if (i >= 0)
tem = HASH_KEY (h, i);
else
for (i = 0; i < HASH_TABLE_SIZE (h); ++i)
if (!NILP (HASH_HASH (h, i))
&& (key = HASH_KEY (h, i),
SYMBOLP (key) ? key = Fsymbol_name (key) : key,
STRINGP (key))
&& EQ (Fcompare_strings (string, make_number (0), Qnil,
key, make_number (0) , Qnil,
completion_ignore_case ? Qt : Qnil),
Qt))
{
tem = key;
break;
}
if (!STRINGP (tem))
return Qnil;
}
else
return call3 (collection, string, predicate, Qlambda);
/* Reject this element if it fails to match all the regexps. */
if (CONSP (Vcompletion_regexp_list))
{
ptrdiff_t count = SPECPDL_INDEX ();
specbind (Qcase_fold_search, completion_ignore_case ? Qt : Qnil);
for (regexps = Vcompletion_regexp_list; CONSP (regexps);
regexps = XCDR (regexps))
{
if (NILP (Fstring_match (XCAR (regexps),
SYMBOLP (tem) ? string : tem,
Qnil)))
return unbind_to (count, Qnil);
}
unbind_to (count, Qnil);
}
/* Finally, check the predicate. */
if (!NILP (predicate))
{
return HASH_TABLE_P (collection)
? call2 (predicate, tem, HASH_VALUE (XHASH_TABLE (collection), i))
: call1 (predicate, tem);
}
else
return Qt;
}
static Lisp_Object Qmetadata;
DEFUN ("internal-complete-buffer", Finternal_complete_buffer, Sinternal_complete_buffer, 3, 3, 0,
doc: /* Perform completion on buffer names.
STRING and PREDICATE have the same meanings as in `try-completion',
`all-completions', and `test-completion'.
If FLAG is nil, invoke `try-completion'; if it is t, invoke
`all-completions'; otherwise invoke `test-completion'. */)
(Lisp_Object string, Lisp_Object predicate, Lisp_Object flag)
{
if (NILP (flag))
return Ftry_completion (string, Vbuffer_alist, predicate);
else if (EQ (flag, Qt))
{
Lisp_Object res = Fall_completions (string, Vbuffer_alist, predicate, Qnil);
if (SCHARS (string) > 0)
return res;
else
{ /* Strip out internal buffers. */
Lisp_Object bufs = res;
/* First, look for a non-internal buffer in `res'. */
while (CONSP (bufs) && SREF (XCAR (bufs), 0) == ' ')
bufs = XCDR (bufs);
if (NILP (bufs))
return (EQ (Flength (res), Flength (Vbuffer_alist))
/* If all bufs are internal don't strip them out. */
? res : bufs);
res = bufs;
while (CONSP (XCDR (bufs)))
if (SREF (XCAR (XCDR (bufs)), 0) == ' ')
XSETCDR (bufs, XCDR (XCDR (bufs)));
else
bufs = XCDR (bufs);
return res;
}
}
else if (EQ (flag, Qlambda))
return Ftest_completion (string, Vbuffer_alist, predicate);
else if (EQ (flag, Qmetadata))
return list2 (Qmetadata, Fcons (Qcategory, Qbuffer));
else
return Qnil;
}
/* Like assoc but assumes KEY is a string, and ignores case if appropriate. */
DEFUN ("assoc-string", Fassoc_string, Sassoc_string, 2, 3, 0,
doc: /* Like `assoc' but specifically for strings (and symbols).
This returns the first element of LIST whose car matches the string or
symbol KEY, or nil if no match exists. When performing the
comparison, symbols are first converted to strings, and unibyte
strings to multibyte. If the optional arg CASE-FOLD is non-nil, case
is ignored.
Unlike `assoc', KEY can also match an entry in LIST consisting of a
single string, rather than a cons cell whose car is a string. */)
(register Lisp_Object key, Lisp_Object list, Lisp_Object case_fold)
{
register Lisp_Object tail;
if (SYMBOLP (key))
key = Fsymbol_name (key);
for (tail = list; CONSP (tail); tail = XCDR (tail))
{
register Lisp_Object elt, tem, thiscar;
elt = XCAR (tail);
thiscar = CONSP (elt) ? XCAR (elt) : elt;
if (SYMBOLP (thiscar))
thiscar = Fsymbol_name (thiscar);
else if (!STRINGP (thiscar))
continue;
tem = Fcompare_strings (thiscar, make_number (0), Qnil,
key, make_number (0), Qnil,
case_fold);
if (EQ (tem, Qt))
return elt;
QUIT;
}
return Qnil;
}
DEFUN ("minibuffer-depth", Fminibuffer_depth, Sminibuffer_depth, 0, 0, 0,
doc: /* Return current depth of activations of minibuffer, a nonnegative integer. */)
(void)
{
return make_number (minibuf_level);
}
DEFUN ("minibuffer-prompt", Fminibuffer_prompt, Sminibuffer_prompt, 0, 0, 0,
doc: /* Return the prompt string of the currently-active minibuffer.
If no minibuffer is active, return nil. */)
(void)
{
return Fcopy_sequence (minibuf_prompt);
}
void
init_minibuf_once (void)
{
Vminibuffer_list = Qnil;
staticpro (&Vminibuffer_list);
}
void
syms_of_minibuf (void)
{
minibuf_level = 0;
minibuf_prompt = Qnil;
staticpro (&minibuf_prompt);
minibuf_save_list = Qnil;
staticpro (&minibuf_save_list);
DEFSYM (Qcompletion_ignore_case, "completion-ignore-case");
DEFSYM (Qread_file_name_internal, "read-file-name-internal");
DEFSYM (Qminibuffer_default, "minibuffer-default");
Fset (Qminibuffer_default, Qnil);
DEFSYM (Qminibuffer_completion_table, "minibuffer-completion-table");
DEFSYM (Qminibuffer_completion_confirm, "minibuffer-completion-confirm");
DEFSYM (Qminibuffer_completion_predicate, "minibuffer-completion-predicate");
staticpro (&last_minibuf_string);
last_minibuf_string = Qnil;
DEFSYM (Qminibuffer_history, "minibuffer-history");
DEFSYM (Qbuffer_name_history, "buffer-name-history");
Fset (Qbuffer_name_history, Qnil);
DEFSYM (Qcustom_variable_p, "custom-variable-p");
DEFSYM (Qminibuffer_setup_hook, "minibuffer-setup-hook");
DEFSYM (Qminibuffer_exit_hook, "minibuffer-exit-hook");
DEFSYM (Qhistory_length, "history-length");
DEFSYM (Qcurrent_input_method, "current-input-method");
DEFSYM (Qactivate_input_method, "activate-input-method");
DEFSYM (Qcase_fold_search, "case-fold-search");
DEFSYM (Qmetadata, "metadata");
DEFVAR_LISP ("read-expression-history", Vread_expression_history,
doc: /* A history list for arguments that are Lisp expressions to evaluate.
For example, `eval-expression' uses this. */);
Vread_expression_history = Qnil;
DEFSYM (Qread_expression_history, "read-expression-history");
DEFVAR_LISP ("read-buffer-function", Vread_buffer_function,
doc: /* If this is non-nil, `read-buffer' does its work by calling this function.
The function is called with the arguments passed to `read-buffer'. */);
Vread_buffer_function = Qnil;
DEFVAR_BOOL ("read-buffer-completion-ignore-case",
read_buffer_completion_ignore_case,
doc: /* Non-nil means completion ignores case when reading a buffer name. */);
read_buffer_completion_ignore_case = 0;
DEFVAR_LISP ("minibuffer-setup-hook", Vminibuffer_setup_hook,
doc: /* Normal hook run just after entry to minibuffer. */);
Vminibuffer_setup_hook = Qnil;
DEFVAR_LISP ("minibuffer-exit-hook", Vminibuffer_exit_hook,
doc: /* Normal hook run just after exit from minibuffer. */);
Vminibuffer_exit_hook = Qnil;
DEFVAR_LISP ("history-length", Vhistory_length,
doc: /* Maximum length of history lists before truncation takes place.
A number means truncate to that length; truncation deletes old
elements, and is done just after inserting a new element.
A value of t means no truncation.
This variable only affects history lists that don't specify their own
maximum lengths. Setting the `history-length' property of a history
variable overrides this default. */);
XSETFASTINT (Vhistory_length, 30);
DEFVAR_BOOL ("history-delete-duplicates", history_delete_duplicates,
doc: /* Non-nil means to delete duplicates in history.
If set to t when adding a new history element, all previous identical
elements are deleted from the history list. */);
history_delete_duplicates = 0;
DEFVAR_LISP ("history-add-new-input", Vhistory_add_new_input,
doc: /* Non-nil means to add new elements in history.
If set to nil, minibuffer reading functions don't add new elements to the
history list, so it is possible to do this afterwards by calling
`add-to-history' explicitly. */);
Vhistory_add_new_input = Qt;
DEFVAR_BOOL ("completion-ignore-case", completion_ignore_case,
doc: /* Non-nil means don't consider case significant in completion.
For file-name completion, `read-file-name-completion-ignore-case'
controls the behavior, rather than this variable.
For buffer name completion, `read-buffer-completion-ignore-case'
controls the behavior, rather than this variable. */);
completion_ignore_case = 0;
DEFVAR_BOOL ("enable-recursive-minibuffers", enable_recursive_minibuffers,
doc: /* Non-nil means to allow minibuffer commands while in the minibuffer.
This variable makes a difference whenever the minibuffer window is active. */);
enable_recursive_minibuffers = 0;
DEFVAR_LISP ("minibuffer-completion-table", Vminibuffer_completion_table,
doc: /* Alist or obarray used for completion in the minibuffer.
This becomes the ALIST argument to `try-completion' and `all-completions'.
The value can also be a list of strings or a hash table.
The value may alternatively be a function, which is given three arguments:
STRING, the current buffer contents;
PREDICATE, the predicate for filtering possible matches;
CODE, which says what kind of things to do.
CODE can be nil, t or `lambda':
nil -- return the best completion of STRING, or nil if there is none.
t -- return a list of all possible completions of STRING.
lambda -- return t if STRING is a valid completion as it stands. */);
Vminibuffer_completion_table = Qnil;
DEFVAR_LISP ("minibuffer-completion-predicate", Vminibuffer_completion_predicate,
doc: /* Within call to `completing-read', this holds the PREDICATE argument. */);
Vminibuffer_completion_predicate = Qnil;
DEFVAR_LISP ("minibuffer-completion-confirm", Vminibuffer_completion_confirm,
doc: /* Whether to demand confirmation of completion before exiting minibuffer.
If nil, confirmation is not required.
If the value is `confirm', the user may exit with an input that is not
a valid completion alternative, but Emacs asks for confirmation.
If the value is `confirm-after-completion', the user may exit with an
input that is not a valid completion alternative, but Emacs asks for
confirmation if the user submitted the input right after any of the
completion commands listed in `minibuffer-confirm-exit-commands'. */);
Vminibuffer_completion_confirm = Qnil;
DEFVAR_LISP ("minibuffer-completing-file-name",
Vminibuffer_completing_file_name,
doc: /* Non-nil means completing file names. */);
Vminibuffer_completing_file_name = Qnil;
DEFVAR_LISP ("minibuffer-help-form", Vminibuffer_help_form,
doc: /* Value that `help-form' takes on inside the minibuffer. */);
Vminibuffer_help_form = Qnil;
DEFVAR_LISP ("minibuffer-history-variable", Vminibuffer_history_variable,
doc: /* History list symbol to add minibuffer values to.
Each string of minibuffer input, as it appears on exit from the minibuffer,
is added with
(set minibuffer-history-variable
(cons STRING (symbol-value minibuffer-history-variable))) */);
XSETFASTINT (Vminibuffer_history_variable, 0);
DEFVAR_LISP ("minibuffer-history-position", Vminibuffer_history_position,
doc: /* Current position of redoing in the history list. */);
Vminibuffer_history_position = Qnil;
DEFVAR_BOOL ("minibuffer-auto-raise", minibuffer_auto_raise,
doc: /* Non-nil means entering the minibuffer raises the minibuffer's frame.
Some uses of the echo area also raise that frame (since they use it too). */);
minibuffer_auto_raise = 0;
DEFVAR_LISP ("completion-regexp-list", Vcompletion_regexp_list,
doc: /* List of regexps that should restrict possible completions.
The basic completion functions only consider a completion acceptable
if it matches all regular expressions in this list, with
`case-fold-search' bound to the value of `completion-ignore-case'.
See Info node `(elisp)Basic Completion', for a description of these
functions. */);
Vcompletion_regexp_list = Qnil;
DEFVAR_BOOL ("minibuffer-allow-text-properties",
minibuffer_allow_text_properties,
doc: /* Non-nil means `read-from-minibuffer' should not discard text properties.
This also affects `read-string', but it does not affect `read-minibuffer',
`read-no-blanks-input', or any of the functions that do minibuffer input
with completion; they always discard text properties. */);
minibuffer_allow_text_properties = 0;
DEFVAR_LISP ("minibuffer-prompt-properties", Vminibuffer_prompt_properties,
doc: /* Text properties that are added to minibuffer prompts.
These are in addition to the basic `field' property, and stickiness
properties. */);
/* We use `intern' here instead of Qread_only to avoid
initialization-order problems. */
Vminibuffer_prompt_properties = list2 (intern_c_string ("read-only"), Qt);
defsubr (&Sactive_minibuffer_window);
defsubr (&Sset_minibuffer_window);
defsubr (&Sread_from_minibuffer);
defsubr (&Sread_string);
defsubr (&Sread_command);
defsubr (&Sread_variable);
defsubr (&Sinternal_complete_buffer);
defsubr (&Sread_buffer);
defsubr (&Sread_no_blanks_input);
defsubr (&Sminibuffer_depth);
defsubr (&Sminibuffer_prompt);
defsubr (&Sminibufferp);
defsubr (&Sminibuffer_prompt_end);
defsubr (&Sminibuffer_contents);
defsubr (&Sminibuffer_contents_no_properties);
defsubr (&Sminibuffer_completion_contents);
defsubr (&Stry_completion);
defsubr (&Sall_completions);
defsubr (&Stest_completion);
defsubr (&Sassoc_string);
defsubr (&Scompleting_read);
}
| jave/xwidget-emacs | src/minibuf.c | C | gpl-3.0 | 71,982 | [
30522,
1013,
1008,
7163,
8569,
12494,
7953,
1998,
6503,
1012,
9385,
1006,
1039,
1007,
3106,
1011,
3069,
1010,
2857,
1011,
2286,
2489,
4007,
3192,
1010,
4297,
1012,
2023,
5371,
2003,
2112,
1997,
27004,
7861,
6305,
2015,
1012,
27004,
7861,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package org.blendee.internal;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
/**
* 内部使用ユーティリティクラス
* @author 千葉 哲嗣
* @param <K> Key
* @param <V> Value
*/
@SuppressWarnings("javadoc")
public class CollectionMap<K, V> implements Cloneable {
private final Map<K, Collection<V>> map;
public static <V, K> CollectionMap<K, V> newInstance() {
return new CollectionMap<>();
}
public static <V, K> CollectionMap<K, V> newInstance(
@SuppressWarnings("rawtypes")
Class<? extends Map> mapClass) {
return new CollectionMap<>(mapClass);
}
public CollectionMap() {
map = new HashMap<>();
}
@SuppressWarnings("unchecked")
public CollectionMap(
@SuppressWarnings("rawtypes")
Class<? extends Map> mapClass) {
try {
this.map = mapClass.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void put(K key, V value) {
var collection = get(key);
collection.add(value);
}
public Collection<V> get(K key) {
Collection<V> collection = map.get(key);
if (collection == null) {
collection = createNewCollection();
map.put(key, collection);
}
return collection;
}
public Set<K> keySet() {
return map.keySet();
}
public Collection<V> remove(K key) {
Collection<V> collection = map.remove(key);
if (collection == null) return createNewCollection();
return collection;
}
public int size() {
return map.size();
}
public void clear() {
map.clear();
}
public boolean containsKey(K key) {
return map.containsKey(key);
}
public Map<K, Collection<V>> getInnerMap() {
return Collections.unmodifiableMap(map);
}
@Override
public CollectionMap<K, V> clone() {
CollectionMap<K, V> clone = newInstance(map.getClass());
for (var entry : map.entrySet()) {
var key = entry.getKey();
for (var value : entry.getValue()) {
clone.put(key, value);
}
}
return clone;
}
@Override
public String toString() {
return U.toString(this);
}
protected Collection<V> createNewCollection() {
return new LinkedList<>();
}
}
| blendee/blendee | src/main/java/org/blendee/internal/CollectionMap.java | Java | mit | 2,203 | [
30522,
7427,
8917,
1012,
12586,
4402,
1012,
4722,
1025,
12324,
9262,
1012,
21183,
4014,
1012,
3074,
1025,
12324,
9262,
1012,
21183,
4014,
1012,
6407,
1025,
12324,
9262,
1012,
21183,
4014,
1012,
23325,
2863,
2361,
1025,
12324,
9262,
1012,
21... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
TARGET = runmilan.prg
AS = vasm
ASFLAGS = -devpac -m68040 -Ftos
$(TARGET): main.s
$(AS) $(ASFLAGS) -o $@ $<
clean:
rm -f $(TARGET) *~
| mikrosk/running | milan/Makefile | Makefile | gpl-2.0 | 139 | [
30522,
4539,
1027,
2448,
4328,
5802,
1012,
10975,
2290,
2004,
1027,
12436,
6491,
2004,
10258,
26454,
1027,
1011,
16475,
19498,
1011,
1049,
2575,
17914,
12740,
1011,
3027,
2891,
1002,
1006,
4539,
1007,
1024,
2364,
1012,
1055,
1002,
1006,
200... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, shrink-to-fit=no, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Litecoin</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Hotjar Tracking Code for https://kristiano92.github.io/ -->
<script>
(function(h,o,t,j,a,r){
h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
h._hjSettings={hjid:367063,hjsv:5};
a=o.getElementsByTagName('head')[0];
r=o.createElement('script');r.async=1;
r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
a.appendChild(r);
})(window,document,'//static.hotjar.com/c/hotjar-','.js?sv=');
</script>
</head>
<body>
<div id="wrapper">
<!-- Page Content -->
<div id="page-content-wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<h1>Litecoin</h1>
<p>Litecoin – kryptowaluta, a także otwarto-źródłowy projekt na licencji X11. Zainspirowany i niemal identyczny technicznie jak bitcoin, litecoin jest tworzony i przekazywany bez udziału centralnego emitenta. Różni się on od bitcoina trzema podstawowymi cechami:
Po pierwsze sieć litecoin przetwarza blok co 2,5 minuty, podczas gdy bitcoin robi to co 10 minut, co według twórców litecoina pozwala na szybsze potwierdzenie transakcji. Analogicznie jak dla bitcoina[1], trudność sieci dostosowuje się do dostępnej mocy obliczeniowej, wykorzystując kroczącą średnią tak, żeby każdy nowy blok wydobywany był raz na 2,5 minuty.
Po drugie sieć litecoin wyprodukuje 84 miliony litecoinów, tj. czterokrotnie więcej, niż ma to miejsce w przypadku sieci bitcoin.
Po trzecie litecoin opiera się na Scrypt jako matematycznym dowodzie (proof of work) wykonywanych działań. Stworzenie koparek FPGA i ASIC, wykorzystujących Scrypt, wydaje się o wiele trudniejsze niż układów korzystających z SHA-256 na potrzeby sieci bitcoin oraz kosztowniejsze z powodu konieczności zastosowania szybkich pamięci. Ponadto wydajność ew. układów nie powinna się znacząco różnić od obecnie wykorzystywanych GPU, ponieważ największy wpływ na wydajność obliczeń Scrypt ma szybkość pamięci.</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/VOVKowJkk2A" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
<!-- /#page-content-wrapper -->
</div>
<!-- /#wrapper -->
<canvas id="canvas" style="display:none;"></canvas>
<script type="text/javascript">
var can = document.getElementById('canvas');
var ctx = can.getContext('2d');
var img = new Image();
img.onload = function(){
can.width = screen.width; // pobieramy szerokość ekranu
can.height = screen.height; // pobieramy wysokość ekranu
ctx.drawImage(img, 0, 0, can.width, can.height);
document.body.style.backgroundImage = 'url('+can.toDataURL('image/jpeg')+')';
}
img.src = 'litecoin.jpg'; // wczytanie grafiki
</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','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-86297746-1', 'auto');
ga('send', 'pageview');
</script>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
| kristiano92/kristiano92.github.io | Litecoin/index.html | HTML | mit | 4,085 | [
30522,
1026,
999,
9986,
13874,
16129,
1028,
1026,
16129,
11374,
1027,
1000,
4372,
1000,
1028,
1026,
2132,
1028,
1026,
18804,
25869,
13462,
1027,
1000,
21183,
2546,
1011,
1022,
1000,
1028,
1026,
18804,
8299,
1011,
1041,
15549,
2615,
1027,
10... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package com.pepoc.joke.view.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.pepoc.joke.R;
import com.pepoc.joke.data.bean.JokeComment;
import com.pepoc.joke.data.bean.JokeContent;
import com.pepoc.joke.data.user.UserManager;
import com.pepoc.joke.presenter.JokeContentPresenter;
import com.pepoc.joke.util.Util;
import com.pepoc.joke.view.adapter.JokeContentAdapter;
import com.pepoc.joke.view.iview.IJokeContentView;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
public class JokeContentActivity extends BaseSwipeBackActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, IJokeContentView<JokeComment> {
@Bind(R.id.toolbar)
Toolbar toolbar;
@Bind(R.id.recyclerview_joke_content)
RecyclerView recyclerviewJokeContent;
@Bind(R.id.swiperefresh_joke_content)
SwipeRefreshLayout swiperefreshJokeContent;
@Bind(R.id.et_joke_comment)
EditText etJokeComment;
@Bind(R.id.btn_send_comment)
Button btnSendComment;
@Bind(R.id.rl_comment)
RelativeLayout rlComment;
private JokeContent jokeContent;
private JokeContentAdapter jokeContentAdapter;
private JokeContentPresenter jokeContentPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_joke_content);
ButterKnife.bind(this);
jokeContentPresenter = new JokeContentPresenter(this);
Intent intent = getIntent();
jokeContent = intent.getParcelableExtra("JokeContent");
init();
jokeContentPresenter.getComment(context, jokeContent.getJokeId());
}
@Override
public void init() {
super.init();
toolbar.setTitle(R.string.activity_joke_content);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
swiperefreshJokeContent.setColorSchemeResources(R.color.colorAccent);
swiperefreshJokeContent.setOnRefreshListener(this);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
recyclerviewJokeContent.setLayoutManager(linearLayoutManager);
jokeContentAdapter = new JokeContentAdapter(context, jokeContentPresenter);
jokeContentAdapter.setJokeContent(jokeContent);
recyclerviewJokeContent.setAdapter(jokeContentAdapter);
btnSendComment.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send_comment:
if (UserManager.getCurrentUser() != null) {
String commentContent = etJokeComment.getText().toString();
if (TextUtils.isEmpty(commentContent)) {
Toast.makeText(context, "评论内容不能为空", Toast.LENGTH_SHORT).show();
} else {
jokeContentPresenter.comment(context, jokeContent.getJokeId(), commentContent);
}
} else {
Toast.makeText(context, "登录后才能评论", Toast.LENGTH_SHORT).show();
}
break;
}
}
@Override
public void onRefresh() {
jokeContentPresenter.getComment(context, jokeContent.getJokeId());
}
@Override
public void showLoading() {
}
@Override
public void hideLoading() {
}
@Override
public void updateCommentData(List<JokeComment> datas) {
swiperefreshJokeContent.setRefreshing(false);
jokeContentAdapter.setJokeComments(datas);
jokeContentAdapter.notifyDataSetChanged();
}
@Override
public void commentSuccess() {
Toast.makeText(context, "comment success", Toast.LENGTH_SHORT).show();
etJokeComment.setText("");
Util.hiddenSoftKeyborad(etJokeComment, context);
jokeContentPresenter.getComment(context, jokeContent.getJokeId());
}
@Override
public void onError() {
swiperefreshJokeContent.setRefreshing(false);
}
}
| pepoc/Joke | Joke/app/src/main/java/com/pepoc/joke/view/activity/JokeContentActivity.java | Java | apache-2.0 | 4,698 | [
30522,
7427,
4012,
1012,
27233,
10085,
1012,
8257,
1012,
3193,
1012,
4023,
1025,
12324,
11924,
1012,
4180,
1012,
7848,
1025,
12324,
11924,
1012,
9808,
1012,
14012,
1025,
12324,
11924,
1012,
2490,
1012,
1058,
2549,
1012,
15536,
24291,
1012,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# -*- coding: utf-8 -*-
from django.core.cache import cache
from django.shortcuts import render
from django.http import Http404
from styleguide.utils import (Styleguide, STYLEGUIDE_DIR_NAME,
STYLEGUIDE_DEBUG, STYLEGUIDE_CACHE_NAME,
STYLEGUIDE_ACCESS)
def index(request, module_name=None, component_name=None):
if not STYLEGUIDE_ACCESS(request.user):
raise Http404()
styleguide = None
if not STYLEGUIDE_DEBUG:
styleguide = cache.get(STYLEGUIDE_CACHE_NAME)
if styleguide is None:
styleguide = Styleguide()
cache.set(STYLEGUIDE_CACHE_NAME, styleguide, None)
if module_name is not None:
styleguide.set_current_module(module_name)
context = {'styleguide': styleguide}
index_path = "%s/index.html" % STYLEGUIDE_DIR_NAME
return render(request, index_path, context)
| andrefarzat/django-styleguide | styleguide/views.py | Python | mit | 897 | [
30522,
1001,
1011,
1008,
1011,
16861,
1024,
21183,
2546,
1011,
1022,
1011,
1008,
1011,
2013,
6520,
23422,
1012,
4563,
1012,
17053,
12324,
17053,
2013,
6520,
23422,
1012,
2460,
12690,
2015,
12324,
17552,
2013,
6520,
23422,
1012,
8299,
12324,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
require "rss/rss"
module RSS
##
#
# Provides a set of builders for various RSS objects
#
# * Feeds
# * RSS 0.91
# * RSS 1.0
# * RSS 2.0
# * Atom 1.0
#
# * Elements
# * Atom::Entry
module Maker
# Collection of supported makers
MAKERS = {}
class << self
# Builder for an RSS object
# Creates an object of the type passed in +args+
#
# Executes the +block+ to populate elements of the created RSS object
def make(version, &block)
self[version].make(&block)
end
# Returns the maker for the +version+
def [](version)
maker_info = maker(version)
raise UnsupportedMakerVersionError.new(version) if maker_info.nil?
maker_info[:maker]
end
# Adds a maker to the set of supported makers
def add_maker(version, normalized_version, maker)
MAKERS[version] = {:maker => maker, :version => normalized_version}
end
# Returns collection of supported maker versions
def versions
MAKERS.keys.uniq.sort
end
# Returns collection of supported makers
def makers
MAKERS.values.collect { |info| info[:maker] }.uniq
end
# Returns true if the version is supported
def supported?(version)
versions.include?(version)
end
private
# Can I remove this method?
def maker(version)
MAKERS[version]
end
end
end
end
require "rss/maker/1.0"
require "rss/maker/2.0"
require "rss/maker/feed"
require "rss/maker/entry"
require "rss/maker/content"
require "rss/maker/dublincore"
require "rss/maker/slash"
require "rss/maker/syndication"
require "rss/maker/taxonomy"
require "rss/maker/trackback"
require "rss/maker/image"
require "rss/maker/itunes"
| jmatbastos/rbenv | versions/2.2.3/lib/ruby/2.2.0/rss/maker.rb | Ruby | mit | 1,793 | [
30522,
5478,
1000,
12667,
2015,
1013,
12667,
2015,
1000,
11336,
12667,
2015,
1001,
1001,
1001,
1001,
3640,
1037,
2275,
1997,
16472,
2005,
2536,
12667,
2015,
5200,
1001,
1001,
1008,
14172,
1001,
1008,
12667,
2015,
1014,
1012,
6205,
1001,
100... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
* A null-safe function to repeat the source string the desired amount of times.
* @private
* @param {String} source
* @param {Number} times
* @returns {String}
*/
function _repeat (source, times) {
var result = "";
for (var i = 0; i < times; i++) {
result += source;
}
return result;
}
export default _repeat;
| ascartabelli/lamb | src/privates/_repeat.js | JavaScript | mit | 347 | [
30522,
1013,
1008,
1008,
1008,
1037,
19701,
1011,
3647,
3853,
2000,
9377,
1996,
3120,
5164,
1996,
9059,
3815,
1997,
2335,
1012,
1008,
1030,
2797,
1008,
1030,
11498,
2213,
1063,
5164,
1065,
3120,
1008,
1030,
11498,
2213,
1063,
2193,
1065,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package org.cardiacatlas.xpacs.repository;
import org.cardiacatlas.xpacs.domain.PatientInfo;
import org.springframework.data.jpa.repository.*;
import java.util.List;
/**
* Spring Data JPA repository for the PatientInfo entity.
*/
@SuppressWarnings("unused")
public interface PatientInfoRepository extends JpaRepository<PatientInfo,Long> {
}
| CardiacAtlasProject/xpacs-web | src/main/java/org/cardiacatlas/xpacs/repository/PatientInfoRepository.java | Java | gpl-3.0 | 348 | [
30522,
7427,
8917,
1012,
15050,
4017,
8523,
1012,
26726,
6305,
2015,
1012,
22409,
1025,
12324,
8917,
1012,
15050,
4017,
8523,
1012,
26726,
6305,
2015,
1012,
5884,
1012,
5776,
2378,
14876,
1025,
12324,
8917,
1012,
3500,
15643,
6198,
1012,
29... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/* Copyright 2013 10gen 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.
*/
/* global describe, expect, it, mongo */
describe('The const module', function () {
it('stores keycode constants', function () {
var key = mongo.config.keycodes;
expect(key.enter).toBe(13);
expect(key.left).toBe(37);
expect(key.up).toBe(38);
expect(key.right).toBe(39);
expect(key.down).toBe(40);
});
it('stores the keep alive timeout', function () {
expect(mongo.config.keepAliveTime).toBeDefined();
});
it('stores the root element CSS selector', function () {
expect(mongo.config.rootElementSelector).toBeDefined();
});
it('stores the script name', function () {
expect(mongo.config.scriptName).toBeDefined();
});
it('stores the shell batch size', function () {
expect(mongo.config.shellBatchSize).toBeDefined();
});
it('gets and stores the MWS host', function () {
expect(mongo.config.mwsHost).toEqual('http://mwshost.example.com');
});
it('generates and stores the baseUrl', function(){
expect(mongo.config.baseUrl).toBeDefined();
expect(mongo.config.baseUrl.indexOf(mongo.config.mwsHost) > -1).toBe(true);
});
});
| greinerb/mongo-web-shell | frontend/spec/mws/config.spec.js | JavaScript | apache-2.0 | 1,723 | [
30522,
1013,
1008,
9385,
2286,
2184,
6914,
4297,
1012,
1008,
1008,
7000,
2104,
30524,
2224,
2023,
5371,
3272,
1999,
12646,
2007,
1996,
6105,
1012,
1008,
2017,
2089,
6855,
1037,
6100,
1997,
1996,
6105,
2012,
1008,
1008,
8299,
1024,
1013,
1... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
const simple_sort = (key, a, b) => {
if (a[key] < b[key]) return -1
if (a[key] > b[key]) return 1
return 0
}
const name_sort = (a, b) => simple_sort('name', a, b)
const skill_sort = (a, b) => simple_sort('skill', a, b)
const speed_sort = (a, b) => simple_sort('speed', a, b)
export {
simple_sort,
name_sort,
skill_sort,
speed_sort
} | stevegood/tython | util/sorting.js | JavaScript | mit | 348 | [
30522,
9530,
3367,
3722,
1035,
4066,
1027,
1006,
3145,
1010,
1037,
1010,
1038,
1007,
1027,
1028,
1063,
2065,
1006,
1037,
1031,
3145,
1033,
1026,
1038,
1031,
3145,
1033,
1007,
2709,
1011,
1015,
2065,
1006,
1037,
1031,
3145,
1033,
1028,
103... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package tutor.utils
import org.scalatest.{FunSpec, Matchers}
class FileUtilSpec extends FunSpec with Matchers {
describe("FileUtil"){
it("can extract file extension name"){
val path = "src/test/build.sbt"
FileUtil.extractExtFileName(path) shouldBe "sbt"
}
it("if file has no extension name, should give EmptyFileType constant"){
val path = "src/test/build"
FileUtil.extractExtFileName(path) shouldBe FileUtil.EmptyFileType
}
it("can extract local file path"){
val path = "src/test/build.sbt"
FileUtil.extractLocalPath(path) shouldBe "build.sbt"
}
}
}
| notyy/CodeAnalyzerTutorial | src/test/scala/tutor/utils/FileUtilSpec.scala | Scala | apache-2.0 | 617 | [
30522,
7427,
14924,
1012,
21183,
12146,
12324,
8917,
1012,
26743,
22199,
1012,
1063,
4569,
13102,
8586,
1010,
2674,
2545,
1065,
2465,
5371,
21823,
4877,
5051,
2278,
8908,
4569,
13102,
8586,
2007,
2674,
2545,
1063,
6235,
1006,
1000,
5371,
21... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
export default {
cache: function (state, payload) {
state.apiCache[payload.api_url] = payload.api_response;
},
addConfiguredType: function (state, type) {
state.configuredTypes.push(type);
},
removeConfiguredType: function (state, index) {
state.configuredTypes.splice(index, 1);
},
updateConfiguredType: function (state, type) {
for (var i = 0, len = state.configuredTypes.length; i < len; i++) {
if (state.configuredTypes[i].name === type.name) {
state.configuredTypes.splice(i, 1);
state.configuredTypes.push(type);
// Avoid too keep looping over a spliced array
return;
}
}
},
setBaseExtraFormTypes: function (state, types) {
state.baseTypes = types;
},
setConfiguredExtraFormTypes: function (state, types) {
state.configuredTypes = types;
}
};
| IDCI-Consulting/ExtraFormBundle | Resources/public/js/editor/src/store/mutations.js | JavaScript | mit | 854 | [
30522,
9167,
12398,
1063,
17053,
1024,
3853,
1006,
2110,
1010,
18093,
1007,
1063,
2110,
1012,
17928,
3540,
5403,
1031,
18093,
1012,
17928,
1035,
24471,
2140,
1033,
1027,
18093,
1012,
17928,
1035,
3433,
1025,
1065,
1010,
5587,
8663,
8873,
27... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/* tslint:disable:no-unused-variable */
import { TestBed, async } from "@angular/core/testing";
import { FormBuilder } from "@angular/forms";
import { Router } from "@angular/router";
import { MemberAddComponent } from "./member-add.component";
import { StubMemberService } from "../member.service.stub";
describe("Component: MemberAdd", () => {
function mockComp(): MemberAddComponent {
const keys = [];
for (const key in Router.prototype) {
if (Router.prototype.hasOwnProperty(key)) {
keys.push(key);
}
}
const builder = new FormBuilder();
const router = jasmine.createSpyObj("MockRouter", keys);
const service = new StubMemberService();
return new MemberAddComponent(builder, service, router);
}
it("should create an instance", async(() => {
const component = mockComp();
expect(component).toBeTruthy();
}));
});
| jSherz/lsd-members | frontend/src/app/admin/member/member-add/member-add.component.spec.ts | TypeScript | mit | 887 | [
30522,
1013,
1008,
24529,
4115,
2102,
1024,
4487,
19150,
1024,
2053,
1011,
15171,
1011,
8023,
1008,
1013,
12324,
1063,
3231,
8270,
1010,
2004,
6038,
2278,
1065,
2013,
1000,
1030,
16108,
1013,
4563,
1013,
5604,
1000,
1025,
12324,
1063,
2433,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Copyright (c) 2016 Juniper Networks, Inc. All rights reserved.
*/
define([ 'lodash',
'controlnode-widgetcfg', 'vrouter-widgetcfg','databasenode-widgetcfg',
'analyticsnode-widgetcfg','confignode-widgetcfg','monitor-infra-widgetcfg',
'security-dashboard-widgetcfg',
'confignode-modelcfg','controlnode-modelcfg','vrouter-modelcfg',
'databasenode-modelcfg','analyticsnode-modelcfg','monitor-infra-modelcfg',
'security-dashboard-modelcfg',
'monitor-infra-viewcfg','confignode-viewcfg', 'databasenode-viewcfg',
'vrouter-viewcfg', 'security-dashboard-viewcfg', 'alarms-viewconfig'
], function(
_,ControlNodeWidgetCfg, VRouterWidgetCfg, DBNodeWidgetCfg,
AnalyticsNodeWidgetCfg, CfgNodeWidgetCfg,MonitorInfraWidgetCfg,
SecurityDashboardWidgetCfg,
CfgNodeModelCfg,ControlNodeModelCfg,VRouterModelCfg,DatabaseNodeModelCfg,
AnaltyicsNodeModelCfg,MonitorInfraModelCfg,SecurityDashboardModelCfg,
MonitorInfraViewCfg,CfgNodeViewCfg, DBNodeViewCfg, VRouterViewCfg,
SecurityDashboardViewConfig, AlarmsViewConfig, SecurityDashboardViewCfg ) {
var widgetCfgManager = function() {
var self = this;
var widgetCfgMap = {},
widgetViewCfgMap = {},
widgetModelCfgMap = {};
//Populate the available widget config maps
$.extend(widgetCfgMap, ControlNodeWidgetCfg, VRouterWidgetCfg,
DBNodeWidgetCfg, AnalyticsNodeWidgetCfg,
CfgNodeWidgetCfg,MonitorInfraWidgetCfg, SecurityDashboardWidgetCfg);
//Populate the available model config maps
$.extend(widgetModelCfgMap, CfgNodeModelCfg,ControlNodeModelCfg,VRouterModelCfg,
DatabaseNodeModelCfg,AnaltyicsNodeModelCfg,MonitorInfraModelCfg,
SecurityDashboardModelCfg);
$.extend(widgetViewCfgMap, MonitorInfraViewCfg, CfgNodeViewCfg,
DBNodeViewCfg, VRouterViewCfg, SecurityDashboardViewConfig, AlarmsViewConfig,
SecurityDashboardViewCfg);
//,ControlNodeViewCfg,VRouterViewCfg,DatabaseNodeViewCfg,AnaltyicsNodeViewCfg,);
self.get = function(widgetId,overrideCfg,i) {
var widgetCfg = _.isFunction(widgetCfgMap[widgetId]) ? widgetCfgMap[widgetId](overrideCfg,i) : widgetCfgMap[widgetId];
if (widgetCfg == null) {
widgetCfg = _.isFunction(widgetViewCfgMap[widgetId]) ? widgetViewCfgMap[widgetId](overrideCfg) : widgetViewCfgMap[widgetId];
}
var modelCfg = {},viewCfg = {},baseModelCfg;
if(widgetCfg['baseModel'] != null) {
baseModelCfg = widgetModelCfgMap[widgetCfg['baseModel']];
if(widgetCfg['modelCfg'] != null) {
$.extend(true,modelCfg,baseModelCfg,widgetCfg['modelCfg'])
} else {
modelCfg = baseModelCfg;
}
if(_.result(baseModelCfg,'type','')) {
widgetCfg['tag'] = baseModelCfg['type'];
}
widgetCfg['modelCfg'] = modelCfg;
}
if(_.result(widgetCfg,'modelCfg.type','')) {
widgetCfg['tag'] = _.result(widgetCfg,'modelCfg.type');
}
if(widgetCfg['baseView'] != null) {
baseViewCfg = widgetViewCfgMap[widgetCfg['baseView']];
if(widgetCfg['viewCfg'] != null) {
$.extend(true,viewCfg,baseViewCfg,widgetCfg['viewCfg'])
} else {
viewCfg= baseViewCfg;
}
widgetCfg['viewCfg'] = viewCfg;
}
return widgetCfg;
}
//Returns list of available widgets
self.getWidgetList = function() {
// return _.keys(widgetCfgMap);
var widgetMap = _.map(_.keys(widgetCfgMap),function(widgetId) {
return {
key: widgetId,
value: self.get(widgetId),
tag: self.get(widgetId)['tag']
}
});
widgetMap = _.groupBy(widgetMap,function(d) {
return d.tag;
});
//Pick yAxisLabel if exists else return widgetId
return _.map(widgetMap,function(value,key) {
return {
text: key,
children: _.map(value, function(widgetCfg) {
return {
id:widgetCfg['key'],
text:_.result(widgetCfg['value'],'viewCfg.viewConfig.chartOptions.yAxisLabel',widgetCfg['key'])
}
})
// val:_.result(widgetCfg['value'],'viewCfg.viewConfig.chartOptions.yAxisLabel',widgetCfg['key'])
}
});
}
self.modelInstMap = {};
}
return new widgetCfgManager();
});
| biswajit-mandal/contrail-web-core | webroot/js/widget.configmanager.js | JavaScript | apache-2.0 | 4,969 | [
30522,
1013,
1008,
1008,
9385,
1006,
1039,
1007,
2355,
29425,
6125,
1010,
4297,
1012,
2035,
2916,
9235,
1012,
1008,
1013,
9375,
1006,
1031,
1005,
8840,
8883,
2232,
1005,
1010,
1005,
2491,
3630,
3207,
1011,
15536,
24291,
2278,
2546,
2290,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
'use strict';
const assert = require('assert');
const HttpResponse = require('./http-response');
describe('HttpResponse', () => {
const mockResponse = {
version: '1.0',
status: '200 OK'
};
it('should create an instance', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.ok(httpResponse instanceof HttpResponse);
});
describe('isProtocolVersion()', () => {
it('should determine if protocol version matches', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.ok(httpResponse.isProtocolVersion('1.0'));
});
it('should return false if versions do not match', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.isProtocolVersion('2.0'), false);
});
it('should throw an error if no version specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.isProtocolVersion, /Specify a protocol `version`/);
});
it('should throw an error if no version specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() =>
httpResponse.isProtocolVersion(false), /The protocol `version` must be a string/);
});
});
describe('getProtocolVersion()', () => {
it('should get the protocol version', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getProtocolVersion(), '1.0');
});
});
describe('setProtocolVersion()', () => {
it('should set the protocol version', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getProtocolVersion(), '1.0');
httpResponse.setProtocolVersion('2.0');
assert.equal(httpResponse.getProtocolVersion(), '2.0');
});
it('should throw an error if no version specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.setProtocolVersion, /Specify a protocol `version`/);
});
it('should throw an error if no version specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() =>
httpResponse.setProtocolVersion(Boolean), /The protocol `version` must be a string/);
});
});
describe('isStatus()', () => {
it('should determine if status matches', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.ok(httpResponse.isStatus('200 OK'));
});
it('should return false if status do not match', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.isStatus('400 Bad Request'), false);
});
it('should throw an error if no status specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.isStatus, /Specify a `status`/);
});
it('should throw an error if specified status is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.isStatus({}), /The `status` must be a string/);
});
});
describe('getStatus()', () => {
it('should return the status', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
});
});
describe('getStatusCode()', () => {
it('should return status code', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatusCode(), '200');
});
});
describe('getStatusText()', () => {
it('should return status text', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatusText(), 'OK');
});
});
describe('setStatus()', () => {
it('should set the status', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
httpResponse.setStatus(400, 'Bad Request');
assert.equal(httpResponse.getStatus(), '400 Bad Request');
});
it('should throw an error if no code specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
assert.throws(() => httpResponse.setStatus(void 0, 'Bad Request'), /Specify a status `code`/);
});
it('should throw an error if the code is not an integer', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
assert.throws(() =>
httpResponse.setStatus('200', 'Bad Request'), /The status `code` must be an integer/);
});
it('should throw an error if no text specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
assert.throws(() => httpResponse.setStatus(400, void 0), /Specify a status `text`/);
});
it('should throw an error if specified text is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.getStatus(), '200 OK');
assert.throws(() => httpResponse.setStatus(400, true), /The status `text` must be a string/);
});
});
describe('hasHeader()', () => {
it('should determine if header has been set', () => {
const _mockResponse = Object.assign({headers: {'Content-Type': 'test'}}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.ok(httpResponse.hasHeader('Content-Type'));
});
it('should return false if header has not been set', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.hasHeader('Content-Type'), false);
});
it('should throw an error if no header `name` specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.hasHeader, /Specify a header `name`/);
});
it('should throw an error if specified header `name` is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.hasHeader({}), /The header `name` must be a string/);
});
});
describe('getHeader()', () => {
it('should return the header with the specified `name`', () => {
const _mockResponse = Object.assign({headers: {'Content-Type': ['test']}}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.equal(httpResponse.getHeader('Content-Type'), 'test');
});
it('should return the default value if specified header does not exist', () => {
const _mockResponse = Object.assign({headers: {}}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
const defaultValue = 'text/plain';
assert.equal(httpResponse.getHeader('Content-Type', defaultValue), defaultValue);
});
it('should throw an error if no header `name` specified', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(httpResponse.getHeader, /Specify a header `name`/);
});
it('should throw an error if specified header `name` is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.getHeader({}), /The header `name` must be a string/);
});
});
describe('getHeaders()', () => {
it('should return all headers', () => {
const headers = {'Content-Type': ['test']};
const _mockResponse = Object.assign({headers}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.deepEqual(httpResponse.getHeaders(), {'Content-Type': 'test'});
});
it('should return an empty set of headers when none are set', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.deepEqual(httpResponse.getHeaders(), {});
});
});
describe('setHeader()', () => {
it('should set a header in the httpResponse', () => {
const httpResponse = new HttpResponse(mockResponse);
httpResponse.setHeader('Content-Type', 'test');
assert.ok(httpResponse.hasHeader('Content-Type'));
assert.equal(httpResponse.getHeader('Content-Type'), 'test');
});
it('should throw an error if a header `name` is not defined', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.setHeader(void 0, 'test'), /Specify a header `name`/);
});
it('should throw an error if a header `name` is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() =>
httpResponse.setHeader(false, 'test'), /The header `name` must be a string/);
});
it('should throw an error if a header `value` is not defined', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() =>
httpResponse.setHeader('Content-Type', void 0), /Specify a header `value`/);
});
it('should throw an error if a header `name` is not a string', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.throws(() => httpResponse.setHeader('Content-Type', []),
/The header `value` must be a string/);
});
it('should register a new header as an array with 1 value', () => {
const httpResponse = new HttpResponse(mockResponse);
httpResponse.setHeader('X-Test', 'test');
assert.ok(httpResponse.hasHeader('X-Test'));
assert.deepEqual(httpResponse.getHeaderArray('X-Test'), ['test']);
});
});
describe('hasBody()', () => {
it('should determine if the httpResponse has a `body`', () => {
const _mockResponse = Object.assign({body: ' '}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.ok(httpResponse.hasBody());
});
it('should return false if the esponse do not have a `body`', () => {
const httpResponse = new HttpResponse(mockResponse);
assert.equal(httpResponse.hasBody(), false);
});
});
describe('getBody()', () => {
it('should return the content of the httpResponse `body`', () => {
const body = ' ';
const _mockResponse = Object.assign({body}, mockResponse);
const httpResponse = new HttpResponse(_mockResponse);
assert.equal(httpResponse.getBody(), body);
});
});
describe('setBody()', () => {
it('should set the content of the httpResponse `body`', () => {
const body = ' ';
const httpResponse = new HttpResponse(mockResponse);
httpResponse.setBody(body);
assert.equal(httpResponse.getBody(), body);
});
});
});
| orestes/katana-sdk-node | sdk/http-response.test.js | JavaScript | mit | 10,676 | [
30522,
1005,
2224,
9384,
1005,
1025,
9530,
3367,
20865,
1027,
5478,
1006,
1005,
20865,
1005,
1007,
1025,
9530,
3367,
8299,
6072,
26029,
3366,
1027,
5478,
1006,
1005,
1012,
1013,
8299,
1011,
3433,
1005,
1007,
1025,
6235,
1006,
1005,
8299,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* ================================
* eli960@qq.com
* https://blog.csdn.net/eli960
* 2015-09-29
* ================================
*/
#include "zc.h"
typedef struct zargv_mpool_t zargv_mpool_t;
struct zargv_mpool_t {
zargv_t v;
zmpool_t *mpool;
};
void zargv_init(zargv_t *argvp, int size);
void zargv_fini(zargv_t *argvp);
zargv_t *zargv_create(int size)
{
zargv_t *argvp = (zargv_t *) zmalloc(sizeof(zargv_t));
zargv_init(argvp, size);
return (argvp);
}
void zargv_init(zargv_t *argvp, int size)
{
int sane_size = (size < 0 ? 13 : size);
argvp->argv = (char **)zmalloc((sane_size + 1) * sizeof(char *));
argvp->size = sane_size;
argvp->argc = 0;
argvp->argv[0] = 0;
argvp->mpool_used = 0;
}
void zargv_init_mpool(zargv_t *argvp, int size, zmpool_t *mpool)
{
int sane_size = (size < 0 ? 13 : size);
argvp->argv = (char **)zmpool_malloc(mpool, (sane_size + 1) * sizeof(char *));
argvp->size = sane_size;
argvp->argc = 0;
argvp->argv[0] = 0;
argvp->mpool_used = 1;
zargv_mpool_t *ama = (zargv_mpool_t *)argvp;
ama->mpool = mpool;
}
void zargv_fini(zargv_t *argvp)
{
zargv_mpool_t *ama = (zargv_mpool_t *)argvp;
char **cpp;
for (cpp = argvp->argv; cpp < argvp->argv + argvp->argc; cpp++) {
if (argvp->mpool_used) {
zmpool_free(ama->mpool, *cpp);
} else {
zfree(*cpp);
}
}
if (argvp->mpool_used) {
zmpool_free(ama->mpool, argvp->argv);
} else {
zfree(argvp->argv);
}
}
void zargv_free(zargv_t * argvp)
{
if (argvp) {
zargv_fini(argvp);
zfree(argvp);
}
}
static void zargv_extend(zargv_t * argvp)
{
int new_size = argvp->size * 2;
if (new_size < 1) {
new_size = 2;
}
if (argvp->mpool_used) {
zargv_mpool_t *ama = (zargv_mpool_t *)argvp;
char **npp = (char **)zmpool_malloc(ama->mpool, (new_size + 1) * sizeof(char *));
if (argvp->argc) {
memcpy(npp, argvp->argv, argvp->argc * sizeof(char *));
}
zmpool_free(ama->mpool, argvp->argv);
argvp->argv = npp;
} else {
argvp->argv = (char **)zrealloc(argvp->argv, (new_size + 1) * sizeof(char *));
}
argvp->size = new_size;
}
void zargv_add(zargv_t * argvp, const char *ns)
{
if (argvp->argc >= argvp->size) {
zargv_extend(argvp);
}
if (argvp->mpool_used) {
zargv_mpool_t *ama = (zargv_mpool_t *)argvp;
argvp->argv[argvp->argc++] = zmpool_strdup(ama->mpool, ns);
} else {
argvp->argv[argvp->argc++] = zstrdup(ns);
}
argvp->argv[argvp->argc] = 0;
}
void zargv_addn(zargv_t * argvp, const char *ns, int nlen)
{
if (argvp->argc >= argvp->size) {
zargv_extend(argvp);
}
if (argvp->mpool_used) {
zargv_mpool_t *ama = (zargv_mpool_t *)argvp;
argvp->argv[argvp->argc++] = zmpool_strndup(ama->mpool, ns, nlen);
} else {
argvp->argv[argvp->argc++] = zstrndup(ns, nlen);
}
argvp->argv[argvp->argc] = 0;
}
void zargv_truncate(zargv_t * argvp, int len)
{
zargv_mpool_t *ama = (zargv_mpool_t *)argvp;
char **cpp;
if (len < argvp->argc) {
for (cpp = argvp->argv + len; cpp < argvp->argv + argvp->argc; cpp++) {
if (argvp->mpool_used) {
zmpool_free(ama->mpool, *cpp);
} else {
zfree(*cpp);
}
}
argvp->argc = len;
argvp->argv[argvp->argc] = 0;
}
}
zargv_t *zargv_split_append(zargv_t * argvp, const char *string, const char *delim)
{
zstrtok_t stok;
if (argvp == 0) {
argvp = zargv_create(-1);
}
zstrtok_init(&stok, (char *)string);
while (zstrtok(&stok, delim)) {
zargv_addn(argvp, stok.str, stok.len);
}
return (argvp);
}
void zargv_debug_show(zargv_t * argvp)
{
ZARGV_WALK_BEGIN(argvp, p) {
printf("%s\n", p);
}
ZARGV_WALK_END;
}
| mailhonor/libzc | src/stdlib/argv.c | C | gpl-3.0 | 3,973 | [
30522,
1013,
1008,
1008,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1008,
12005,
2683,
16... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
module.exports = function(grunt) {
// Add our custom tasks.
grunt.loadTasks('../../../tasks');
// Project configuration.
grunt.initConfig({
mochaTest: {
options: {
reporter: 'spec',
grep: 'tests that match grep',
invert: true
},
all: {
src: ['*.js']
}
}
});
// Default task.
grunt.registerTask('default', ['mochaTest']);
};
| quantumlicht/collarbone | node_modules/grunt-mocha-test/test/scenarios/invertOption/Gruntfile.js | JavaScript | mit | 425 | [
30522,
11336,
1012,
14338,
1027,
3853,
1006,
20696,
1007,
1063,
1013,
1013,
5587,
2256,
7661,
8518,
1012,
20696,
1012,
7170,
10230,
5705,
1006,
1005,
1012,
1012,
1013,
1012,
1012,
1013,
1012,
1012,
1013,
8518,
1005,
1007,
1025,
1013,
1013,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
jsonp({"cep":"09341146","logradouro":"Rua Beatriz Helena Costa","bairro":"Jardim Quarto Centen\u00e1rio","cidade":"Mau\u00e1","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/09341146.jsonp.js | JavaScript | cc0-1.0 | 165 | [
30522,
1046,
3385,
2361,
1006,
1063,
1000,
8292,
2361,
1000,
1024,
1000,
5641,
22022,
14526,
21472,
1000,
1010,
1000,
8833,
12173,
8162,
2080,
1000,
1024,
1000,
21766,
2050,
3786,
21885,
10269,
6849,
1000,
1010,
1000,
21790,
18933,
1000,
10... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* 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.
*/
using System;
namespace Lucene.Net.Search
{
/// <summary> A <see cref="Scorer" /> which wraps another scorer and caches the score of the
/// current document. Successive calls to <see cref="Score()" /> will return the same
/// result and will not invoke the wrapped Scorer's score() method, unless the
/// current document has changed.<br/>
/// This class might be useful due to the changes done to the <see cref="Collector" />
/// interface, in which the score is not computed for a document by default, only
/// if the collector requests it. Some collectors may need to use the score in
/// several places, however all they have in hand is a <see cref="Scorer" /> object, and
/// might end up computing the score of a document more than once.
/// </summary>
public class ScoreCachingWrappingScorer:Scorer
{
private Scorer scorer;
private int curDoc = - 1;
private float curScore;
/// <summary>Creates a new instance by wrapping the given scorer. </summary>
public ScoreCachingWrappingScorer(Scorer scorer):base(scorer.Similarity)
{
this.scorer = scorer;
}
public /*protected internal*/ override bool Score(Collector collector, int max, int firstDocID)
{
return scorer.Score(collector, max, firstDocID);
}
public override Similarity Similarity
{
get { return scorer.Similarity; }
}
public override float Score()
{
int doc = scorer.DocID();
if (doc != curDoc)
{
curScore = scorer.Score();
curDoc = doc;
}
return curScore;
}
public override int DocID()
{
return scorer.DocID();
}
public override int NextDoc()
{
return scorer.NextDoc();
}
public override void Score(Collector collector)
{
scorer.Score(collector);
}
public override int Advance(int target)
{
return scorer.Advance(target);
}
}
} | Anomalous-Software/Lucene.NET | src/core/Search/ScoreCachingWrappingScorer.cs | C# | apache-2.0 | 2,744 | [
30522,
1013,
1008,
1008,
7000,
2000,
1996,
15895,
4007,
3192,
1006,
2004,
2546,
1007,
2104,
2028,
2030,
2062,
1008,
12130,
6105,
10540,
1012,
2156,
1996,
5060,
5371,
5500,
2007,
30524,
1008,
1006,
1996,
1000,
6105,
1000,
1007,
1025,
2017,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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.jetbrains.plugins.groovy.intentions.conversions;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.plugins.groovy.intentions.base.ErrorUtil;
import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate;
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty;
class IndexedExpressionConversionPredicate implements PsiElementPredicate {
public boolean satisfiedBy(PsiElement element) {
if (!(element instanceof GrIndexProperty)) return false;
if (ErrorUtil.containsError(element)) return false;
final GrIndexProperty arrayIndexExpression = (GrIndexProperty) element;
final PsiElement lastChild = arrayIndexExpression.getLastChild();
if (!(lastChild instanceof GrArgumentList)) return false;
final GrArgumentList argList = (GrArgumentList) lastChild;
final GrExpression[] arguments = argList.getExpressionArguments();
if (arguments.length != 1) return false;
final PsiElement parent = element.getParent();
if (!(parent instanceof GrAssignmentExpression)) {
return true;
}
final GrAssignmentExpression assignmentExpression = (GrAssignmentExpression) parent;
final GrExpression rvalue = assignmentExpression.getRValue();
if (rvalue == null) return false;
if (rvalue.equals(element)) return true;
final IElementType operator = assignmentExpression.getOperationTokenType();
return GroovyTokenTypes.mASSIGN.equals(operator);
}
}
| liveqmock/platform-tools-idea | plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/IndexedExpressionConversionPredicate.java | Java | apache-2.0 | 2,533 | [
30522,
1013,
1008,
1008,
9385,
2456,
1011,
2286,
6892,
10024,
7076,
1055,
1012,
1054,
1012,
1051,
1012,
1008,
1008,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
1012,
1014,
1006,
1996,
1000,
6105,
1000,
1007,
1025,
1008,
2017,
2089,
2... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Bundle\Test\Unit\Block\Adminhtml\Sales\Order\View\Items;
class RendererTest extends \PHPUnit_Framework_TestCase
{
/** @var \Magento\Sales\Model\Order\Item|\PHPUnit_Framework_MockObject_MockObject */
protected $orderItem;
/** @var \Magento\Bundle\Block\Adminhtml\Sales\Order\View\Items\Renderer $model */
protected $model;
protected function setUp()
{
$this->orderItem = $this->getMock(
'Magento\Sales\Model\Order\Item',
['getProductOptions', '__wakeup', 'getParentItem', 'getOrderItem'],
[],
'',
false
);
$objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
$this->model = $objectManager->getObject('Magento\Bundle\Block\Adminhtml\Sales\Order\View\Items\Renderer');
}
/**
* @dataProvider isShipmentSeparatelyWithoutItemDataProvider
*/
public function testIsShipmentSeparatelyWithoutItem($productOptions, $result)
{
$this->model->setItem($this->orderItem);
$this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions));
$this->assertSame($result, $this->model->isShipmentSeparately());
}
public function isShipmentSeparatelyWithoutItemDataProvider()
{
return [
[['shipment_type' => 1], true],
[['shipment_type' => 0], false],
[[], false]
];
}
/**
* @dataProvider isShipmentSeparatelyWithItemDataProvider
*/
public function testIsShipmentSeparatelyWithItem($productOptions, $result, $parentItem)
{
if ($parentItem) {
$parentItem =
$this->getMock('Magento\Sales\Model\Order\Item', ['getProductOptions', '__wakeup'], [], '', false);
$parentItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions));
} else {
$this->orderItem->expects($this->any())->method('getProductOptions')
->will($this->returnValue($productOptions));
}
$this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem));
$this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf());
$this->assertSame($result, $this->model->isShipmentSeparately($this->orderItem));
}
public function isShipmentSeparatelyWithItemDataProvider()
{
return [
[['shipment_type' => 1], false, false],
[['shipment_type' => 0], true, false],
[['shipment_type' => 1], true, true],
[['shipment_type' => 0], false, true],
];
}
/**
* @dataProvider isChildCalculatedWithoutItemDataProvider
*/
public function testIsChildCalculatedWithoutItem($productOptions, $result)
{
$this->model->setItem($this->orderItem);
$this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions));
$this->assertSame($result, $this->model->isChildCalculated());
}
public function isChildCalculatedWithoutItemDataProvider()
{
return [
[['product_calculations' => 0], true],
[['product_calculations' => 1], false],
[[], false],
];
}
/**
* @dataProvider isChildCalculatedWithItemDataProvider
*/
public function testIsChildCalculatedWithItem($productOptions, $result, $parentItem)
{
if ($parentItem) {
$parentItem =
$this->getMock('Magento\Sales\Model\Order\Item', ['getProductOptions', '__wakeup'], [], '', false);
$parentItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions));
} else {
$this->orderItem->expects($this->any())->method('getProductOptions')
->will($this->returnValue($productOptions));
}
$this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem));
$this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf());
$this->assertSame($result, $this->model->isChildCalculated($this->orderItem));
}
public function isChildCalculatedWithItemDataProvider()
{
return [
[['product_calculations' => 0], false, false],
[['product_calculations' => 1], true, false],
[['product_calculations' => 0], true, true],
[['product_calculations' => 1], false, true],
];
}
/**
* @dataProvider getSelectionAttributesDataProvider
*/
public function testGetSelectionAttributes($productOptions, $result)
{
$this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions));
$this->assertSame($result, $this->model->getSelectionAttributes($this->orderItem));
}
public function getSelectionAttributesDataProvider()
{
return [
[[], null],
[['bundle_selection_attributes' => 'a:1:{i:0;i:1;}'], [0 => 1]],
];
}
public function testGetOrderOptions()
{
$productOptions = [
'options' => ['options'],
'additional_options' => ['additional_options'],
'attributes_info' => ['attributes_info'],
];
$this->model->setItem($this->orderItem);
$this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions));
$this->assertEquals(['attributes_info', 'options', 'additional_options'], $this->model->getOrderOptions());
}
/**
* @dataProvider canShowPriceInfoDataProvider
*/
public function testCanShowPriceInfo($parentItem, $productOptions, $result)
{
$this->model->setItem($this->orderItem);
$this->orderItem->expects($this->any())->method('getOrderItem')->will($this->returnSelf());
$this->orderItem->expects($this->any())->method('getParentItem')->will($this->returnValue($parentItem));
$this->orderItem->expects($this->any())->method('getProductOptions')->will($this->returnValue($productOptions));
$this->assertSame($result, $this->model->canShowPriceInfo($this->orderItem));
}
public function canShowPriceInfoDataProvider()
{
return [
[true, ['product_calculations' => 0], true],
[false, [], true],
[false, ['product_calculations' => 0], false],
];
}
}
| FPLD/project0 | vendor/magento/module-bundle/Test/Unit/Block/Adminhtml/Sales/Order/View/Items/RendererTest.php | PHP | gpl-2.0 | 6,729 | [
30522,
1026,
1029,
25718,
1013,
1008,
1008,
1008,
9385,
1075,
2325,
17454,
13663,
1012,
2035,
2916,
9235,
1012,
1008,
2156,
24731,
1012,
19067,
2102,
2005,
6105,
4751,
1012,
1008,
1013,
3415,
15327,
17454,
13663,
1032,
14012,
1032,
3231,
10... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
using System;
using strange.extensions.mediation.api;
namespace strange.examples.strangerobots.game
{
public class ObjectStatus {
public int x;
public int y;
public ObjectStatus(int xx, int yy) {
x = xx;
y = yy;
destroyed = false;
}
public IView view{ get; set; }
public bool destroyed { get; set; }
}
}
| strangeioc/strangerobots | StrangeRobots/Assets/scripts/strangerobots/game/model/ObjectStatus.cs | C# | apache-2.0 | 335 | [
30522,
2478,
2291,
1025,
2478,
4326,
1012,
14305,
1012,
26435,
1012,
17928,
1025,
3415,
15327,
4326,
1012,
4973,
1012,
7985,
16429,
12868,
1012,
2208,
1063,
2270,
2465,
5200,
29336,
2271,
1063,
2270,
20014,
1060,
1025,
2270,
20014,
1061,
10... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* This file is part of the libsigrok project.
*
* Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
* Copyright (C) 2011 Olivier Fauchon <olivier@aixmarseille.com>
* Copyright (C) 2012 Alexandru Gagniuc <mr.nuke.me@gmail.com>
* Copyright (C) 2015 Bartosz Golaszewski <bgolaszewski@baylibre.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#define pipe(fds) _pipe(fds, 4096, _O_BINARY)
#endif
#include "libsigrok.h"
#include "libsigrok-internal.h"
#define LOG_PREFIX "demo"
#define DEFAULT_NUM_LOGIC_CHANNELS 8
#define DEFAULT_NUM_ANALOG_CHANNELS 4
/* The size in bytes of chunks to send through the session bus. */
#define LOGIC_BUFSIZE 4096
/* Size of the analog pattern space per channel. */
#define ANALOG_BUFSIZE 4096
#define DEFAULT_ANALOG_AMPLITUDE 25
#define ANALOG_SAMPLES_PER_PERIOD 20
/* Logic patterns we can generate. */
enum {
/**
* Spells "sigrok" across 8 channels using '0's (with '1's as
* "background") when displayed using the 'bits' output format.
* The pattern is repeated every 8 channels, shifted to the right
* in time by one bit.
*/
PATTERN_SIGROK,
/** Pseudo-random values on all channels. */
PATTERN_RANDOM,
/**
* Incrementing number across 8 channels. The pattern is repeated
* every 8 channels, shifted to the right in time by one bit.
*/
PATTERN_INC,
/** All channels have a low logic state. */
PATTERN_ALL_LOW,
/** All channels have a high logic state. */
PATTERN_ALL_HIGH,
};
/* Analog patterns we can generate. */
enum {
/**
* Square wave.
*/
PATTERN_SQUARE,
PATTERN_SINE,
PATTERN_TRIANGLE,
PATTERN_SAWTOOTH,
};
static const char *logic_pattern_str[] = {
"sigrok",
"random",
"incremental",
"all-low",
"all-high",
};
static const char *analog_pattern_str[] = {
"square",
"sine",
"triangle",
"sawtooth",
};
struct analog_gen {
int pattern;
float amplitude;
float pattern_data[ANALOG_BUFSIZE];
unsigned int num_samples;
struct sr_datafeed_analog packet;
float avg_val; /* Average value */
unsigned num_avgs; /* Number of samples averaged */
};
/* Private, per-device-instance driver context. */
struct dev_context {
int pipe_fds[2];
GIOChannel *channel;
uint64_t cur_samplerate;
gboolean continuous;
uint64_t limit_samples;
uint64_t limit_msec;
uint64_t logic_counter;
uint64_t analog_counter;
int64_t starttime;
uint64_t step;
/* Logic */
int32_t num_logic_channels;
unsigned int logic_unitsize;
/* There is only ever one logic channel group, so its pattern goes here. */
uint8_t logic_pattern;
unsigned char logic_data[LOGIC_BUFSIZE];
/* Analog */
int32_t num_analog_channels;
GHashTable *ch_ag;
gboolean avg; /* True if averaging is enabled */
uint64_t avg_samples;
};
static const uint32_t drvopts[] = {
SR_CONF_DEMO_DEV,
SR_CONF_LOGIC_ANALYZER,
SR_CONF_OSCILLOSCOPE,
};
static const uint32_t scanopts[] = {
SR_CONF_NUM_LOGIC_CHANNELS,
SR_CONF_NUM_ANALOG_CHANNELS,
};
static const uint32_t devopts[] = {
SR_CONF_CONTINUOUS | SR_CONF_SET,
SR_CONF_LIMIT_SAMPLES | SR_CONF_GET | SR_CONF_SET,
SR_CONF_LIMIT_MSEC | SR_CONF_GET | SR_CONF_SET,
SR_CONF_SAMPLERATE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
SR_CONF_AVERAGING | SR_CONF_GET | SR_CONF_SET,
SR_CONF_AVG_SAMPLES | SR_CONF_GET | SR_CONF_SET,
};
static const uint32_t devopts_cg_logic[] = {
SR_CONF_PATTERN_MODE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
};
static const uint32_t devopts_cg_analog[] = {
SR_CONF_PATTERN_MODE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
SR_CONF_AMPLITUDE | SR_CONF_GET | SR_CONF_SET,
};
static const uint64_t samplerates[] = {
SR_HZ(1),
SR_GHZ(1),
SR_HZ(1),
};
static const uint8_t pattern_sigrok[] = {
0x4c, 0x92, 0x92, 0x92, 0x64, 0x00, 0x00, 0x00,
0x82, 0xfe, 0xfe, 0x82, 0x00, 0x00, 0x00, 0x00,
0x7c, 0x82, 0x82, 0x92, 0x74, 0x00, 0x00, 0x00,
0xfe, 0x12, 0x12, 0x32, 0xcc, 0x00, 0x00, 0x00,
0x7c, 0x82, 0x82, 0x82, 0x7c, 0x00, 0x00, 0x00,
0xfe, 0x10, 0x28, 0x44, 0x82, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xbe, 0xbe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
SR_PRIV struct sr_dev_driver demo_driver_info;
static int dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data);
static int init(struct sr_dev_driver *di, struct sr_context *sr_ctx)
{
return std_init(sr_ctx, di, LOG_PREFIX);
}
static void generate_analog_pattern(struct analog_gen *ag, uint64_t sample_rate)
{
double t, frequency;
float value;
unsigned int num_samples, i;
int last_end;
sr_dbg("Generating %s pattern.", analog_pattern_str[ag->pattern]);
num_samples = ANALOG_BUFSIZE / sizeof(float);
switch (ag->pattern) {
case PATTERN_SQUARE:
value = ag->amplitude;
last_end = 0;
for (i = 0; i < num_samples; i++) {
if (i % 5 == 0)
value = -value;
if (i % 10 == 0)
last_end = i;
ag->pattern_data[i] = value;
}
ag->num_samples = last_end;
break;
case PATTERN_SINE:
frequency = (double) sample_rate / ANALOG_SAMPLES_PER_PERIOD;
/* Make sure the number of samples we put out is an integer
* multiple of our period size */
/* FIXME we actually need only one period. A ringbuffer would be
* useful here. */
while (num_samples % ANALOG_SAMPLES_PER_PERIOD != 0)
num_samples--;
for (i = 0; i < num_samples; i++) {
t = (double) i / (double) sample_rate;
ag->pattern_data[i] = ag->amplitude *
sin(2 * PI * frequency * t);
}
ag->num_samples = num_samples;
break;
case PATTERN_TRIANGLE:
frequency = (double) sample_rate / ANALOG_SAMPLES_PER_PERIOD;
while (num_samples % ANALOG_SAMPLES_PER_PERIOD != 0)
num_samples--;
for (i = 0; i < num_samples; i++) {
t = (double) i / (double) sample_rate;
ag->pattern_data[i] = (2 * ag->amplitude / PI) *
asin(sin(2 * PI * frequency * t));
}
ag->num_samples = num_samples;
break;
case PATTERN_SAWTOOTH:
frequency = (double) sample_rate / ANALOG_SAMPLES_PER_PERIOD;
while (num_samples % ANALOG_SAMPLES_PER_PERIOD != 0)
num_samples--;
for (i = 0; i < num_samples; i++) {
t = (double) i / (double) sample_rate;
ag->pattern_data[i] = 2 * ag->amplitude *
((t * frequency) - floor(0.5f + t * frequency));
}
ag->num_samples = num_samples;
break;
}
}
static GSList *scan(struct sr_dev_driver *di, GSList *options)
{
struct drv_context *drvc;
struct dev_context *devc;
struct sr_dev_inst *sdi;
struct sr_channel *ch;
struct sr_channel_group *cg, *acg;
struct sr_config *src;
struct analog_gen *ag;
GSList *devices, *l;
int num_logic_channels, num_analog_channels, pattern, i;
char channel_name[16];
drvc = di->priv;
num_logic_channels = DEFAULT_NUM_LOGIC_CHANNELS;
num_analog_channels = DEFAULT_NUM_ANALOG_CHANNELS;
for (l = options; l; l = l->next) {
src = l->data;
switch (src->key) {
case SR_CONF_NUM_LOGIC_CHANNELS:
num_logic_channels = g_variant_get_int32(src->data);
break;
case SR_CONF_NUM_ANALOG_CHANNELS:
num_analog_channels = g_variant_get_int32(src->data);
break;
}
}
devices = NULL;
sdi = g_malloc0(sizeof(struct sr_dev_inst));
sdi->status = SR_ST_ACTIVE;
sdi->model = g_strdup("Demo device");
sdi->driver = di;
devc = g_malloc(sizeof(struct dev_context));
devc->cur_samplerate = SR_KHZ(200);
devc->limit_samples = 0;
devc->limit_msec = 0;
devc->step = 0;
devc->continuous = FALSE;
devc->num_logic_channels = num_logic_channels;
devc->logic_unitsize = (devc->num_logic_channels + 7) / 8;
devc->logic_pattern = PATTERN_SIGROK;
devc->num_analog_channels = num_analog_channels;
devc->avg = FALSE;
devc->avg_samples = 0;
/* Logic channels, all in one channel group. */
cg = g_malloc0(sizeof(struct sr_channel_group));
cg->name = g_strdup("Logic");
for (i = 0; i < num_logic_channels; i++) {
sprintf(channel_name, "D%d", i);
ch = sr_channel_new(sdi, i, SR_CHANNEL_LOGIC, TRUE, channel_name);
cg->channels = g_slist_append(cg->channels, ch);
}
sdi->channel_groups = g_slist_append(NULL, cg);
/* Analog channels, channel groups and pattern generators. */
pattern = 0;
/* An "Analog" channel group with all analog channels in it. */
acg = g_malloc0(sizeof(struct sr_channel_group));
acg->name = g_strdup("Analog");
sdi->channel_groups = g_slist_append(sdi->channel_groups, acg);
devc->ch_ag = g_hash_table_new(g_direct_hash, g_direct_equal);
for (i = 0; i < num_analog_channels; i++) {
snprintf(channel_name, 16, "A%d", i);
ch = sr_channel_new(sdi, i + num_logic_channels, SR_CHANNEL_ANALOG,
TRUE, channel_name);
acg->channels = g_slist_append(acg->channels, ch);
/* Every analog channel gets its own channel group as well. */
cg = g_malloc0(sizeof(struct sr_channel_group));
cg->name = g_strdup(channel_name);
cg->channels = g_slist_append(NULL, ch);
sdi->channel_groups = g_slist_append(sdi->channel_groups, cg);
/* Every channel gets a generator struct. */
ag = g_malloc(sizeof(struct analog_gen));
ag->amplitude = DEFAULT_ANALOG_AMPLITUDE;
ag->packet.channels = cg->channels;
ag->packet.mq = 0;
ag->packet.mqflags = 0;
ag->packet.unit = SR_UNIT_VOLT;
ag->packet.data = ag->pattern_data;
ag->pattern = pattern;
ag->avg_val = 0.0f;
ag->num_avgs = 0;
g_hash_table_insert(devc->ch_ag, ch, ag);
if (++pattern == ARRAY_SIZE(analog_pattern_str))
pattern = 0;
}
sdi->priv = devc;
devices = g_slist_append(devices, sdi);
drvc->instances = g_slist_append(drvc->instances, sdi);
return devices;
}
static GSList *dev_list(const struct sr_dev_driver *di)
{
return ((struct drv_context *)(di->priv))->instances;
}
static int dev_open(struct sr_dev_inst *sdi)
{
sdi->status = SR_ST_ACTIVE;
return SR_OK;
}
static int dev_close(struct sr_dev_inst *sdi)
{
sdi->status = SR_ST_INACTIVE;
return SR_OK;
}
static void clear_helper(void *priv)
{
struct dev_context *devc;
GHashTableIter iter;
void *value;
devc = priv;
/* Analog generators. */
g_hash_table_iter_init(&iter, devc->ch_ag);
while (g_hash_table_iter_next(&iter, NULL, &value))
g_free(value);
g_hash_table_unref(devc->ch_ag);
g_free(devc);
}
static int cleanup(const struct sr_dev_driver *di)
{
return std_dev_clear(di, clear_helper);
}
static int config_get(uint32_t key, GVariant **data, const struct sr_dev_inst *sdi,
const struct sr_channel_group *cg)
{
struct dev_context *devc;
struct sr_channel *ch;
struct analog_gen *ag;
int pattern;
if (!sdi)
return SR_ERR_ARG;
devc = sdi->priv;
switch (key) {
case SR_CONF_SAMPLERATE:
*data = g_variant_new_uint64(devc->cur_samplerate);
break;
case SR_CONF_LIMIT_SAMPLES:
*data = g_variant_new_uint64(devc->limit_samples);
break;
case SR_CONF_LIMIT_MSEC:
*data = g_variant_new_uint64(devc->limit_msec);
break;
case SR_CONF_AVERAGING:
*data = g_variant_new_boolean(devc->avg);
break;
case SR_CONF_AVG_SAMPLES:
*data = g_variant_new_uint64(devc->avg_samples);
break;
case SR_CONF_PATTERN_MODE:
if (!cg)
return SR_ERR_CHANNEL_GROUP;
/* Any channel in the group will do. */
ch = cg->channels->data;
if (ch->type == SR_CHANNEL_LOGIC) {
pattern = devc->logic_pattern;
*data = g_variant_new_string(logic_pattern_str[pattern]);
} else if (ch->type == SR_CHANNEL_ANALOG) {
ag = g_hash_table_lookup(devc->ch_ag, ch);
pattern = ag->pattern;
*data = g_variant_new_string(analog_pattern_str[pattern]);
} else
return SR_ERR_BUG;
break;
case SR_CONF_AMPLITUDE:
if (!cg)
return SR_ERR_CHANNEL_GROUP;
/* Any channel in the group will do. */
ch = cg->channels->data;
if (ch->type != SR_CHANNEL_ANALOG)
return SR_ERR_ARG;
ag = g_hash_table_lookup(devc->ch_ag, ch);
*data = g_variant_new_double(ag->amplitude);
break;
default:
return SR_ERR_NA;
}
return SR_OK;
}
static int config_set(uint32_t key, GVariant *data, const struct sr_dev_inst *sdi,
const struct sr_channel_group *cg)
{
struct dev_context *devc;
struct analog_gen *ag;
struct sr_channel *ch;
GSList *l;
int logic_pattern, analog_pattern, ret;
unsigned int i;
const char *stropt;
devc = sdi->priv;
if (sdi->status != SR_ST_ACTIVE)
return SR_ERR_DEV_CLOSED;
ret = SR_OK;
switch (key) {
case SR_CONF_SAMPLERATE:
devc->cur_samplerate = g_variant_get_uint64(data);
break;
case SR_CONF_LIMIT_SAMPLES:
devc->limit_msec = 0;
devc->limit_samples = g_variant_get_uint64(data);
break;
case SR_CONF_LIMIT_MSEC:
devc->limit_msec = g_variant_get_uint64(data);
devc->limit_samples = 0;
break;
case SR_CONF_AVERAGING:
devc->avg = g_variant_get_boolean(data);
sr_dbg("%s averaging", devc->avg ? "Enabling" : "Disabling");
break;
case SR_CONF_AVG_SAMPLES:
devc->avg_samples = g_variant_get_uint64(data);
sr_dbg("Setting averaging rate to %" PRIu64, devc->avg_samples);
break;
case SR_CONF_PATTERN_MODE:
if (!cg)
return SR_ERR_CHANNEL_GROUP;
stropt = g_variant_get_string(data, NULL);
logic_pattern = analog_pattern = -1;
for (i = 0; i < ARRAY_SIZE(logic_pattern_str); i++) {
if (!strcmp(stropt, logic_pattern_str[i])) {
logic_pattern = i;
break;
}
}
for (i = 0; i < ARRAY_SIZE(analog_pattern_str); i++) {
if (!strcmp(stropt, analog_pattern_str[i])) {
analog_pattern = i;
break;
}
}
if (logic_pattern == -1 && analog_pattern == -1)
return SR_ERR_ARG;
for (l = cg->channels; l; l = l->next) {
ch = l->data;
if (ch->type == SR_CHANNEL_LOGIC) {
if (logic_pattern == -1)
return SR_ERR_ARG;
sr_dbg("Setting logic pattern to %s",
logic_pattern_str[logic_pattern]);
devc->logic_pattern = logic_pattern;
/* Might as well do this now, these are static. */
if (logic_pattern == PATTERN_ALL_LOW)
memset(devc->logic_data, 0x00, LOGIC_BUFSIZE);
else if (logic_pattern == PATTERN_ALL_HIGH)
memset(devc->logic_data, 0xff, LOGIC_BUFSIZE);
} else if (ch->type == SR_CHANNEL_ANALOG) {
if (analog_pattern == -1)
return SR_ERR_ARG;
sr_dbg("Setting analog pattern for channel %s to %s",
ch->name, analog_pattern_str[analog_pattern]);
ag = g_hash_table_lookup(devc->ch_ag, ch);
ag->pattern = analog_pattern;
} else
return SR_ERR_BUG;
}
break;
case SR_CONF_AMPLITUDE:
if (!cg)
return SR_ERR_CHANNEL_GROUP;
for (l = cg->channels; l; l = l->next) {
ch = l->data;
if (ch->type != SR_CHANNEL_ANALOG)
return SR_ERR_ARG;
ag = g_hash_table_lookup(devc->ch_ag, ch);
ag->amplitude = g_variant_get_double(data);
}
break;
default:
ret = SR_ERR_NA;
}
return ret;
}
static int config_list(uint32_t key, GVariant **data, const struct sr_dev_inst *sdi,
const struct sr_channel_group *cg)
{
struct sr_channel *ch;
GVariant *gvar;
GVariantBuilder gvb;
if (key == SR_CONF_SCAN_OPTIONS) {
*data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
scanopts, ARRAY_SIZE(scanopts), sizeof(uint32_t));
return SR_OK;
}
if (key == SR_CONF_DEVICE_OPTIONS && !sdi) {
*data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
drvopts, ARRAY_SIZE(drvopts), sizeof(uint32_t));
return SR_OK;
}
if (!sdi)
return SR_ERR_ARG;
if (!cg) {
switch (key) {
case SR_CONF_DEVICE_OPTIONS:
*data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
devopts, ARRAY_SIZE(devopts), sizeof(uint32_t));
break;
case SR_CONF_SAMPLERATE:
g_variant_builder_init(&gvb, G_VARIANT_TYPE("a{sv}"));
gvar = g_variant_new_fixed_array(G_VARIANT_TYPE("t"), samplerates,
ARRAY_SIZE(samplerates), sizeof(uint64_t));
g_variant_builder_add(&gvb, "{sv}", "samplerate-steps", gvar);
*data = g_variant_builder_end(&gvb);
break;
default:
return SR_ERR_NA;
}
} else {
/* Any channel in the group will do. */
ch = cg->channels->data;
switch (key) {
case SR_CONF_DEVICE_OPTIONS:
if (ch->type == SR_CHANNEL_LOGIC)
*data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
devopts_cg_logic, ARRAY_SIZE(devopts_cg_logic),
sizeof(uint32_t));
else if (ch->type == SR_CHANNEL_ANALOG)
*data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
devopts_cg_analog, ARRAY_SIZE(devopts_cg_analog),
sizeof(uint32_t));
else
return SR_ERR_BUG;
break;
case SR_CONF_PATTERN_MODE:
if (ch->type == SR_CHANNEL_LOGIC)
*data = g_variant_new_strv(logic_pattern_str,
ARRAY_SIZE(logic_pattern_str));
else if (ch->type == SR_CHANNEL_ANALOG)
*data = g_variant_new_strv(analog_pattern_str,
ARRAY_SIZE(analog_pattern_str));
else
return SR_ERR_BUG;
break;
default:
return SR_ERR_NA;
}
}
return SR_OK;
}
static void logic_generator(struct sr_dev_inst *sdi, uint64_t size)
{
struct dev_context *devc;
uint64_t i, j;
uint8_t pat;
devc = sdi->priv;
switch (devc->logic_pattern) {
case PATTERN_SIGROK:
memset(devc->logic_data, 0x00, size);
for (i = 0; i < size; i += devc->logic_unitsize) {
for (j = 0; j < devc->logic_unitsize; j++) {
pat = pattern_sigrok[(devc->step + j) % sizeof(pattern_sigrok)] >> 1;
devc->logic_data[i + j] = ~pat;
}
devc->step++;
}
break;
case PATTERN_RANDOM:
for (i = 0; i < size; i++)
devc->logic_data[i] = (uint8_t)(rand() & 0xff);
break;
case PATTERN_INC:
for (i = 0; i < size; i++) {
for (j = 0; j < devc->logic_unitsize; j++) {
devc->logic_data[i + j] = devc->step;
}
devc->step++;
}
break;
case PATTERN_ALL_LOW:
case PATTERN_ALL_HIGH:
/* These were set when the pattern mode was selected. */
break;
default:
sr_err("Unknown pattern: %d.", devc->logic_pattern);
break;
}
}
static void send_analog_packet(struct analog_gen *ag,
struct sr_dev_inst *sdi,
uint64_t *analog_sent,
uint64_t analog_todo)
{
struct sr_datafeed_packet packet;
struct dev_context *devc;
uint64_t sending_now, to_avg;
int ag_pattern_pos;
unsigned int i;
devc = sdi->priv;
packet.type = SR_DF_ANALOG;
packet.payload = &ag->packet;
if (!devc->avg) {
ag_pattern_pos = devc->analog_counter % ag->num_samples;
sending_now = MIN(analog_todo, ag->num_samples-ag_pattern_pos);
ag->packet.data = ag->pattern_data + ag_pattern_pos;
ag->packet.num_samples = sending_now;
sr_session_send(sdi, &packet);
/* Whichever channel group gets there first. */
*analog_sent = MAX(*analog_sent, sending_now);
} else {
ag_pattern_pos = devc->analog_counter % ag->num_samples;
to_avg = MIN(analog_todo, ag->num_samples-ag_pattern_pos);
for (i = 0; i < to_avg; i++) {
ag->avg_val = (ag->avg_val +
*(ag->pattern_data +
ag_pattern_pos + i)) / 2;
ag->num_avgs++;
/* Time to send averaged data? */
if (devc->avg_samples > 0 &&
ag->num_avgs >= devc->avg_samples)
goto do_send;
}
if (devc->avg_samples == 0) {
/* We're averaging all the samples, so wait with
* sending until the very end.
*/
*analog_sent = ag->num_avgs;
return;
}
do_send:
ag->packet.data = &ag->avg_val;
ag->packet.num_samples = 1;
sr_session_send(sdi, &packet);
*analog_sent = ag->num_avgs;
ag->num_avgs = 0;
ag->avg_val = 0.0f;
}
}
/* Callback handling data */
static int prepare_data(int fd, int revents, void *cb_data)
{
struct sr_dev_inst *sdi;
struct dev_context *devc;
struct sr_datafeed_packet packet;
struct sr_datafeed_logic logic;
struct analog_gen *ag;
GHashTableIter iter;
void *value;
uint64_t logic_todo, analog_todo, expected_samplenum, analog_sent, sending_now;
int64_t time, elapsed;
(void)fd;
(void)revents;
sdi = cb_data;
devc = sdi->priv;
logic_todo = analog_todo = 0;
/* How many samples should we have sent by now? */
time = g_get_monotonic_time();
elapsed = time - devc->starttime;
expected_samplenum = elapsed * devc->cur_samplerate / (1000 * 1000);
/* But never more than the limit, if there is one. */
if (!devc->continuous)
expected_samplenum = MIN(expected_samplenum, devc->limit_samples);
/* Of those, how many do we still have to send? */
if (devc->num_logic_channels)
logic_todo = expected_samplenum - devc->logic_counter;
if (devc->num_analog_channels)
analog_todo = expected_samplenum - devc->analog_counter;
while (logic_todo || analog_todo) {
/* Logic */
if (logic_todo > 0) {
sending_now = MIN(logic_todo, LOGIC_BUFSIZE / devc->logic_unitsize);
logic_generator(sdi, sending_now * devc->logic_unitsize);
packet.type = SR_DF_LOGIC;
packet.payload = &logic;
logic.length = sending_now * devc->logic_unitsize;
logic.unitsize = devc->logic_unitsize;
logic.data = devc->logic_data;
sr_session_send(sdi, &packet);
logic_todo -= sending_now;
devc->logic_counter += sending_now;
}
/* Analog, one channel at a time */
if (analog_todo > 0) {
analog_sent = 0;
g_hash_table_iter_init(&iter, devc->ch_ag);
while (g_hash_table_iter_next(&iter, NULL, &value)) {
send_analog_packet(value, sdi,
&analog_sent, analog_todo);
}
analog_todo -= analog_sent;
devc->analog_counter += analog_sent;
}
}
if (!devc->continuous
&& (!devc->num_logic_channels || devc->logic_counter >= devc->limit_samples)
&& (!devc->num_analog_channels || devc->analog_counter >= devc->limit_samples)) {
/* If we're averaging everything - now is the time to send data */
if (devc->avg_samples == 0) {
g_hash_table_iter_init(&iter, devc->ch_ag);
while (g_hash_table_iter_next(&iter, NULL, &value)) {
ag = value;
packet.type = SR_DF_ANALOG;
packet.payload = &ag->packet;
ag->packet.data = &ag->avg_val;
ag->packet.num_samples = 1;
sr_session_send(sdi, &packet);
}
}
sr_dbg("Requested number of samples reached.");
dev_acquisition_stop(sdi, cb_data);
return TRUE;
}
return TRUE;
}
static int dev_acquisition_start(const struct sr_dev_inst *sdi, void *cb_data)
{
struct dev_context *devc;
GHashTableIter iter;
void *value;
(void)cb_data;
if (sdi->status != SR_ST_ACTIVE)
return SR_ERR_DEV_CLOSED;
devc = sdi->priv;
devc->continuous = !devc->limit_samples;
devc->logic_counter = devc->analog_counter = 0;
/*
* Setting two channels connected by a pipe is a remnant from when the
* demo driver generated data in a thread, and collected and sent the
* data in the main program loop.
* They are kept here because it provides a convenient way of setting
* up a timeout-based polling mechanism.
*/
if (pipe(devc->pipe_fds)) {
sr_err("%s: pipe() failed", __func__);
return SR_ERR;
}
g_hash_table_iter_init(&iter, devc->ch_ag);
while (g_hash_table_iter_next(&iter, NULL, &value))
generate_analog_pattern(value, devc->cur_samplerate);
devc->channel = g_io_channel_unix_new(devc->pipe_fds[0]);
g_io_channel_set_flags(devc->channel, G_IO_FLAG_NONBLOCK, NULL);
/* Set channel encoding to binary (default is UTF-8). */
g_io_channel_set_encoding(devc->channel, NULL, NULL);
/* Make channels unbuffered. */
g_io_channel_set_buffered(devc->channel, FALSE);
sr_session_source_add_channel(sdi->session, devc->channel,
G_IO_IN | G_IO_ERR, 40, prepare_data, (void *)sdi);
/* Send header packet to the session bus. */
std_session_send_df_header(sdi, LOG_PREFIX);
/* We use this timestamp to decide how many more samples to send. */
devc->starttime = g_get_monotonic_time();
return SR_OK;
}
static int dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data)
{
struct dev_context *devc;
struct sr_datafeed_packet packet;
(void)cb_data;
devc = sdi->priv;
sr_dbg("Stopping acquisition.");
sr_session_source_remove_channel(sdi->session, devc->channel);
g_io_channel_shutdown(devc->channel, FALSE, NULL);
g_io_channel_unref(devc->channel);
devc->channel = NULL;
/* Send last packet. */
packet.type = SR_DF_END;
sr_session_send(sdi, &packet);
return SR_OK;
}
SR_PRIV struct sr_dev_driver demo_driver_info = {
.name = "demo",
.longname = "Demo driver and pattern generator",
.api_version = 1,
.init = init,
.cleanup = cleanup,
.scan = scan,
.dev_list = dev_list,
.dev_clear = NULL,
.config_get = config_get,
.config_set = config_set,
.config_list = config_list,
.dev_open = dev_open,
.dev_close = dev_close,
.dev_acquisition_start = dev_acquisition_start,
.dev_acquisition_stop = dev_acquisition_stop,
.priv = NULL,
};
| mrnuke/libsigrok | src/hardware/demo/demo.c | C | gpl-3.0 | 24,798 | [
30522,
1013,
1008,
1008,
2023,
5371,
2003,
2112,
1997,
1996,
5622,
5910,
8004,
27923,
2622,
1012,
1008,
1008,
9385,
1006,
1039,
1007,
2230,
1057,
8545,
12224,
1026,
1057,
8545,
1030,
12224,
1011,
1057,
8545,
1012,
2139,
1028,
1008,
9385,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
set LIB=%LIBRARY_LIB%;%LIB%
set LIBPATH=%LIBRARY_LIB%;%LIBPATH%
set INCLUDE=%LIBRARY_INC%;%INCLUDE%;%RECIPE_DIR%
%PYTHON% setup.py build_ext -I %LIBRARY_INC% -L %LIBRARY_LIB% -l geos_c
%PYTHON% setup.py install
if errorlevel 1 exit 1
| pelson/conda-recipes-scitools | shapely/bld.bat | Batchfile | gpl-3.0 | 235 | [
30522,
2275,
5622,
2497,
1027,
1003,
3075,
1035,
5622,
2497,
1003,
1025,
1003,
5622,
2497,
1003,
2275,
5622,
2497,
15069,
1027,
1003,
3075,
1035,
5622,
2497,
1003,
1025,
1003,
5622,
2497,
15069,
1003,
2275,
2421,
1027,
1003,
3075,
1035,
4... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
<title>onSupportNavigateUp</title>
</head><body><link href="../../../images/logo-icon.svg" rel="icon" type="image/svg"><script>var pathToRoot = "../../../";</script>
<script type="text/javascript" src="../../../scripts/sourceset_dependencies.js" async></script><link href="../../../styles/style.css" rel="Stylesheet"><link href="../../../styles/jetbrains-mono.css" rel="Stylesheet"><link href="../../../styles/main.css" rel="Stylesheet"><link href="../../../styles/prism.css" rel="Stylesheet"><link href="../../../styles/logo-styles.css" rel="Stylesheet"><script type="text/javascript" src="../../../scripts/clipboard.js" async></script><script type="text/javascript" src="../../../scripts/navigation-loader.js" async></script><script type="text/javascript" src="../../../scripts/platform-content-handler.js" async></script><script type="text/javascript" src="../../../scripts/main.js" defer></script><script type="text/javascript" src="../../../scripts/prism.js" async></script><script>const storage = localStorage.getItem("dokka-dark-mode")
const savedDarkMode = storage ? JSON.parse(storage) : false
if(savedDarkMode === true){
document.getElementsByTagName("html")[0].classList.add("theme-dark")
}</script>
<div class="navigation-wrapper" id="navigation-wrapper">
<div id="leftToggler"><span class="icon-toggler"></span></div>
<div class="library-name"><a href="../../../index.html"><span>stripe-android</span></a></div>
<div></div>
<div class="pull-right d-flex"><button id="theme-toggle-button"><span id="theme-toggle"></span></button>
<div id="searchBar"></div>
</div>
</div>
<div id="container">
<div id="leftColumn">
<div id="sideMenu"></div>
</div>
<div id="main">
<div class="main-content" id="content" pageids="payments-core::com.stripe.android.view/PaymentMethodsActivity/onSupportNavigateUp/#/PointingToDeclaration//-1622557690">
<div class="breadcrumbs"><a href="../../index.html">payments-core</a>/<a href="../index.html">com.stripe.android.view</a>/<a href="index.html">PaymentMethodsActivity</a>/<a href="on-support-navigate-up.html">onSupportNavigateUp</a></div>
<div class="cover ">
<h1 class="cover"><span>on</span><wbr><span>Support</span><wbr><span>Navigate</span><wbr><span><span>Up</span></span></h1>
</div>
<div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-depenent-content" data-active="" data-togglable=":payments-core:dokkaHtmlPartial/release"><div class="symbol monospace"><span class="token keyword">open </span><span class="token keyword">override </span><span class="token keyword">fun </span><a href="on-support-navigate-up.html"><span class="token function">onSupportNavigateUp</span></a><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">: </span><a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html">Boolean</a><span class="top-right-position"><span class="copy-icon"></span><div class="copy-popup-wrapper popup-to-left"><span class="copy-popup-icon"></span><span>Content copied to clipboard</span></div></span></div></div></div>
</div>
<div class="footer"><span class="go-to-top-icon"><a href="#content" id="go-to-top-link"></a></span><span>© 2022 Copyright</span><span class="pull-right"><span>Generated by </span><a href="https://github.com/Kotlin/dokka"><span>dokka</span><span class="padded-icon"></span></a></span></div>
</div>
</div>
</body></html>
| stripe/stripe-android | docs/payments-core/com.stripe.android.view/-payment-methods-activity/on-support-navigate-up.html | HTML | mit | 3,722 | [
30522,
1026,
16129,
1028,
1026,
2132,
1028,
1026,
18804,
2171,
1027,
1000,
3193,
6442,
1000,
4180,
1027,
1000,
9381,
1027,
5080,
1011,
9381,
1010,
3988,
1011,
4094,
1027,
1015,
1000,
25869,
13462,
1027,
1000,
21183,
2546,
1011,
1022,
1000,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* 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.
*/
(function() {
'use strict';
var ALERT_FETCH_LIMIT = 1000 * 60 * 60 * 12;
var ALERT_REFRESH_INTERVAL = 1000 * 10;
var ALERT_TEMPLATE = '#/site/${siteId}/alert/detail/${alertId}?timestamp=${timestamp}';
var serviceModule = angular.module('eagle.service');
serviceModule.service('Alert', function ($notification, Time, CompatibleEntity) {
var Alert = {
list: null,
};
$notification.getPromise().then(function () {
function queryAlerts() {
var endTime = new Time();
var list = CompatibleEntity.query("LIST", {
query: "AlertService",
startTime: endTime.clone().subtract(ALERT_FETCH_LIMIT, 'ms'),
endTime: endTime
});
list._then(function () {
if (!Alert.list) {
Alert.list = list;
return;
}
var subList = common.array.minus(list, Alert.list, ['encodedRowkey'], ['encodedRowkey']);
Alert.list = list;
$.each(subList, function (i, alert) {
$notification(alert.alertSubject, common.template(ALERT_TEMPLATE, {
siteId: alert.tags.siteId,
alertId: alert.tags.alertId,
timestamp: alert.timestamp,
}));
});
});
}
queryAlerts();
setInterval(queryAlerts, ALERT_REFRESH_INTERVAL);
});
return Alert;
});
})();
| qingwen220/eagle | eagle-server/src/main/webapp/app/dev/public/js/services/alertSrv.js | JavaScript | apache-2.0 | 2,048 | [
30522,
1013,
1008,
1008,
7000,
2000,
1996,
15895,
4007,
3192,
1006,
2004,
2546,
1007,
2104,
2028,
1008,
2030,
2062,
12130,
6105,
10540,
1012,
2156,
1996,
5060,
5371,
1008,
5500,
2007,
2023,
2147,
2005,
3176,
2592,
1008,
4953,
9385,
6095,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
Serializing X12
==============
Once you have built a parse tree, either by generating one programatically (see
{file:Generating.md Generating}) or parsing serialized input (see
{file:Parsing.md}), you can serialize it back to a string using one of the
classes in [`Stupidedi::Writer`][1].
| skaczor/stupidedi | doc/Serializing.md | Markdown | bsd-3-clause | 290 | [
30522,
7642,
6026,
1060,
12521,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
2320,
2017,
2031,
2328,
1037,
11968,
3366,
3392,
1010,
2593,
2011,
11717,
2028,
2565,
12070,
3973,
1006,
2156,
1063,
5371,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
import Test.Tasty
import Test.Tasty.QuickCheck
import Coreutils
import Data.List (intersperse)
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Unit tests" [libTests]
libTests :: TestTree
libTests = testGroup "coreutils" [splitTests]
splitTests :: TestTree
splitTests = testGroup "split"
[ testProperty "removes a" $
\as -> length (as :: String) > 10 ==>
notElem ',' . concat . split ',' . intersperse ',' $ as
, testProperty "has +1 results from element count" $
\as -> length (as :: String) > 10 ==>
let commafied = intersperse ',' as
count = length . filter (== ',') $ commafied
len = length $ split ',' commafied
in len == count + 1
]
| mrak/coreutils.hs | tests/unit/Main.hs | Haskell | mit | 768 | [
30522,
12324,
3231,
1012,
11937,
21756,
12324,
3231,
1012,
11937,
21756,
1012,
4248,
5403,
3600,
12324,
4563,
21823,
4877,
12324,
2951,
1012,
2862,
1006,
6970,
17668,
3366,
1007,
2364,
1024,
1024,
22834,
1006,
1007,
2364,
1027,
12398,
24238,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// 1000-page badge
// Awarded when total read page count exceeds 1000.
var sys = require('sys');
var _ = require('underscore');
var users = require('../../users');
var badge_template = require('./badge');
// badge key, must be unique.
var name = "1000page";
exports.badge_info =
{
id: name,
name: "1,000 Pages",
achievement: "Reading over 1,000 pages."
}
// the in-work state of a badge for a user
function Badge (userid) {
badge_template.Badge.apply(this,arguments);
this.id = name;
this.page_goal = 1000;
};
// inherit from the badge template
sys.inherits(Badge, badge_template.Badge);
// Steps to perform when a book is added or modified in the read list
Badge.prototype.add_reading_transform = function(reading,callback) {
var pages = parseInt(reading.book.pages);
if (_.isNumber(pages)) {
this.state[reading.book_id] = pages
}
callback();
};
// Steps to perform when a book is removed from the read list.
Badge.prototype.remove_book_transform = function(book,callback) {
delete(this.state[book.id]);
callback();
};
// determine if the badge should be awarded, and if yes, do so
Badge.prototype.should_award = function(callback) {
// sum all page counts in state
var pagecount = 0;
for (bookid in this.state) {
pagecount += this.state[bookid]
}
return (pagecount >= this.page_goal);
}
exports.Badge = Badge; | scsibug/read52 | badger/badges/1000page.js | JavaScript | bsd-3-clause | 1,422 | [
30522,
1013,
1013,
6694,
1011,
3931,
10780,
1013,
1013,
3018,
2043,
2561,
3191,
3931,
4175,
23651,
6694,
1012,
13075,
25353,
2015,
1027,
5478,
1006,
1005,
25353,
2015,
1005,
1007,
1025,
13075,
1035,
1027,
5478,
1006,
1005,
2104,
9363,
2890,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
namespace SMARTASK\HomeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use SMARTASK\UserBundle\Entity\User ;
use FOS\ElasticaBundle\Configuration\Search;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Task
*
* @ORM\Table(name="task")
* @Search(repositoryClass="SMARTASK\HomeBundle\Repository\TaskRepository")
* @ORM\Entity(repositoryClass="SMARTASK\HomeBundle\Repository\TaskRepository")
*/
class Task
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* Many Tasks have Many Users.
* @ORM\ManyToMany(targetEntity="SMARTASK\UserBundle\Entity\User", mappedBy="tasks")
*/
private $users;
/**
* @var string
*
* @ORM\Column(name="titre", type="string", length=255, unique=true)
* @Assert\Length(min=5)
* @Assert\NotBlank()
*/
private $titre;
/**
* @var string
*
* @ORM\Column(name="localisation", type="string", length=255, nullable=true)
*/
private $localisation;
/**
* One Task has One Groupe.
* @ORM\ManyToOne(targetEntity="SMARTASK\HomeBundle\Entity\Groupe")
* @ORM\JoinColumn(name="group_id", referencedColumnName="id")
* @Assert\NotBlank()
*/
private $group;
/**
* One Task has One resp.
* @ORM\ManyToOne(targetEntity="SMARTASK\UserBundle\Entity\User")
* @ORM\JoinColumn(name="resp_id", referencedColumnName="id")
* @Assert\NotBlank()
*/
private $resp;
/**
* One Task has One Manager.
* @ORM\ManyToOne(targetEntity="SMARTASK\UserBundle\Entity\User")
* @ORM\JoinColumn(name="manager_id", referencedColumnName="id")
* @Assert\NotBlank()
*/
private $manager;
/**
* @var datetime
*
* @ORM\Column(name="date", type="date", nullable=true)
*/
private $date;
/**
* @var time
*
* @ORM\Column(name="time", type="time", nullable=true)
* @Assert\DateTime()
*/
private $time;
/**
* @var string
*
* @ORM\Column(name="description", type="string", length=255, nullable=true)
*/
private $description;
/**
* @var int
*
* @ORM\Column(name="isalarmeon", type="integer", nullable=true)
*/
private $isalarmeon;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set titre
*
* @param string $titre
*
* @return Task
*/
public function setTitre($titre)
{
$this->titre = $titre;
return $this;
}
/**
* Get titre
*
* @return string
*/
public function getTitre()
{
return $this->titre;
}
/**
* Set localisation
*
* @param string $localisation
*
* @return Task
*/
public function setLocalisation($localisation)
{
$this->localisation = $localisation;
return $this;
}
/**
* Get localisation
*
* @return string
*/
public function getLocalisation()
{
return $this->localisation;
}
/**
* Set group
*
* @param Group $group
*
* @return Task
*/
public function setGroup($group)
{
$this->group = $group;
return $this;
}
/**
* Get group
*
* @return Group
*/
public function getGroup()
{
return $this->group;
}
/**
* Set resp
*
* @param Contact $resp
*
* @return Task
*/
public function setResp($resp)
{
$this->resp = $resp;
return $this;
}
/**
* Get manager
*
* @return User
*/
public function getManager()
{
return $this->manager;
}
/**
* Set manager
*
* @param Contact $manager
*
* @return Task
*/
public function setManager($manager)
{
$this->manager = $manager;
return $this;
}
/**
* Get resp
*
* @return Contact
*/
public function getResp()
{
return $this->resp;
}
/**
* Set date
*
* @param date $datetime
*
* @return Task
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get datetime
*
* @return datetime
*/
public function getDate()
{
return $this->date;
}
/**
* Set description
*
* @param time $time
*
* @return Task
*/
public function setTime($time)
{
$this->time = $time;
return $this;
}
/**
* Get time
*
* @return time
*/
public function getTime()
{
return $this->time;
}
/**
* Set description
*
* @param string $description
*
* @return Task
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set isalarmeon
*
* @param integer $isalarmeon
*
* @return Task
*/
public function setIsalarmeon($isalarmeon)
{
$this->isalarmeon = $isalarmeon;
return $this;
}
/**
* Get isalarmeon
*
* @return int
*/
public function getIsalarmeon()
{
return $this->isalarmeon;
}
public function getUsers() {
return $this->users;
}
public function setUsers($users) {
$this->users = $users;
return $this;
}
}
| tonymayflower/smartask | src/SMARTASK/HomeBundle/Entity/Task.php | PHP | mit | 5,793 | [
30522,
1026,
1029,
25718,
3415,
15327,
6047,
19895,
1032,
2188,
27265,
2571,
1032,
9178,
1025,
2224,
8998,
1032,
2030,
2213,
1032,
12375,
2004,
2030,
2213,
1025,
2224,
6047,
19895,
1032,
5310,
27265,
2571,
1032,
9178,
1032,
5310,
1025,
2224... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<meta name="collection" content="exclude">
<!-- Generated by javadoc (build 1.5.0-rc) on Wed Aug 11 07:29:04 PDT 2004 -->
<TITLE>
Uses of Class java.security.AlgorithmParameters (Java 2 Platform SE 5.0)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Class java.security.AlgorithmParameters (Java 2 Platform SE 5.0)";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<b>Java<sup><font size=-2>TM</font></sup> 2 Platform<br>Standard Ed. 5.0</b></EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?java/security//class-useAlgorithmParameters.html" target="_top"><B>FRAMES</B></A>
<A HREF="AlgorithmParameters.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>java.security.AlgorithmParameters</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#java.security"><B>java.security</B></A></TD>
<TD>Provides the classes and interfaces for the security framework. </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#javax.crypto"><B>javax.crypto</B></A></TD>
<TD>Provides the classes and interfaces for cryptographic operations. </TD>
</TR>
</TABLE>
<P>
<A NAME="java.security"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A> in <A HREF="../../../java/security/package-summary.html">java.security</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../java/security/package-summary.html">java.security</A> that return <A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected abstract <A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A></CODE></FONT></TD>
<TD><CODE><B>AlgorithmParameterGeneratorSpi.</B><B><A HREF="../../../java/security/AlgorithmParameterGeneratorSpi.html#engineGenerateParameters()">engineGenerateParameters</A></B>()</CODE>
<BR>
Generates the parameters.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A></CODE></FONT></TD>
<TD><CODE><B>SignatureSpi.</B><B><A HREF="../../../java/security/SignatureSpi.html#engineGetParameters()">engineGetParameters</A></B>()</CODE>
<BR>
This method is overridden by providers to return the
parameters used with this signature engine, or null
if this signature engine does not use any parameters.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A></CODE></FONT></TD>
<TD><CODE><B>AlgorithmParameterGenerator.</B><B><A HREF="../../../java/security/AlgorithmParameterGenerator.html#generateParameters()">generateParameters</A></B>()</CODE>
<BR>
Generates the parameters.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A></CODE></FONT></TD>
<TD><CODE><B>AlgorithmParameters.</B><B><A HREF="../../../java/security/AlgorithmParameters.html#getInstance(java.lang.String)">getInstance</A></B>(<A HREF="../../../java/lang/String.html" title="class in java.lang">String</A> algorithm)</CODE>
<BR>
Generates a parameter object for the specified algorithm.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A></CODE></FONT></TD>
<TD><CODE><B>AlgorithmParameters.</B><B><A HREF="../../../java/security/AlgorithmParameters.html#getInstance(java.lang.String, java.security.Provider)">getInstance</A></B>(<A HREF="../../../java/lang/String.html" title="class in java.lang">String</A> algorithm,
<A HREF="../../../java/security/Provider.html" title="class in java.security">Provider</A> provider)</CODE>
<BR>
Generates a parameter object for the specified algorithm, as supplied
by the specified provider, if such an algorithm is available from the
provider.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A></CODE></FONT></TD>
<TD><CODE><B>AlgorithmParameters.</B><B><A HREF="../../../java/security/AlgorithmParameters.html#getInstance(java.lang.String, java.lang.String)">getInstance</A></B>(<A HREF="../../../java/lang/String.html" title="class in java.lang">String</A> algorithm,
<A HREF="../../../java/lang/String.html" title="class in java.lang">String</A> provider)</CODE>
<BR>
Generates a parameter object for the specified algorithm, as supplied
by the specified provider, if such an algorithm is available from the
provider.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A></CODE></FONT></TD>
<TD><CODE><B>Signature.</B><B><A HREF="../../../java/security/Signature.html#getParameters()">getParameters</A></B>()</CODE>
<BR>
Returns the parameters used with this signature object.</TD>
</TR>
</TABLE>
<P>
<A NAME="javax.crypto"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A> in <A HREF="../../../javax/crypto/package-summary.html">javax.crypto</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../javax/crypto/package-summary.html">javax.crypto</A> that return <A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected abstract <A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A></CODE></FONT></TD>
<TD><CODE><B>CipherSpi.</B><B><A HREF="../../../javax/crypto/CipherSpi.html#engineGetParameters()">engineGetParameters</A></B>()</CODE>
<BR>
Returns the parameters used with this cipher.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A></CODE></FONT></TD>
<TD><CODE><B>EncryptedPrivateKeyInfo.</B><B><A HREF="../../../javax/crypto/EncryptedPrivateKeyInfo.html#getAlgParameters()">getAlgParameters</A></B>()</CODE>
<BR>
Returns the algorithm parameters used by the encryption algorithm.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A></CODE></FONT></TD>
<TD><CODE><B>Cipher.</B><B><A HREF="../../../javax/crypto/Cipher.html#getParameters()">getParameters</A></B>()</CODE>
<BR>
Returns the parameters used with this cipher.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../javax/crypto/package-summary.html">javax.crypto</A> with parameters of type <A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected abstract void</CODE></FONT></TD>
<TD><CODE><B>CipherSpi.</B><B><A HREF="../../../javax/crypto/CipherSpi.html#engineInit(int, java.security.Key, java.security.AlgorithmParameters, java.security.SecureRandom)">engineInit</A></B>(int opmode,
<A HREF="../../../java/security/Key.html" title="interface in java.security">Key</A> key,
<A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A> params,
<A HREF="../../../java/security/SecureRandom.html" title="class in java.security">SecureRandom</A> random)</CODE>
<BR>
Initializes this cipher with a key, a set of
algorithm parameters, and a source of randomness.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected abstract void</CODE></FONT></TD>
<TD><CODE><B>ExemptionMechanismSpi.</B><B><A HREF="../../../javax/crypto/ExemptionMechanismSpi.html#engineInit(java.security.Key, java.security.AlgorithmParameters)">engineInit</A></B>(<A HREF="../../../java/security/Key.html" title="interface in java.security">Key</A> key,
<A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A> params)</CODE>
<BR>
Initializes this exemption mechanism with a key and a set of algorithm
parameters.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>Cipher.</B><B><A HREF="../../../javax/crypto/Cipher.html#init(int, java.security.Key, java.security.AlgorithmParameters)">init</A></B>(int opmode,
<A HREF="../../../java/security/Key.html" title="interface in java.security">Key</A> key,
<A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A> params)</CODE>
<BR>
Initializes this cipher with a key and a set of algorithm
parameters.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>Cipher.</B><B><A HREF="../../../javax/crypto/Cipher.html#init(int, java.security.Key, java.security.AlgorithmParameters, java.security.SecureRandom)">init</A></B>(int opmode,
<A HREF="../../../java/security/Key.html" title="interface in java.security">Key</A> key,
<A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A> params,
<A HREF="../../../java/security/SecureRandom.html" title="class in java.security">SecureRandom</A> random)</CODE>
<BR>
Initializes this cipher with a key, a set of algorithm
parameters, and a source of randomness.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ExemptionMechanism.</B><B><A HREF="../../../javax/crypto/ExemptionMechanism.html#init(java.security.Key, java.security.AlgorithmParameters)">init</A></B>(<A HREF="../../../java/security/Key.html" title="interface in java.security">Key</A> key,
<A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A> params)</CODE>
<BR>
Initializes this exemption mechanism with a key and a set of algorithm
parameters.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Constructors in <A HREF="../../../javax/crypto/package-summary.html">javax.crypto</A> with parameters of type <A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../javax/crypto/EncryptedPrivateKeyInfo.html#EncryptedPrivateKeyInfo(java.security.AlgorithmParameters, byte[])">EncryptedPrivateKeyInfo</A></B>(<A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security">AlgorithmParameters</A> algParams,
byte[] encryptedData)</CODE>
<BR>
Constructs an <code>EncryptedPrivateKeyInfo</code> from the
encryption algorithm parameters and the encrypted data.</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../java/security/AlgorithmParameters.html" title="class in java.security"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<b>Java<sup><font size=-2>TM</font></sup> 2 Platform<br>Standard Ed. 5.0</b></EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?java/security//class-useAlgorithmParameters.html" target="_top"><B>FRAMES</B></A>
<A HREF="AlgorithmParameters.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<font size="-1"><a href="http://java.sun.com/cgi-bin/bugreport.cgi">Submit a bug or feature</a><br>For further API reference and developer documentation, see <a href="../../../../relnotes/devdocs-vs-specs.html">Java 2 SDK SE Developer Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples. <p>Copyright © 2004, 2010 Oracle and/or its affiliates. All rights reserved. Use is subject to <a href="../../../../relnotes/license.html">license terms</a>. Also see the <a href="http://java.sun.com/docs/redist.html">documentation redistribution policy</a>.</font>
<!-- Start SiteCatalyst code -->
<script language="JavaScript" src="http://www.oracle.com/ocom/groups/systemobject/@mktg_admin/documents/systemobject/s_code_download.js"></script>
<script language="JavaScript" src="http://www.oracle.com/ocom/groups/systemobject/@mktg_admin/documents/systemobject/s_code.js"></script>
<!-- ********** DO NOT ALTER ANYTHING BELOW THIS LINE ! *********** -->
<!-- Below code will send the info to Omniture server -->
<script language="javascript">var s_code=s.t();if(s_code)document.write(s_code)</script>
<!-- End SiteCatalyst code -->
</body>
</HTML>
| Smolations/more-dash-docsets | docsets/Java 5.docset/Contents/Resources/Documents/java/security/class-use/AlgorithmParameters.html | HTML | mit | 21,020 | [
30522,
1026,
999,
9986,
13874,
16129,
2270,
1000,
1011,
1013,
1013,
1059,
2509,
2278,
1013,
1013,
26718,
2094,
16129,
1018,
1012,
5890,
17459,
1013,
1013,
4372,
1000,
1000,
8299,
1024,
1013,
1013,
7479,
1012,
1059,
2509,
1012,
8917,
1013,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>Direct Spherical Harmonic Transform: Member List</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.4.4 -->
<div class="qindex"> <form class="search" action="search.php" method="get">
<a class="qindex" href="index.html">Main Page</a> | <a class="qindex" href="classes.html">Alphabetical List</a> | <a class="qindex" href="annotated.html">Class List</a> | <a class="qindex" href="files.html">File List</a> | <a class="qindex" href="functions.html">Class Members</a> | <a class="qindex" href="globals.html">File Members</a> | <span class="search"><u>S</u>earch for <input class="search" type="text" name="query" value="" size="20" accesskey="s"/></span></form></div>
<h1>CModel Member List</h1>This is the complete list of members for <a class="el" href="classCModel.html">CModel</a>, including all inherited members.<p><table>
<tr class="memlist"><td><a class="el" href="classCModel.html#a7">AllFacetHarmonics</a>(int bw, double r, gsl_complex *coeff)</td><td><a class="el" href="classCModel.html">CModel</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classCModel.html#a0">CModel</a>()</td><td><a class="el" href="classCModel.html">CModel</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classCModel.html#a2">CModel</a>(const CModel &m)</td><td><a class="el" href="classCModel.html">CModel</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classCModel.html#r1">f_no</a></td><td><a class="el" href="classCModel.html">CModel</a></td><td><code> [private]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classCModel.html#a6">FacetHarmonics</a>(int fh, int bw, double r, gsl_complex *coeff)</td><td><a class="el" href="classCModel.html">CModel</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classCModel.html#a8">Facets_no</a>()</td><td><a class="el" href="classCModel.html">CModel</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classCModel.html#r3">flist</a></td><td><a class="el" href="classCModel.html">CModel</a></td><td><code> [private]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classCModel.html#a3">LoadModel</a>(char *fname)</td><td><a class="el" href="classCModel.html">CModel</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classCModel.html#a5">Normalize</a>()</td><td><a class="el" href="classCModel.html">CModel</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classCModel.html#r0">p_no</a></td><td><a class="el" href="classCModel.html">CModel</a></td><td><code> [private]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classCModel.html#r2">plist</a></td><td><a class="el" href="classCModel.html">CModel</a></td><td><code> [private]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classCModel.html#a4">SaveModel</a>(char *fname)</td><td><a class="el" href="classCModel.html">CModel</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classCModel.html#a9">Vertices_no</a>()</td><td><a class="el" href="classCModel.html">CModel</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classCModel.html#a1">~CModel</a>()</td><td><a class="el" href="classCModel.html">CModel</a></td><td></td></tr>
</table><hr size="1"><address style="align: right;"><small>Generated on Mon Oct 2 08:45:58 2006 for Direct Spherical Harmonic Transform by
<a href="http://www.doxygen.org/index.html">
<img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.4.4 </small></address>
</body>
</html>
| erich666/jgt-code | Volume_11/Number_2/Mousa2006/html/classCModel-members.html | HTML | mit | 3,800 | [
30522,
1026,
999,
9986,
13874,
16129,
2270,
1000,
1011,
1013,
1013,
1059,
2509,
2278,
1013,
1013,
26718,
2094,
16129,
1018,
1012,
5890,
17459,
1013,
1013,
4372,
1000,
1028,
1026,
30524,
1000,
1028,
1026,
2516,
1028,
3622,
18970,
19452,
1093... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/* Machine independent support for QNX Neutrino /proc (process file system)
for GDB. Written by Colin Burgess at QNX Software Systems Limited.
Copyright (C) 2003-2017 Free Software Foundation, Inc.
Contributed by QNX Software Systems Ltd.
This file is part of GDB.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include "defs.h"
#include <fcntl.h>
#include <spawn.h>
#include <sys/debug.h>
#include <sys/procfs.h>
#include <sys/neutrino.h>
#include <sys/syspage.h>
#include <dirent.h>
#include <sys/netmgr.h>
#include <sys/auxv.h>
#include "gdbcore.h"
#include "inferior.h"
#include "target.h"
#include "objfiles.h"
#include "gdbthread.h"
#include "nto-tdep.h"
#include "command.h"
#include "regcache.h"
#include "solib.h"
#include "inf-child.h"
#include "common/filestuff.h"
#define NULL_PID 0
#define _DEBUG_FLAG_TRACE (_DEBUG_FLAG_TRACE_EXEC|_DEBUG_FLAG_TRACE_RD|\
_DEBUG_FLAG_TRACE_WR|_DEBUG_FLAG_TRACE_MODIFY)
int ctl_fd;
static sighandler_t ofunc;
static procfs_run run;
static ptid_t do_attach (ptid_t ptid);
static int procfs_can_use_hw_breakpoint (struct target_ops *self,
enum bptype, int, int);
static int procfs_insert_hw_watchpoint (struct target_ops *self,
CORE_ADDR addr, int len,
enum target_hw_bp_type type,
struct expression *cond);
static int procfs_remove_hw_watchpoint (struct target_ops *self,
CORE_ADDR addr, int len,
enum target_hw_bp_type type,
struct expression *cond);
static int procfs_stopped_by_watchpoint (struct target_ops *ops);
/* These two globals are only ever set in procfs_open_1, but are
referenced elsewhere. 'nto_procfs_node' is a flag used to say
whether we are local, or we should get the current node descriptor
for the remote QNX node. */
static char *nodestr;
static unsigned nto_procfs_node = ND_LOCAL_NODE;
/* Return the current QNX Node, or error out. This is a simple
wrapper for the netmgr_strtond() function. The reason this
is required is because QNX node descriptors are transient so
we have to re-acquire them every time. */
static unsigned
nto_node (void)
{
unsigned node;
if (ND_NODE_CMP (nto_procfs_node, ND_LOCAL_NODE) == 0
|| nodestr == NULL)
return ND_LOCAL_NODE;
node = netmgr_strtond (nodestr, 0);
if (node == -1)
error (_("Lost the QNX node. Debug session probably over."));
return (node);
}
static enum gdb_osabi
procfs_is_nto_target (bfd *abfd)
{
return GDB_OSABI_QNXNTO;
}
/* This is called when we call 'target native' or 'target procfs
<arg>' from the (gdb) prompt. For QNX6 (nto), the only valid arg
will be a QNX node string, eg: "/net/some_node". If arg is not a
valid QNX node, we will default to local. */
static void
procfs_open_1 (struct target_ops *ops, const char *arg, int from_tty)
{
char *endstr;
char buffer[50];
int fd, total_size;
procfs_sysinfo *sysinfo;
struct cleanup *cleanups;
char nto_procfs_path[PATH_MAX];
/* Offer to kill previous inferiors before opening this target. */
target_preopen (from_tty);
nto_is_nto_target = procfs_is_nto_target;
/* Set the default node used for spawning to this one,
and only override it if there is a valid arg. */
xfree (nodestr);
nodestr = NULL;
nto_procfs_node = ND_LOCAL_NODE;
nodestr = (arg != NULL) ? xstrdup (arg) : NULL;
init_thread_list ();
if (nodestr)
{
nto_procfs_node = netmgr_strtond (nodestr, &endstr);
if (nto_procfs_node == -1)
{
if (errno == ENOTSUP)
printf_filtered ("QNX Net Manager not found.\n");
printf_filtered ("Invalid QNX node %s: error %d (%s).\n", nodestr,
errno, safe_strerror (errno));
xfree (nodestr);
nodestr = NULL;
nto_procfs_node = ND_LOCAL_NODE;
}
else if (*endstr)
{
if (*(endstr - 1) == '/')
*(endstr - 1) = 0;
else
*endstr = 0;
}
}
snprintf (nto_procfs_path, PATH_MAX - 1, "%s%s",
(nodestr != NULL) ? nodestr : "", "/proc");
fd = open (nto_procfs_path, O_RDONLY);
if (fd == -1)
{
printf_filtered ("Error opening %s : %d (%s)\n", nto_procfs_path, errno,
safe_strerror (errno));
error (_("Invalid procfs arg"));
}
cleanups = make_cleanup_close (fd);
sysinfo = (void *) buffer;
if (devctl (fd, DCMD_PROC_SYSINFO, sysinfo, sizeof buffer, 0) != EOK)
{
printf_filtered ("Error getting size: %d (%s)\n", errno,
safe_strerror (errno));
error (_("Devctl failed."));
}
else
{
total_size = sysinfo->total_size;
sysinfo = alloca (total_size);
if (sysinfo == NULL)
{
printf_filtered ("Memory error: %d (%s)\n", errno,
safe_strerror (errno));
error (_("alloca failed."));
}
else
{
if (devctl (fd, DCMD_PROC_SYSINFO, sysinfo, total_size, 0) != EOK)
{
printf_filtered ("Error getting sysinfo: %d (%s)\n", errno,
safe_strerror (errno));
error (_("Devctl failed."));
}
else
{
if (sysinfo->type !=
nto_map_arch_to_cputype (gdbarch_bfd_arch_info
(target_gdbarch ())->arch_name))
error (_("Invalid target CPU."));
}
}
}
do_cleanups (cleanups);
inf_child_open_target (ops, arg, from_tty);
printf_filtered ("Debugging using %s\n", nto_procfs_path);
}
static void
procfs_set_thread (ptid_t ptid)
{
pid_t tid;
tid = ptid_get_tid (ptid);
devctl (ctl_fd, DCMD_PROC_CURTHREAD, &tid, sizeof (tid), 0);
}
/* Return nonzero if the thread TH is still alive. */
static int
procfs_thread_alive (struct target_ops *ops, ptid_t ptid)
{
pid_t tid;
pid_t pid;
procfs_status status;
int err;
tid = ptid_get_tid (ptid);
pid = ptid_get_pid (ptid);
if (kill (pid, 0) == -1)
return 0;
status.tid = tid;
if ((err = devctl (ctl_fd, DCMD_PROC_TIDSTATUS,
&status, sizeof (status), 0)) != EOK)
return 0;
/* Thread is alive or dead but not yet joined,
or dead and there is an alive (or dead unjoined) thread with
higher tid.
If the tid is not the same as requested, requested tid is dead. */
return (status.tid == tid) && (status.state != STATE_DEAD);
}
static void
update_thread_private_data_name (struct thread_info *new_thread,
const char *newname)
{
int newnamelen;
struct private_thread_info *pti;
gdb_assert (newname != NULL);
gdb_assert (new_thread != NULL);
newnamelen = strlen (newname);
if (!new_thread->priv)
{
new_thread->priv = xmalloc (offsetof (struct private_thread_info,
name)
+ newnamelen + 1);
memcpy (new_thread->priv->name, newname, newnamelen + 1);
}
else if (strcmp (newname, new_thread->priv->name) != 0)
{
/* Reallocate if neccessary. */
int oldnamelen = strlen (new_thread->priv->name);
if (oldnamelen < newnamelen)
new_thread->priv = xrealloc (new_thread->priv,
offsetof (struct private_thread_info,
name)
+ newnamelen + 1);
memcpy (new_thread->priv->name, newname, newnamelen + 1);
}
}
static void
update_thread_private_data (struct thread_info *new_thread,
pthread_t tid, int state, int flags)
{
struct private_thread_info *pti;
procfs_info pidinfo;
struct _thread_name *tn;
procfs_threadctl tctl;
#if _NTO_VERSION > 630
gdb_assert (new_thread != NULL);
if (devctl (ctl_fd, DCMD_PROC_INFO, &pidinfo,
sizeof(pidinfo), 0) != EOK)
return;
memset (&tctl, 0, sizeof (tctl));
tctl.cmd = _NTO_TCTL_NAME;
tn = (struct _thread_name *) (&tctl.data);
/* Fetch name for the given thread. */
tctl.tid = tid;
tn->name_buf_len = sizeof (tctl.data) - sizeof (*tn);
tn->new_name_len = -1; /* Getting, not setting. */
if (devctl (ctl_fd, DCMD_PROC_THREADCTL, &tctl, sizeof (tctl), NULL) != EOK)
tn->name_buf[0] = '\0';
tn->name_buf[_NTO_THREAD_NAME_MAX] = '\0';
update_thread_private_data_name (new_thread, tn->name_buf);
pti = (struct private_thread_info *) new_thread->priv;
pti->tid = tid;
pti->state = state;
pti->flags = flags;
#endif /* _NTO_VERSION */
}
static void
procfs_update_thread_list (struct target_ops *ops)
{
procfs_status status;
pid_t pid;
ptid_t ptid;
pthread_t tid;
struct thread_info *new_thread;
if (ctl_fd == -1)
return;
prune_threads ();
pid = ptid_get_pid (inferior_ptid);
status.tid = 1;
for (tid = 1;; ++tid)
{
if (status.tid == tid
&& (devctl (ctl_fd, DCMD_PROC_TIDSTATUS, &status, sizeof (status), 0)
!= EOK))
break;
if (status.tid != tid)
/* The reason why this would not be equal is that devctl might have
returned different tid, meaning the requested tid no longer exists
(e.g. thread exited). */
continue;
ptid = ptid_build (pid, 0, tid);
new_thread = find_thread_ptid (ptid);
if (!new_thread)
new_thread = add_thread (ptid);
update_thread_private_data (new_thread, tid, status.state, 0);
status.tid++;
}
return;
}
static void
do_closedir_cleanup (void *dir)
{
closedir (dir);
}
static void
procfs_pidlist (char *args, int from_tty)
{
DIR *dp = NULL;
struct dirent *dirp = NULL;
char buf[PATH_MAX];
procfs_info *pidinfo = NULL;
procfs_debuginfo *info = NULL;
procfs_status *status = NULL;
pid_t num_threads = 0;
pid_t pid;
char name[512];
struct cleanup *cleanups;
char procfs_dir[PATH_MAX];
snprintf (procfs_dir, sizeof (procfs_dir), "%s%s",
(nodestr != NULL) ? nodestr : "", "/proc");
dp = opendir (procfs_dir);
if (dp == NULL)
{
fprintf_unfiltered (gdb_stderr, "failed to opendir \"%s\" - %d (%s)",
procfs_dir, errno, safe_strerror (errno));
return;
}
cleanups = make_cleanup (do_closedir_cleanup, dp);
/* Start scan at first pid. */
rewinddir (dp);
do
{
int fd;
struct cleanup *inner_cleanup;
/* Get the right pid and procfs path for the pid. */
do
{
dirp = readdir (dp);
if (dirp == NULL)
{
do_cleanups (cleanups);
return;
}
snprintf (buf, sizeof (buf), "%s%s/%s/as",
(nodestr != NULL) ? nodestr : "",
"/proc", dirp->d_name);
pid = atoi (dirp->d_name);
}
while (pid == 0);
/* Open the procfs path. */
fd = open (buf, O_RDONLY);
if (fd == -1)
{
fprintf_unfiltered (gdb_stderr, "failed to open %s - %d (%s)\n",
buf, errno, safe_strerror (errno));
continue;
}
inner_cleanup = make_cleanup_close (fd);
pidinfo = (procfs_info *) buf;
if (devctl (fd, DCMD_PROC_INFO, pidinfo, sizeof (buf), 0) != EOK)
{
fprintf_unfiltered (gdb_stderr,
"devctl DCMD_PROC_INFO failed - %d (%s)\n",
errno, safe_strerror (errno));
break;
}
num_threads = pidinfo->num_threads;
info = (procfs_debuginfo *) buf;
if (devctl (fd, DCMD_PROC_MAPDEBUG_BASE, info, sizeof (buf), 0) != EOK)
strcpy (name, "unavailable");
else
strcpy (name, info->path);
/* Collect state info on all the threads. */
status = (procfs_status *) buf;
for (status->tid = 1; status->tid <= num_threads; status->tid++)
{
const int err
= devctl (fd, DCMD_PROC_TIDSTATUS, status, sizeof (buf), 0);
printf_filtered ("%s - %d", name, pid);
if (err == EOK && status->tid != 0)
printf_filtered ("/%d\n", status->tid);
else
{
printf_filtered ("\n");
break;
}
}
do_cleanups (inner_cleanup);
}
while (dirp != NULL);
do_cleanups (cleanups);
return;
}
static void
procfs_meminfo (char *args, int from_tty)
{
procfs_mapinfo *mapinfos = NULL;
static int num_mapinfos = 0;
procfs_mapinfo *mapinfo_p, *mapinfo_p2;
int flags = ~0, err, num, i, j;
struct
{
procfs_debuginfo info;
char buff[_POSIX_PATH_MAX];
} map;
struct info
{
unsigned addr;
unsigned size;
unsigned flags;
unsigned debug_vaddr;
unsigned long long offset;
};
struct printinfo
{
unsigned long long ino;
unsigned dev;
struct info text;
struct info data;
char name[256];
} printme;
/* Get the number of map entrys. */
err = devctl (ctl_fd, DCMD_PROC_MAPINFO, NULL, 0, &num);
if (err != EOK)
{
printf ("failed devctl num mapinfos - %d (%s)\n", err,
safe_strerror (err));
return;
}
mapinfos = XNEWVEC (procfs_mapinfo, num);
num_mapinfos = num;
mapinfo_p = mapinfos;
/* Fill the map entrys. */
err = devctl (ctl_fd, DCMD_PROC_MAPINFO, mapinfo_p, num
* sizeof (procfs_mapinfo), &num);
if (err != EOK)
{
printf ("failed devctl mapinfos - %d (%s)\n", err, safe_strerror (err));
xfree (mapinfos);
return;
}
num = std::min (num, num_mapinfos);
/* Run through the list of mapinfos, and store the data and text info
so we can print it at the bottom of the loop. */
for (mapinfo_p = mapinfos, i = 0; i < num; i++, mapinfo_p++)
{
if (!(mapinfo_p->flags & flags))
mapinfo_p->ino = 0;
if (mapinfo_p->ino == 0) /* Already visited. */
continue;
map.info.vaddr = mapinfo_p->vaddr;
err = devctl (ctl_fd, DCMD_PROC_MAPDEBUG, &map, sizeof (map), 0);
if (err != EOK)
continue;
memset (&printme, 0, sizeof printme);
printme.dev = mapinfo_p->dev;
printme.ino = mapinfo_p->ino;
printme.text.addr = mapinfo_p->vaddr;
printme.text.size = mapinfo_p->size;
printme.text.flags = mapinfo_p->flags;
printme.text.offset = mapinfo_p->offset;
printme.text.debug_vaddr = map.info.vaddr;
strcpy (printme.name, map.info.path);
/* Check for matching data. */
for (mapinfo_p2 = mapinfos, j = 0; j < num; j++, mapinfo_p2++)
{
if (mapinfo_p2->vaddr != mapinfo_p->vaddr
&& mapinfo_p2->ino == mapinfo_p->ino
&& mapinfo_p2->dev == mapinfo_p->dev)
{
map.info.vaddr = mapinfo_p2->vaddr;
err =
devctl (ctl_fd, DCMD_PROC_MAPDEBUG, &map, sizeof (map), 0);
if (err != EOK)
continue;
if (strcmp (map.info.path, printme.name))
continue;
/* Lower debug_vaddr is always text, if nessessary, swap. */
if ((int) map.info.vaddr < (int) printme.text.debug_vaddr)
{
memcpy (&(printme.data), &(printme.text),
sizeof (printme.data));
printme.text.addr = mapinfo_p2->vaddr;
printme.text.size = mapinfo_p2->size;
printme.text.flags = mapinfo_p2->flags;
printme.text.offset = mapinfo_p2->offset;
printme.text.debug_vaddr = map.info.vaddr;
}
else
{
printme.data.addr = mapinfo_p2->vaddr;
printme.data.size = mapinfo_p2->size;
printme.data.flags = mapinfo_p2->flags;
printme.data.offset = mapinfo_p2->offset;
printme.data.debug_vaddr = map.info.vaddr;
}
mapinfo_p2->ino = 0;
}
}
mapinfo_p->ino = 0;
printf_filtered ("%s\n", printme.name);
printf_filtered ("\ttext=%08x bytes @ 0x%08x\n", printme.text.size,
printme.text.addr);
printf_filtered ("\t\tflags=%08x\n", printme.text.flags);
printf_filtered ("\t\tdebug=%08x\n", printme.text.debug_vaddr);
printf_filtered ("\t\toffset=%s\n", phex (printme.text.offset, 8));
if (printme.data.size)
{
printf_filtered ("\tdata=%08x bytes @ 0x%08x\n", printme.data.size,
printme.data.addr);
printf_filtered ("\t\tflags=%08x\n", printme.data.flags);
printf_filtered ("\t\tdebug=%08x\n", printme.data.debug_vaddr);
printf_filtered ("\t\toffset=%s\n", phex (printme.data.offset, 8));
}
printf_filtered ("\tdev=0x%x\n", printme.dev);
printf_filtered ("\tino=0x%x\n", (unsigned int) printme.ino);
}
xfree (mapinfos);
return;
}
/* Print status information about what we're accessing. */
static void
procfs_files_info (struct target_ops *ignore)
{
struct inferior *inf = current_inferior ();
printf_unfiltered ("\tUsing the running image of %s %s via %s.\n",
inf->attach_flag ? "attached" : "child",
target_pid_to_str (inferior_ptid),
(nodestr != NULL) ? nodestr : "local node");
}
/* Target to_pid_to_exec_file implementation. */
static char *
procfs_pid_to_exec_file (struct target_ops *ops, const int pid)
{
int proc_fd;
static char proc_path[PATH_MAX];
ssize_t rd;
/* Read exe file name. */
snprintf (proc_path, sizeof (proc_path), "%s/proc/%d/exefile",
(nodestr != NULL) ? nodestr : "", pid);
proc_fd = open (proc_path, O_RDONLY);
if (proc_fd == -1)
return NULL;
rd = read (proc_fd, proc_path, sizeof (proc_path) - 1);
close (proc_fd);
if (rd <= 0)
{
proc_path[0] = '\0';
return NULL;
}
proc_path[rd] = '\0';
return proc_path;
}
/* Attach to process PID, then initialize for debugging it. */
static void
procfs_attach (struct target_ops *ops, const char *args, int from_tty)
{
char *exec_file;
int pid;
struct inferior *inf;
pid = parse_pid_to_attach (args);
if (pid == getpid ())
error (_("Attaching GDB to itself is not a good idea..."));
if (from_tty)
{
exec_file = (char *) get_exec_file (0);
if (exec_file)
printf_unfiltered ("Attaching to program `%s', %s\n", exec_file,
target_pid_to_str (pid_to_ptid (pid)));
else
printf_unfiltered ("Attaching to %s\n",
target_pid_to_str (pid_to_ptid (pid)));
gdb_flush (gdb_stdout);
}
inferior_ptid = do_attach (pid_to_ptid (pid));
inf = current_inferior ();
inferior_appeared (inf, pid);
inf->attach_flag = 1;
if (!target_is_pushed (ops))
push_target (ops);
procfs_update_thread_list (ops);
}
static void
procfs_post_attach (struct target_ops *self, pid_t pid)
{
if (exec_bfd)
solib_create_inferior_hook (0);
}
static ptid_t
do_attach (ptid_t ptid)
{
procfs_status status;
struct sigevent event;
char path[PATH_MAX];
snprintf (path, PATH_MAX - 1, "%s%s/%d/as",
(nodestr != NULL) ? nodestr : "", "/proc", ptid_get_pid (ptid));
ctl_fd = open (path, O_RDWR);
if (ctl_fd == -1)
error (_("Couldn't open proc file %s, error %d (%s)"), path, errno,
safe_strerror (errno));
if (devctl (ctl_fd, DCMD_PROC_STOP, &status, sizeof (status), 0) != EOK)
error (_("Couldn't stop process"));
/* Define a sigevent for process stopped notification. */
event.sigev_notify = SIGEV_SIGNAL_THREAD;
event.sigev_signo = SIGUSR1;
event.sigev_code = 0;
event.sigev_value.sival_ptr = NULL;
event.sigev_priority = -1;
devctl (ctl_fd, DCMD_PROC_EVENT, &event, sizeof (event), 0);
if (devctl (ctl_fd, DCMD_PROC_STATUS, &status, sizeof (status), 0) == EOK
&& status.flags & _DEBUG_FLAG_STOPPED)
SignalKill (nto_node (), ptid_get_pid (ptid), 0, SIGCONT, 0, 0);
nto_init_solib_absolute_prefix ();
return ptid_build (ptid_get_pid (ptid), 0, status.tid);
}
/* Ask the user what to do when an interrupt is received. */
static void
interrupt_query (void)
{
if (query (_("Interrupted while waiting for the program.\n\
Give up (and stop debugging it)? ")))
{
target_mourn_inferior (inferior_ptid);
quit ();
}
}
/* The user typed ^C twice. */
static void
nto_handle_sigint_twice (int signo)
{
signal (signo, ofunc);
interrupt_query ();
signal (signo, nto_handle_sigint_twice);
}
static void
nto_handle_sigint (int signo)
{
/* If this doesn't work, try more severe steps. */
signal (signo, nto_handle_sigint_twice);
target_interrupt (inferior_ptid);
}
static ptid_t
procfs_wait (struct target_ops *ops,
ptid_t ptid, struct target_waitstatus *ourstatus, int options)
{
sigset_t set;
siginfo_t info;
procfs_status status;
static int exit_signo = 0; /* To track signals that cause termination. */
ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
if (ptid_equal (inferior_ptid, null_ptid))
{
ourstatus->kind = TARGET_WAITKIND_STOPPED;
ourstatus->value.sig = GDB_SIGNAL_0;
exit_signo = 0;
return null_ptid;
}
sigemptyset (&set);
sigaddset (&set, SIGUSR1);
devctl (ctl_fd, DCMD_PROC_STATUS, &status, sizeof (status), 0);
while (!(status.flags & _DEBUG_FLAG_ISTOP))
{
ofunc = signal (SIGINT, nto_handle_sigint);
sigwaitinfo (&set, &info);
signal (SIGINT, ofunc);
devctl (ctl_fd, DCMD_PROC_STATUS, &status, sizeof (status), 0);
}
nto_inferior_data (NULL)->stopped_flags = status.flags;
nto_inferior_data (NULL)->stopped_pc = status.ip;
if (status.flags & _DEBUG_FLAG_SSTEP)
{
ourstatus->kind = TARGET_WAITKIND_STOPPED;
ourstatus->value.sig = GDB_SIGNAL_TRAP;
}
/* Was it a breakpoint? */
else if (status.flags & _DEBUG_FLAG_TRACE)
{
ourstatus->kind = TARGET_WAITKIND_STOPPED;
ourstatus->value.sig = GDB_SIGNAL_TRAP;
}
else if (status.flags & _DEBUG_FLAG_ISTOP)
{
switch (status.why)
{
case _DEBUG_WHY_SIGNALLED:
ourstatus->kind = TARGET_WAITKIND_STOPPED;
ourstatus->value.sig =
gdb_signal_from_host (status.info.si_signo);
exit_signo = 0;
break;
case _DEBUG_WHY_FAULTED:
ourstatus->kind = TARGET_WAITKIND_STOPPED;
if (status.info.si_signo == SIGTRAP)
{
ourstatus->value.sig = 0;
exit_signo = 0;
}
else
{
ourstatus->value.sig =
gdb_signal_from_host (status.info.si_signo);
exit_signo = ourstatus->value.sig;
}
break;
case _DEBUG_WHY_TERMINATED:
{
int waitval = 0;
waitpid (ptid_get_pid (inferior_ptid), &waitval, WNOHANG);
if (exit_signo)
{
/* Abnormal death. */
ourstatus->kind = TARGET_WAITKIND_SIGNALLED;
ourstatus->value.sig = exit_signo;
}
else
{
/* Normal death. */
ourstatus->kind = TARGET_WAITKIND_EXITED;
ourstatus->value.integer = WEXITSTATUS (waitval);
}
exit_signo = 0;
break;
}
case _DEBUG_WHY_REQUESTED:
/* We are assuming a requested stop is due to a SIGINT. */
ourstatus->kind = TARGET_WAITKIND_STOPPED;
ourstatus->value.sig = GDB_SIGNAL_INT;
exit_signo = 0;
break;
}
}
return ptid_build (status.pid, 0, status.tid);
}
/* Read the current values of the inferior's registers, both the
general register set and floating point registers (if supported)
and update gdb's idea of their current values. */
static void
procfs_fetch_registers (struct target_ops *ops,
struct regcache *regcache, int regno)
{
union
{
procfs_greg greg;
procfs_fpreg fpreg;
procfs_altreg altreg;
}
reg;
int regsize;
procfs_set_thread (regcache_get_ptid (regcache));
if (devctl (ctl_fd, DCMD_PROC_GETGREG, ®, sizeof (reg), ®size) == EOK)
nto_supply_gregset (regcache, (char *) ®.greg);
if (devctl (ctl_fd, DCMD_PROC_GETFPREG, ®, sizeof (reg), ®size)
== EOK)
nto_supply_fpregset (regcache, (char *) ®.fpreg);
if (devctl (ctl_fd, DCMD_PROC_GETALTREG, ®, sizeof (reg), ®size)
== EOK)
nto_supply_altregset (regcache, (char *) ®.altreg);
}
/* Helper for procfs_xfer_partial that handles memory transfers.
Arguments are like target_xfer_partial. */
static enum target_xfer_status
procfs_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
{
int nbytes;
if (lseek (ctl_fd, (off_t) memaddr, SEEK_SET) != (off_t) memaddr)
return TARGET_XFER_E_IO;
if (writebuf != NULL)
nbytes = write (ctl_fd, writebuf, len);
else
nbytes = read (ctl_fd, readbuf, len);
if (nbytes <= 0)
return TARGET_XFER_E_IO;
*xfered_len = nbytes;
return TARGET_XFER_OK;
}
/* Target to_xfer_partial implementation. */
static enum target_xfer_status
procfs_xfer_partial (struct target_ops *ops, enum target_object object,
const char *annex, gdb_byte *readbuf,
const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
ULONGEST *xfered_len)
{
switch (object)
{
case TARGET_OBJECT_MEMORY:
return procfs_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
case TARGET_OBJECT_AUXV:
if (readbuf != NULL)
{
int err;
CORE_ADDR initial_stack;
debug_process_t procinfo;
/* For 32-bit architecture, size of auxv_t is 8 bytes. */
const unsigned int sizeof_auxv_t = sizeof (auxv_t);
const unsigned int sizeof_tempbuf = 20 * sizeof_auxv_t;
int tempread;
gdb_byte *const tempbuf = alloca (sizeof_tempbuf);
if (tempbuf == NULL)
return TARGET_XFER_E_IO;
err = devctl (ctl_fd, DCMD_PROC_INFO, &procinfo,
sizeof procinfo, 0);
if (err != EOK)
return TARGET_XFER_E_IO;
initial_stack = procinfo.initial_stack;
/* procfs is always 'self-hosted', no byte-order manipulation. */
tempread = nto_read_auxv_from_initial_stack (initial_stack, tempbuf,
sizeof_tempbuf,
sizeof (auxv_t));
tempread = std::min (tempread, len) - offset;
memcpy (readbuf, tempbuf + offset, tempread);
*xfered_len = tempread;
return tempread ? TARGET_XFER_OK : TARGET_XFER_EOF;
}
/* Fallthru */
default:
return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
readbuf, writebuf, offset, len,
xfered_len);
}
}
/* Take a program previously attached to and detaches it.
The program resumes execution and will no longer stop
on signals, etc. We'd better not have left any breakpoints
in the program or it'll die when it hits one. */
static void
procfs_detach (struct target_ops *ops, const char *args, int from_tty)
{
int siggnal = 0;
int pid;
target_announce_detach ();
if (args)
siggnal = atoi (args);
if (siggnal)
SignalKill (nto_node (), ptid_get_pid (inferior_ptid), 0, siggnal, 0, 0);
close (ctl_fd);
ctl_fd = -1;
pid = ptid_get_pid (inferior_ptid);
inferior_ptid = null_ptid;
detach_inferior (pid);
init_thread_list ();
inf_child_maybe_unpush_target (ops);
}
static int
procfs_breakpoint (CORE_ADDR addr, int type, int size)
{
procfs_break brk;
brk.type = type;
brk.addr = addr;
brk.size = size;
errno = devctl (ctl_fd, DCMD_PROC_BREAK, &brk, sizeof (brk), 0);
if (errno != EOK)
return 1;
return 0;
}
static int
procfs_insert_breakpoint (struct target_ops *ops, struct gdbarch *gdbarch,
struct bp_target_info *bp_tgt)
{
bp_tgt->placed_address = bp_tgt->reqstd_address;
return procfs_breakpoint (bp_tgt->placed_address, _DEBUG_BREAK_EXEC, 0);
}
static int
procfs_remove_breakpoint (struct target_ops *ops, struct gdbarch *gdbarch,
struct bp_target_info *bp_tgt,
enum remove_bp_reason reason)
{
return procfs_breakpoint (bp_tgt->placed_address, _DEBUG_BREAK_EXEC, -1);
}
static int
procfs_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
struct bp_target_info *bp_tgt)
{
bp_tgt->placed_address = bp_tgt->reqstd_address;
return procfs_breakpoint (bp_tgt->placed_address,
_DEBUG_BREAK_EXEC | _DEBUG_BREAK_HW, 0);
}
static int
procfs_remove_hw_breakpoint (struct target_ops *self,
struct gdbarch *gdbarch,
struct bp_target_info *bp_tgt)
{
return procfs_breakpoint (bp_tgt->placed_address,
_DEBUG_BREAK_EXEC | _DEBUG_BREAK_HW, -1);
}
static void
procfs_resume (struct target_ops *ops,
ptid_t ptid, int step, enum gdb_signal signo)
{
int signal_to_pass;
procfs_status status;
sigset_t *run_fault = (sigset_t *) (void *) &run.fault;
if (ptid_equal (inferior_ptid, null_ptid))
return;
procfs_set_thread (ptid_equal (ptid, minus_one_ptid) ? inferior_ptid :
ptid);
run.flags = _DEBUG_RUN_FAULT | _DEBUG_RUN_TRACE;
if (step)
run.flags |= _DEBUG_RUN_STEP;
sigemptyset (run_fault);
sigaddset (run_fault, FLTBPT);
sigaddset (run_fault, FLTTRACE);
sigaddset (run_fault, FLTILL);
sigaddset (run_fault, FLTPRIV);
sigaddset (run_fault, FLTBOUNDS);
sigaddset (run_fault, FLTIOVF);
sigaddset (run_fault, FLTIZDIV);
sigaddset (run_fault, FLTFPE);
/* Peter V will be changing this at some point. */
sigaddset (run_fault, FLTPAGE);
run.flags |= _DEBUG_RUN_ARM;
signal_to_pass = gdb_signal_to_host (signo);
if (signal_to_pass)
{
devctl (ctl_fd, DCMD_PROC_STATUS, &status, sizeof (status), 0);
signal_to_pass = gdb_signal_to_host (signo);
if (status.why & (_DEBUG_WHY_SIGNALLED | _DEBUG_WHY_FAULTED))
{
if (signal_to_pass != status.info.si_signo)
{
SignalKill (nto_node (), ptid_get_pid (inferior_ptid), 0,
signal_to_pass, 0, 0);
run.flags |= _DEBUG_RUN_CLRFLT | _DEBUG_RUN_CLRSIG;
}
else /* Let it kill the program without telling us. */
sigdelset (&run.trace, signal_to_pass);
}
}
else
run.flags |= _DEBUG_RUN_CLRSIG | _DEBUG_RUN_CLRFLT;
errno = devctl (ctl_fd, DCMD_PROC_RUN, &run, sizeof (run), 0);
if (errno != EOK)
{
perror (_("run error!\n"));
return;
}
}
static void
procfs_mourn_inferior (struct target_ops *ops)
{
if (!ptid_equal (inferior_ptid, null_ptid))
{
SignalKill (nto_node (), ptid_get_pid (inferior_ptid), 0, SIGKILL, 0, 0);
close (ctl_fd);
}
inferior_ptid = null_ptid;
init_thread_list ();
inf_child_mourn_inferior (ops);
}
/* This function breaks up an argument string into an argument
vector suitable for passing to execvp().
E.g., on "run a b c d" this routine would get as input
the string "a b c d", and as output it would fill in argv with
the four arguments "a", "b", "c", "d". The only additional
functionality is simple quoting. The gdb command:
run a "b c d" f
will fill in argv with the three args "a", "b c d", "e". */
static void
breakup_args (char *scratch, char **argv)
{
char *pp, *cp = scratch;
char quoting = 0;
for (;;)
{
/* Scan past leading separators. */
quoting = 0;
while (*cp == ' ' || *cp == '\t' || *cp == '\n')
cp++;
/* Break if at end of string. */
if (*cp == '\0')
break;
/* Take an arg. */
if (*cp == '"')
{
cp++;
quoting = strchr (cp, '"') ? 1 : 0;
}
*argv++ = cp;
/* Scan for next arg separator. */
pp = cp;
if (quoting)
cp = strchr (pp, '"');
if ((cp == NULL) || (!quoting))
cp = strchr (pp, ' ');
if (cp == NULL)
cp = strchr (pp, '\t');
if (cp == NULL)
cp = strchr (pp, '\n');
/* No separators => end of string => break. */
if (cp == NULL)
{
pp = cp;
break;
}
/* Replace the separator with a terminator. */
*cp++ = '\0';
}
/* Execv requires a null-terminated arg vector. */
*argv = NULL;
}
static void
procfs_create_inferior (struct target_ops *ops, const char *exec_file,
const std::string &allargs,
char **env, int from_tty)
{
struct inheritance inherit;
pid_t pid;
int flags, errn;
char **argv, *args;
const char *in = "", *out = "", *err = "";
int fd, fds[3];
sigset_t set;
const char *inferior_io_terminal = get_inferior_io_terminal ();
struct inferior *inf;
argv = xmalloc ((allargs.size () / (unsigned) 2 + 2) *
sizeof (*argv));
argv[0] = get_exec_file (1);
if (!argv[0])
{
if (exec_file)
argv[0] = exec_file;
else
return;
}
args = xstrdup (allargs.c_str ());
breakup_args (args, (exec_file != NULL) ? &argv[1] : &argv[0]);
argv = nto_parse_redirection (argv, &in, &out, &err);
fds[0] = STDIN_FILENO;
fds[1] = STDOUT_FILENO;
fds[2] = STDERR_FILENO;
/* If the user specified I/O via gdb's --tty= arg, use it, but only
if the i/o is not also being specified via redirection. */
if (inferior_io_terminal)
{
if (!in[0])
in = inferior_io_terminal;
if (!out[0])
out = inferior_io_terminal;
if (!err[0])
err = inferior_io_terminal;
}
if (in[0])
{
fd = open (in, O_RDONLY);
if (fd == -1)
perror (in);
else
fds[0] = fd;
}
if (out[0])
{
fd = open (out, O_WRONLY);
if (fd == -1)
perror (out);
else
fds[1] = fd;
}
if (err[0])
{
fd = open (err, O_WRONLY);
if (fd == -1)
perror (err);
else
fds[2] = fd;
}
/* Clear any pending SIGUSR1's but keep the behavior the same. */
signal (SIGUSR1, signal (SIGUSR1, SIG_IGN));
sigemptyset (&set);
sigaddset (&set, SIGUSR1);
sigprocmask (SIG_UNBLOCK, &set, NULL);
memset (&inherit, 0, sizeof (inherit));
if (ND_NODE_CMP (nto_procfs_node, ND_LOCAL_NODE) != 0)
{
inherit.nd = nto_node ();
inherit.flags |= SPAWN_SETND;
inherit.flags &= ~SPAWN_EXEC;
}
inherit.flags |= SPAWN_SETGROUP | SPAWN_HOLD;
inherit.pgroup = SPAWN_NEWPGROUP;
pid = spawnp (argv[0], 3, fds, &inherit, argv,
ND_NODE_CMP (nto_procfs_node, ND_LOCAL_NODE) == 0 ? env : 0);
xfree (args);
sigprocmask (SIG_BLOCK, &set, NULL);
if (pid == -1)
error (_("Error spawning %s: %d (%s)"), argv[0], errno,
safe_strerror (errno));
if (fds[0] != STDIN_FILENO)
close (fds[0]);
if (fds[1] != STDOUT_FILENO)
close (fds[1]);
if (fds[2] != STDERR_FILENO)
close (fds[2]);
inferior_ptid = do_attach (pid_to_ptid (pid));
procfs_update_thread_list (ops);
inf = current_inferior ();
inferior_appeared (inf, pid);
inf->attach_flag = 0;
flags = _DEBUG_FLAG_KLC; /* Kill-on-Last-Close flag. */
errn = devctl (ctl_fd, DCMD_PROC_SET_FLAG, &flags, sizeof (flags), 0);
if (errn != EOK)
{
/* FIXME: expected warning? */
/* warning( "Failed to set Kill-on-Last-Close flag: errno = %d(%s)\n",
errn, strerror(errn) ); */
}
if (!target_is_pushed (ops))
push_target (ops);
target_terminal_init ();
if (exec_bfd != NULL
|| (symfile_objfile != NULL && symfile_objfile->obfd != NULL))
solib_create_inferior_hook (0);
}
static void
procfs_interrupt (struct target_ops *self, ptid_t ptid)
{
devctl (ctl_fd, DCMD_PROC_STOP, NULL, 0, 0);
}
static void
procfs_kill_inferior (struct target_ops *ops)
{
target_mourn_inferior (inferior_ptid);
}
/* Fill buf with regset and return devctl cmd to do the setting. Return
-1 if we fail to get the regset. Store size of regset in regsize. */
static int
get_regset (int regset, char *buf, int bufsize, int *regsize)
{
int dev_get, dev_set;
switch (regset)
{
case NTO_REG_GENERAL:
dev_get = DCMD_PROC_GETGREG;
dev_set = DCMD_PROC_SETGREG;
break;
case NTO_REG_FLOAT:
dev_get = DCMD_PROC_GETFPREG;
dev_set = DCMD_PROC_SETFPREG;
break;
case NTO_REG_ALT:
dev_get = DCMD_PROC_GETALTREG;
dev_set = DCMD_PROC_SETALTREG;
break;
case NTO_REG_SYSTEM:
default:
return -1;
}
if (devctl (ctl_fd, dev_get, buf, bufsize, regsize) != EOK)
return -1;
return dev_set;
}
static void
procfs_store_registers (struct target_ops *ops,
struct regcache *regcache, int regno)
{
union
{
procfs_greg greg;
procfs_fpreg fpreg;
procfs_altreg altreg;
}
reg;
unsigned off;
int len, regset, regsize, dev_set, err;
char *data;
ptid_t ptid = regcache_get_ptid (regcache);
if (ptid_equal (ptid, null_ptid))
return;
procfs_set_thread (ptid);
if (regno == -1)
{
for (regset = NTO_REG_GENERAL; regset < NTO_REG_END; regset++)
{
dev_set = get_regset (regset, (char *) ®,
sizeof (reg), ®size);
if (dev_set == -1)
continue;
if (nto_regset_fill (regcache, regset, (char *) ®) == -1)
continue;
err = devctl (ctl_fd, dev_set, ®, regsize, 0);
if (err != EOK)
fprintf_unfiltered (gdb_stderr,
"Warning unable to write regset %d: %s\n",
regno, safe_strerror (err));
}
}
else
{
regset = nto_regset_id (regno);
if (regset == -1)
return;
dev_set = get_regset (regset, (char *) ®, sizeof (reg), ®size);
if (dev_set == -1)
return;
len = nto_register_area (get_regcache_arch (regcache),
regno, regset, &off);
if (len < 1)
return;
regcache_raw_collect (regcache, regno, (char *) ® + off);
err = devctl (ctl_fd, dev_set, ®, regsize, 0);
if (err != EOK)
fprintf_unfiltered (gdb_stderr,
"Warning unable to write regset %d: %s\n", regno,
safe_strerror (err));
}
}
/* Set list of signals to be handled in the target. */
static void
procfs_pass_signals (struct target_ops *self,
int numsigs, unsigned char *pass_signals)
{
int signo;
sigfillset (&run.trace);
for (signo = 1; signo < NSIG; signo++)
{
int target_signo = gdb_signal_from_host (signo);
if (target_signo < numsigs && pass_signals[target_signo])
sigdelset (&run.trace, signo);
}
}
static char *
procfs_pid_to_str (struct target_ops *ops, ptid_t ptid)
{
static char buf[1024];
int pid, tid, n;
struct tidinfo *tip;
pid = ptid_get_pid (ptid);
tid = ptid_get_tid (ptid);
n = snprintf (buf, 1023, "process %d", pid);
#if 0 /* NYI */
tip = procfs_thread_info (pid, tid);
if (tip != NULL)
snprintf (&buf[n], 1023, " (state = 0x%02x)", tip->state);
#endif
return buf;
}
/* to_can_run implementation for "target procfs". Note this really
means "can this target be the default run target", which there can
be only one, and we make it be "target native" like other ports.
"target procfs <node>" wouldn't make sense as default run target, as
it needs <node>. */
static int
procfs_can_run (struct target_ops *self)
{
return 0;
}
/* "target procfs". */
static struct target_ops nto_procfs_ops;
/* "target native". */
static struct target_ops *nto_native_ops;
/* to_open implementation for "target procfs". */
static void
procfs_open (const char *arg, int from_tty)
{
procfs_open_1 (&nto_procfs_ops, arg, from_tty);
}
/* to_open implementation for "target native". */
static void
procfs_native_open (const char *arg, int from_tty)
{
procfs_open_1 (nto_native_ops, arg, from_tty);
}
/* Create the "native" and "procfs" targets. */
static void
init_procfs_targets (void)
{
struct target_ops *t = inf_child_target ();
/* Leave to_shortname as "native". */
t->to_longname = "QNX Neutrino local process";
t->to_doc = "QNX Neutrino local process (started by the \"run\" command).";
t->to_open = procfs_native_open;
t->to_attach = procfs_attach;
t->to_post_attach = procfs_post_attach;
t->to_detach = procfs_detach;
t->to_resume = procfs_resume;
t->to_wait = procfs_wait;
t->to_fetch_registers = procfs_fetch_registers;
t->to_store_registers = procfs_store_registers;
t->to_xfer_partial = procfs_xfer_partial;
t->to_files_info = procfs_files_info;
t->to_insert_breakpoint = procfs_insert_breakpoint;
t->to_remove_breakpoint = procfs_remove_breakpoint;
t->to_can_use_hw_breakpoint = procfs_can_use_hw_breakpoint;
t->to_insert_hw_breakpoint = procfs_insert_hw_breakpoint;
t->to_remove_hw_breakpoint = procfs_remove_hw_breakpoint;
t->to_insert_watchpoint = procfs_insert_hw_watchpoint;
t->to_remove_watchpoint = procfs_remove_hw_watchpoint;
t->to_stopped_by_watchpoint = procfs_stopped_by_watchpoint;
t->to_kill = procfs_kill_inferior;
t->to_create_inferior = procfs_create_inferior;
t->to_mourn_inferior = procfs_mourn_inferior;
t->to_pass_signals = procfs_pass_signals;
t->to_thread_alive = procfs_thread_alive;
t->to_update_thread_list = procfs_update_thread_list;
t->to_pid_to_str = procfs_pid_to_str;
t->to_interrupt = procfs_interrupt;
t->to_have_continuable_watchpoint = 1;
t->to_extra_thread_info = nto_extra_thread_info;
t->to_pid_to_exec_file = procfs_pid_to_exec_file;
nto_native_ops = t;
/* Register "target native". This is the default run target. */
add_target (t);
/* Register "target procfs <node>". */
nto_procfs_ops = *t;
nto_procfs_ops.to_shortname = "procfs";
nto_procfs_ops.to_can_run = procfs_can_run;
t->to_longname = "QNX Neutrino local or remote process";
t->to_doc = "QNX Neutrino process. target procfs <node>";
t->to_open = procfs_open;
add_target (&nto_procfs_ops);
}
#define OSTYPE_NTO 1
extern initialize_file_ftype _initialize_procfs;
void
_initialize_procfs (void)
{
sigset_t set;
init_procfs_targets ();
/* We use SIGUSR1 to gain control after we block waiting for a process.
We use sigwaitevent to wait. */
sigemptyset (&set);
sigaddset (&set, SIGUSR1);
sigprocmask (SIG_BLOCK, &set, NULL);
/* Initially, make sure all signals are reported. */
sigfillset (&run.trace);
/* Stuff some information. */
nto_cpuinfo_flags = SYSPAGE_ENTRY (cpuinfo)->flags;
nto_cpuinfo_valid = 1;
add_info ("pidlist", procfs_pidlist, _("pidlist"));
add_info ("meminfo", procfs_meminfo, _("memory information"));
nto_is_nto_target = procfs_is_nto_target;
}
static int
procfs_hw_watchpoint (int addr, int len, enum target_hw_bp_type type)
{
procfs_break brk;
switch (type)
{
case hw_read:
brk.type = _DEBUG_BREAK_RD;
break;
case hw_access:
brk.type = _DEBUG_BREAK_RW;
break;
default: /* Modify. */
/* FIXME: brk.type = _DEBUG_BREAK_RWM gives EINVAL for some reason. */
brk.type = _DEBUG_BREAK_RW;
}
brk.type |= _DEBUG_BREAK_HW; /* Always ask for HW. */
brk.addr = addr;
brk.size = len;
errno = devctl (ctl_fd, DCMD_PROC_BREAK, &brk, sizeof (brk), 0);
if (errno != EOK)
{
perror (_("Failed to set hardware watchpoint"));
return -1;
}
return 0;
}
static int
procfs_can_use_hw_breakpoint (struct target_ops *self,
enum bptype type,
int cnt, int othertype)
{
return 1;
}
static int
procfs_remove_hw_watchpoint (struct target_ops *self,
CORE_ADDR addr, int len,
enum target_hw_bp_type type,
struct expression *cond)
{
return procfs_hw_watchpoint (addr, -1, type);
}
static int
procfs_insert_hw_watchpoint (struct target_ops *self,
CORE_ADDR addr, int len,
enum target_hw_bp_type type,
struct expression *cond)
{
return procfs_hw_watchpoint (addr, len, type);
}
static int
procfs_stopped_by_watchpoint (struct target_ops *ops)
{
/* NOTE: nto_stopped_by_watchpoint will be called ONLY while we are
stopped due to a SIGTRAP. This assumes gdb works in 'all-stop' mode;
future gdb versions will likely run in 'non-stop' mode in which case
we will have to store/examine statuses per thread in question.
Until then, this will work fine. */
struct inferior *inf = current_inferior ();
struct nto_inferior_data *inf_data;
gdb_assert (inf != NULL);
inf_data = nto_inferior_data (inf);
return inf_data->stopped_flags
& (_DEBUG_FLAG_TRACE_RD
| _DEBUG_FLAG_TRACE_WR
| _DEBUG_FLAG_TRACE_MODIFY);
}
| totalspectrum/binutils-propeller | gdb/nto-procfs.c | C | gpl-2.0 | 42,966 | [
30522,
1013,
1008,
3698,
2981,
2490,
2005,
1053,
26807,
11265,
4904,
17815,
1013,
4013,
2278,
1006,
2832,
5371,
2291,
1007,
2005,
1043,
18939,
1012,
2517,
2011,
6972,
17754,
2012,
1053,
26807,
4007,
3001,
3132,
1012,
9385,
1006,
1039,
1007,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# Panax glabratus Kunth SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Apiales/Araliaceae/Schefflera/Schefflera glabrata/ Syn. Panax glabratus/README.md | Markdown | apache-2.0 | 178 | [
30522,
1001,
6090,
8528,
1043,
20470,
8609,
2271,
28919,
2705,
2427,
1001,
1001,
1001,
1001,
3570,
10675,
1001,
1001,
1001,
1001,
2429,
2000,
1996,
10161,
1997,
2166,
1010,
3822,
2254,
2249,
1001,
1001,
1001,
1001,
2405,
1999,
19701,
1001,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
@extends('admin.layout')
@section('title')
Payment
@endsection
@section('content')
<a href="/admin/ff/payment/create/{{$pledge->id}}" class="ui teal button right floated">New Payment</a>
<h1 class="ui header">Payments</h1>
<div class="ui horizontal divider">{{$pledge->name}}'s <br> Summary </div>
<table class="ui unstackable table">
<thead>
<tr>
<th class="center aligned"> {{trans('futurefund.total_pledge')}} </th>
<th class="center aligned"> {{trans('futurefund.collected')}} </th>
<th class="center aligned"> {{trans('futurefund.balance')}} </th>
</tr>
</thead>
<tr>
<td class="center aligned">RM {{number_format($pledge->amount, 2)}}</td>
<td class="center aligned">RM {{number_format($pledge_collected, 2)}}</td>
<td class="center aligned">RM {{number_format(($pledge->amount - $pledge_collected), 2)}}</td>
</tr>
</table>
<div class="ui horizontal divider">{{$pledge->name}}'s <br> Payments </div>
<div class="ui segment">
{!! Form::select('is_cleared', ['0' => 'Not cleared', '1' => 'Cleared', 'all' => 'All'], $filter['is_cleared'], ['class' => 'ui dropdown']) !!}
{!! Form::select('is_cancelled', ['0' => 'Not cancelled', '1' => 'Cancelled', 'all' => 'All'], $filter['is_cancelled'], ['class' => 'ui dropdown']) !!}
<div class="clearfix field">
<a href="{{ url()->current() }}" class="ui basic right floated right labeled icon tiny button">
Reset <i class="undo icon"></i>
</a>
<button class="ui teal right floated right labeled icon tiny button">
Filter <i class="filter icon"></i>
</button>
</div>
<div class="ui hidden divider"></div>
{!! Form::close() !!}
</div>
<table class="ui very compact unstackable table">
<thead>
<tr>
<th >{!! sort_by('id', 'ID' ) !!}</th>
<th class="three wide">Amount</th>
<th >Status</th>
<th >Created at</th>
<th >Actions</th>
</tr>
</thead>
<tbody>
@forelse ($payments as $payment)
<tr>
<td>
<h5 class="ui header">
{{ prefix()->wrap($payment) }}
</h5>
</td>
<td>
<h5 class="ui header">
RM {{ $payment->amount }}
@if ($payment->remarks)
<div class="sub uppercased header">{{ $payment->remarks }}</div>
@endif
</h5>
</td>
<td>
<div>
@if ($payment->is_cancelled)
<div class="ui grey label">cancelled</div>
@else
@if ($payment->is_cleared)
<div class="ui green label">cleared</div>
@else
<div class="ui orange label">pending</div>
@endif
@endif
</div>
</td>
<td>
{{ $payment->created_at->format('Y-m-d') }}
<div>{{ $payment->created_at->format('h:i a') }}</div>
</td>
<td>
<div class="ui small icon buttons">
<a href="/admin/ff/payment/update/{{$payment->id}}" class="ui button">
<i class="pencil icon"></i>
</a>
</div>
</td>
</tr>
@empty
<tr>
<td colspan="5"> No payment record yet, change filter or come back later </td>
</tr>
@endforelse
</tbody>
</table>
@endsection
| yilliot/souls | resources/views/admin/ff/payment_index.blade.php | PHP | mit | 3,322 | [
30522,
1030,
8908,
1006,
1005,
4748,
10020,
1012,
9621,
1005,
1007,
1030,
2930,
1006,
1005,
2516,
1005,
1007,
7909,
1030,
4515,
18491,
1030,
2930,
1006,
1005,
4180,
1005,
1007,
1026,
1037,
17850,
12879,
1027,
1000,
1013,
4748,
10020,
1013,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
using System;
namespace Server.Items
{
public class ArachnidDoom : BaseInstrument
{
[Constructable]
public ArachnidDoom()
: base(0x0EB3)
{
RandomInstrument();
this.Hue = 1944;
this.Weight = 4;
this.Slayer = SlayerName.ArachnidDoom;
}
public ArachnidDoom(Serial serial)
: base(serial)
{
}
public override int LabelNumber
{
get
{
return 1154724;
}
}// Arachnid Doom
public override int InitMinUses
{
get
{
return 450;
}
}
public override int InitMaxUses
{
get
{
return 450;
}
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
} | tbewley10310/Land-of-Archon | Scripts/Services/CleanUpBritannia/Items/ArachnidDoom.cs | C# | gpl-2.0 | 1,190 | [
30522,
2478,
2291,
1025,
3415,
15327,
8241,
1012,
5167,
1063,
2270,
2465,
19027,
2818,
3490,
14141,
17650,
1024,
2918,
7076,
24456,
4765,
1063,
1031,
9570,
3085,
1033,
2270,
19027,
2818,
3490,
14141,
17650,
1006,
1007,
1024,
2918,
1006,
101... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
function serialize (o)
if type(o) == "number" then
io.write(o)
elseif type(o) == "string" then
io.write(string.format("%q",o)) --good choose
elseif type(o) == "table" then
io.write("{\n")
for k,v in pairs(o) do
-- io.write(" ",k," = ")
io.write(" [")
serialize(k)
io.write("] = ")
serialize(v)
io.write(",\n")
end
io.write("}\n")
else
error("cannot serialize a " .. type(o))
end
end
serialize{a=12,b='Lua',key='another "one"'}
| giftman/Gifts | Lua/moveit/tableSaveWithoutLoop.lua | Lua | apache-2.0 | 572 | [
30522,
3853,
7642,
4697,
1006,
1051,
1007,
2065,
2828,
1006,
1051,
1007,
1027,
1027,
1000,
2193,
1000,
2059,
22834,
1012,
4339,
1006,
1051,
1007,
2842,
10128,
2828,
1006,
1051,
1007,
1027,
1027,
1000,
5164,
1000,
2059,
22834,
1012,
4339,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// Copyright © 2014 John Watson
// Licensed under the terms of the MIT License
var GameState = function(game) {
};
// Load images and sounds
GameState.prototype.preload = function() {
this.game.load.image('ground', 'assets/gfx/ground.png');
this.game.load.image('player', 'assets/gfx/player.png');
};
// Setup the example
GameState.prototype.create = function() {
// Set stage background to something sky colored
this.game.stage.backgroundColor = 0x4488cc;
// Define movement constants
this.MAX_SPEED = 500; // pixels/second
// Create a player sprite
this.player = this.game.add.sprite(this.game.width/2, this.game.height - 64, 'player');
// Enable physics on the player
this.game.physics.enable(this.player, Phaser.Physics.ARCADE);
// Make player collide with world boundaries so he doesn't leave the stage
this.player.body.collideWorldBounds = true;
// Capture certain keys to prevent their default actions in the browser.
// This is only necessary because this is an HTML5 game. Games on other
// platforms may not need code like this.
this.game.input.keyboard.addKeyCapture([
Phaser.Keyboard.LEFT,
Phaser.Keyboard.RIGHT,
Phaser.Keyboard.UP,
Phaser.Keyboard.DOWN
]);
// Create some ground for the player to walk on
this.ground = this.game.add.group();
for(var x = 0; x < this.game.width; x += 32) {
// Add the ground blocks, enable physics on each, make them immovable
var groundBlock = this.game.add.sprite(x, this.game.height - 32, 'ground');
this.game.physics.enable(groundBlock, Phaser.Physics.ARCADE);
groundBlock.body.immovable = true;
groundBlock.body.allowGravity = false;
this.ground.add(groundBlock);
}
};
// The update() method is called every frame
GameState.prototype.update = function() {
// Collide the player with the ground
this.game.physics.arcade.collide(this.player, this.ground);
if (this.leftInputIsActive()) {
// If the LEFT key is down, set the player velocity to move left
this.player.body.velocity.x = -this.MAX_SPEED;
} else if (this.rightInputIsActive()) {
// If the RIGHT key is down, set the player velocity to move right
this.player.body.velocity.x = this.MAX_SPEED;
} else {
// Stop the player from moving horizontally
this.player.body.velocity.x = 0;
}
};
// This function should return true when the player activates the "go left" control
// In this case, either holding the right arrow or tapping or clicking on the left
// side of the screen.
GameState.prototype.leftInputIsActive = function() {
var isActive = false;
isActive = this.input.keyboard.isDown(Phaser.Keyboard.LEFT);
isActive |= (this.game.input.activePointer.isDown &&
this.game.input.activePointer.x < this.game.width/4);
return isActive;
};
// This function should return true when the player activates the "go right" control
// In this case, either holding the right arrow or tapping or clicking on the right
// side of the screen.
GameState.prototype.rightInputIsActive = function() {
var isActive = false;
isActive = this.input.keyboard.isDown(Phaser.Keyboard.RIGHT);
isActive |= (this.game.input.activePointer.isDown &&
this.game.input.activePointer.x > this.game.width/2 + this.game.width/4);
return isActive;
};
var game = new Phaser.Game(640, 320, Phaser.AUTO, 'game');
game.state.add('game', GameState, true);
| boniatillo-com/PhaserEditor | source/phasereditor/phasereditor.resources.templates/templates/Game Mechanic Explorer/01 - Mechanic - Walking and jumping - Basic walking/WebContent/ex-walking-01.js | JavaScript | epl-1.0 | 3,525 | [
30522,
1013,
1013,
9385,
1075,
2297,
2198,
7908,
1013,
1013,
7000,
2104,
1996,
3408,
1997,
1996,
10210,
6105,
13075,
2399,
12259,
1027,
3853,
1006,
2208,
1007,
1063,
1065,
1025,
1013,
1013,
7170,
4871,
1998,
4165,
2399,
12259,
1012,
8773,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
Housey - Split Testing Library
=============================
Introduction
------------
This library started as a port of
[A/Bingo](http://www.bingocardcreator.com/abingo/), which is targetted at Ruby
on Rails to straight up PHP. Like my other Open Source efforts, I was hoping to
create a library that was framework agnostic, so it it's ended up a little messy
and does require a little bit of work to get going.
Storage
-------
Housey uses two kinds of storage. The first we'll refer to as the persistent
storage, the second the cache. Given the way the cache is used, you may actually
want to use a persistant storage engine (such as memcachedb), as described on
the [A/Bingo website](http://www.bingocardcreator.com/abingo/installation).
Usage
-----
See the behat files until I get some documentation, everything under `features/`
Copyright
---------
Copyright (c) 2012 Dave Marshall. See LICENCE for further details
| davedevelopment/housey | README.md | Markdown | mit | 929 | [
30522,
2160,
2100,
1011,
3975,
5604,
3075,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
4955,
1011,
1011,
101... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
//
// AudioComponent.h
// VideoEditor2
//
// Created by Sukrit Sunama on 1/31/56 BE.
// Copyright (c) 2556 Afternoon Tea Break. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
@class VEAudioComposition;
@interface VEAudioComponent : NSObject {
VEAudioComposition *composition;
AVAssetReader *reader;
AVAssetReaderTrackOutput *readerOutput;
double presentTime;
double duration;
}
@property (nonatomic, strong) VEAudioComposition *composition;
@property double presentTime;
@property double duration;
- (id)initWithURL:(NSURL *)url;
- (id)initWithPath:(NSString *)path;
- (void)beginExport;
- (CMSampleBufferRef)nextSampleBuffer;
@end
| Sunama/VEVideoEditor | VideoEditor/Model/Component/VEAudioComponent.h | C | mit | 723 | [
30522,
1013,
1013,
1013,
1013,
5746,
9006,
29513,
3372,
1012,
1044,
1013,
1013,
2678,
2098,
15660,
2475,
1013,
1013,
1013,
1013,
2580,
2011,
10514,
21638,
4183,
3103,
8067,
2006,
1015,
1013,
2861,
1013,
5179,
2022,
1012,
1013,
1013,
9385,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
namespace app\controllers;
use Yii;
use app\models\User;
use app\models\UserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
use yii\filters\VerbFilter;
use yii\db\IntegrityException;
/**
* UserController implements the CRUD actions for User model.
*/
class UserController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
/**
* Displays a single User model.
* @param integer $id
* @return mixed
*/
public function actionView()
{
$model = new User();
$id = Yii::$app->request->post('id');
if(!$id){
$this->autorizaUsuario($id);
$id = Yii::$app->user->identity->idusuario;
//$model = User::findByEmail(Yii::$app->user->identity->email);
}
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new User model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
if(!Yii::$app->user->isGuest)
$this->redirect(['evento/index']);
$model = new User();
if ($model->load(Yii::$app->request->post())) {
if($model->save()){
$this->mensagens('success', 'Cadastro realizado', 'Cadastro efetuado com Sucesso');
return $this->redirect(['site/login']);
}else{
return $this->render('create', [
'model' => $model,
]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing User model.
* If update is successful, the browser will be redirected to the 'view' page.
*
* @param integer $id
* @return mixed
*/
public function actionUpdate($id) {
$this->autorizaUsuario ( $id );
$model = $this->findModel ( $id );
if(Yii::$app->user->identity->idusuario === $model->idusuario){
echo $model->senha."senha";
if ($model->load ( Yii::$app->request->post () ) ) {
//$model->senha = md5($model->senha);
if($model->save(false)){
return $this->redirect ( ['view', 'id' => $model->idusuario]);
}
} else {
return $this->render('update', [
'model' => $model,
]);
}
}else{
return $this->goBack();
}
}
/**
* Deletes an existing User model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id){
$this->autorizaUsuario($id);
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the User model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return User the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = User::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('A página solicitada não foi encontrada.');
}
}
protected function autorizaUsuario($id){
if(Yii::$app->user->isGuest){
$this->redirect(['site/login']);
}
}
/*Tipo: success, danger, warning*/
protected function mensagens($tipo, $titulo, $mensagem){
Yii::$app->session->setFlash($tipo, [
'type' => $tipo,
'duration' => 1200,
'icon' => 'home',
'message' => $mensagem,
'title' => $titulo,
'positonY' => 'bottom',
'positonX' => 'right'
]);
}
}
| schw/SGE3 | controllers/UserController.php | PHP | bsd-3-clause | 4,140 | [
30522,
1026,
1029,
25718,
3415,
15327,
10439,
1032,
21257,
1025,
2224,
12316,
2072,
1025,
2224,
10439,
1032,
4275,
1032,
5310,
1025,
2224,
10439,
1032,
4275,
1032,
5198,
14644,
2818,
1025,
2224,
12316,
2072,
1032,
4773,
1032,
11486,
1025,
2... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/* Copyright 2019 The TensorFlow 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.
==============================================================================*/
#include "tensorflow/lite/experimental/micro/examples/micro_speech/command_responder.h"
#include "am_bsp.h" // NOLINT
// This implementation will light up the LEDs on the board in response to
// different commands.
void RespondToCommand(tflite::ErrorReporter* error_reporter,
int32_t current_time, const char* found_command,
uint8_t score, bool is_new_command) {
static bool is_initialized = false;
if (!is_initialized) {
// Setup LED's as outputs
am_hal_gpio_pinconfig(AM_BSP_GPIO_LED_RED, g_AM_HAL_GPIO_OUTPUT_12);
am_hal_gpio_pinconfig(AM_BSP_GPIO_LED_BLUE, g_AM_HAL_GPIO_OUTPUT_12);
am_hal_gpio_pinconfig(AM_BSP_GPIO_LED_GREEN, g_AM_HAL_GPIO_OUTPUT_12);
am_hal_gpio_pinconfig(AM_BSP_GPIO_LED_YELLOW, g_AM_HAL_GPIO_OUTPUT_12);
is_initialized = true;
}
static int count = 0;
// Toggle the blue LED every time an inference is performed.
++count;
if (count & 1) {
am_hal_gpio_output_set(AM_BSP_GPIO_LED_BLUE);
} else {
am_hal_gpio_output_clear(AM_BSP_GPIO_LED_BLUE);
}
// Turn on the yellow LED if 'yes' was heard.
am_hal_gpio_output_clear(AM_BSP_GPIO_LED_RED);
am_hal_gpio_output_clear(AM_BSP_GPIO_LED_YELLOW);
am_hal_gpio_output_clear(AM_BSP_GPIO_LED_GREEN);
if (is_new_command) {
error_reporter->Report("Heard %s (%d) @%dms", found_command, score,
current_time);
if (found_command[0] == 'y') {
am_hal_gpio_output_set(AM_BSP_GPIO_LED_YELLOW);
}
if (found_command[0] == 'n') {
am_hal_gpio_output_set(AM_BSP_GPIO_LED_RED);
}
if (found_command[0] == 'u') {
am_hal_gpio_output_set(AM_BSP_GPIO_LED_GREEN);
}
}
}
| ghchinoy/tensorflow | tensorflow/lite/experimental/micro/examples/micro_speech/sparkfun_edge/command_responder.cc | C++ | apache-2.0 | 2,363 | [
30522,
1013,
1008,
9385,
10476,
1996,
23435,
12314,
6048,
1012,
2035,
2916,
9235,
1012,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
1012,
1014,
1006,
1996,
1000,
6105,
1000,
1007,
1025,
2017,
2089,
2025,
2224,
2023,
5371,
3272,
1999,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/video/capture/win/video_capture_device_win.h"
#include <ks.h>
#include <ksmedia.h>
#include <algorithm>
#include <list>
#include "base/strings/sys_string_conversions.h"
#include "base/win/scoped_co_mem.h"
#include "base/win/scoped_variant.h"
#include "media/video/capture/win/video_capture_device_mf_win.h"
using base::win::ScopedCoMem;
using base::win::ScopedComPtr;
using base::win::ScopedVariant;
namespace media {
// Finds and creates a DirectShow Video Capture filter matching the device_name.
// static
HRESULT VideoCaptureDeviceWin::GetDeviceFilter(
const VideoCaptureDevice::Name& device_name,
IBaseFilter** filter) {
DCHECK(filter);
ScopedComPtr<ICreateDevEnum> dev_enum;
HRESULT hr = dev_enum.CreateInstance(CLSID_SystemDeviceEnum, NULL,
CLSCTX_INPROC);
if (FAILED(hr))
return hr;
ScopedComPtr<IEnumMoniker> enum_moniker;
hr = dev_enum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory,
enum_moniker.Receive(), 0);
// CreateClassEnumerator returns S_FALSE on some Windows OS
// when no camera exist. Therefore the FAILED macro can't be used.
if (hr != S_OK)
return NULL;
ScopedComPtr<IMoniker> moniker;
ScopedComPtr<IBaseFilter> capture_filter;
DWORD fetched = 0;
while (enum_moniker->Next(1, moniker.Receive(), &fetched) == S_OK) {
ScopedComPtr<IPropertyBag> prop_bag;
hr = moniker->BindToStorage(0, 0, IID_IPropertyBag, prop_bag.ReceiveVoid());
if (FAILED(hr)) {
moniker.Release();
continue;
}
// Find the description or friendly name.
static const wchar_t* kPropertyNames[] = {
L"DevicePath", L"Description", L"FriendlyName"
};
ScopedVariant name;
for (size_t i = 0;
i < arraysize(kPropertyNames) && name.type() != VT_BSTR; ++i) {
prop_bag->Read(kPropertyNames[i], name.Receive(), 0);
}
if (name.type() == VT_BSTR) {
std::string device_path(base::SysWideToUTF8(V_BSTR(&name)));
if (device_path.compare(device_name.id()) == 0) {
// We have found the requested device
hr = moniker->BindToObject(0, 0, IID_IBaseFilter,
capture_filter.ReceiveVoid());
DVPLOG_IF(2, FAILED(hr)) << "Failed to bind camera filter.";
break;
}
}
moniker.Release();
}
*filter = capture_filter.Detach();
if (!*filter && SUCCEEDED(hr))
hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
return hr;
}
// Check if a Pin matches a category.
// static
bool VideoCaptureDeviceWin::PinMatchesCategory(IPin* pin, REFGUID category) {
DCHECK(pin);
bool found = false;
ScopedComPtr<IKsPropertySet> ks_property;
HRESULT hr = ks_property.QueryFrom(pin);
if (SUCCEEDED(hr)) {
GUID pin_category;
DWORD return_value;
hr = ks_property->Get(AMPROPSETID_Pin, AMPROPERTY_PIN_CATEGORY, NULL, 0,
&pin_category, sizeof(pin_category), &return_value);
if (SUCCEEDED(hr) && (return_value == sizeof(pin_category))) {
found = (pin_category == category);
}
}
return found;
}
// Finds a IPin on a IBaseFilter given the direction an category.
// static
ScopedComPtr<IPin> VideoCaptureDeviceWin::GetPin(IBaseFilter* filter,
PIN_DIRECTION pin_dir,
REFGUID category) {
ScopedComPtr<IPin> pin;
ScopedComPtr<IEnumPins> pin_emum;
HRESULT hr = filter->EnumPins(pin_emum.Receive());
if (pin_emum == NULL)
return pin;
// Get first unconnected pin.
hr = pin_emum->Reset(); // set to first pin
while ((hr = pin_emum->Next(1, pin.Receive(), NULL)) == S_OK) {
PIN_DIRECTION this_pin_dir = static_cast<PIN_DIRECTION>(-1);
hr = pin->QueryDirection(&this_pin_dir);
if (pin_dir == this_pin_dir) {
if (category == GUID_NULL || PinMatchesCategory(pin, category))
return pin;
}
pin.Release();
}
DCHECK(!pin);
return pin;
}
// static
VideoPixelFormat VideoCaptureDeviceWin::TranslateMediaSubtypeToPixelFormat(
const GUID& sub_type) {
static struct {
const GUID& sub_type;
VideoPixelFormat format;
} pixel_formats[] = {
{ kMediaSubTypeI420, PIXEL_FORMAT_I420 },
{ MEDIASUBTYPE_IYUV, PIXEL_FORMAT_I420 },
{ MEDIASUBTYPE_RGB24, PIXEL_FORMAT_RGB24 },
{ MEDIASUBTYPE_YUY2, PIXEL_FORMAT_YUY2 },
{ MEDIASUBTYPE_MJPG, PIXEL_FORMAT_MJPEG },
{ MEDIASUBTYPE_UYVY, PIXEL_FORMAT_UYVY },
{ MEDIASUBTYPE_ARGB32, PIXEL_FORMAT_ARGB },
{ kMediaSubTypeHDYC, PIXEL_FORMAT_UYVY },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(pixel_formats); ++i) {
if (sub_type == pixel_formats[i].sub_type)
return pixel_formats[i].format;
}
#ifndef NDEBUG
WCHAR guid_str[128];
StringFromGUID2(sub_type, guid_str, arraysize(guid_str));
DVLOG(2) << "Device (also) supports an unknown media type " << guid_str;
#endif
return PIXEL_FORMAT_UNKNOWN;
}
void VideoCaptureDeviceWin::ScopedMediaType::Free() {
if (!media_type_)
return;
DeleteMediaType(media_type_);
media_type_= NULL;
}
AM_MEDIA_TYPE** VideoCaptureDeviceWin::ScopedMediaType::Receive() {
DCHECK(!media_type_);
return &media_type_;
}
// Release the format block for a media type.
// http://msdn.microsoft.com/en-us/library/dd375432(VS.85).aspx
void VideoCaptureDeviceWin::ScopedMediaType::FreeMediaType(AM_MEDIA_TYPE* mt) {
if (mt->cbFormat != 0) {
CoTaskMemFree(mt->pbFormat);
mt->cbFormat = 0;
mt->pbFormat = NULL;
}
if (mt->pUnk != NULL) {
NOTREACHED();
// pUnk should not be used.
mt->pUnk->Release();
mt->pUnk = NULL;
}
}
// Delete a media type structure that was allocated on the heap.
// http://msdn.microsoft.com/en-us/library/dd375432(VS.85).aspx
void VideoCaptureDeviceWin::ScopedMediaType::DeleteMediaType(
AM_MEDIA_TYPE* mt) {
if (mt != NULL) {
FreeMediaType(mt);
CoTaskMemFree(mt);
}
}
VideoCaptureDeviceWin::VideoCaptureDeviceWin(const Name& device_name)
: device_name_(device_name),
state_(kIdle) {
DetachFromThread();
}
VideoCaptureDeviceWin::~VideoCaptureDeviceWin() {
DCHECK(CalledOnValidThread());
if (media_control_)
media_control_->Stop();
if (graph_builder_) {
if (sink_filter_) {
graph_builder_->RemoveFilter(sink_filter_);
sink_filter_ = NULL;
}
if (capture_filter_)
graph_builder_->RemoveFilter(capture_filter_);
if (mjpg_filter_)
graph_builder_->RemoveFilter(mjpg_filter_);
}
}
bool VideoCaptureDeviceWin::Init() {
DCHECK(CalledOnValidThread());
HRESULT hr = GetDeviceFilter(device_name_, capture_filter_.Receive());
if (!capture_filter_) {
DVLOG(2) << "Failed to create capture filter.";
return false;
}
output_capture_pin_ =
GetPin(capture_filter_, PINDIR_OUTPUT, PIN_CATEGORY_CAPTURE);
if (!output_capture_pin_) {
DVLOG(2) << "Failed to get capture output pin";
return false;
}
// Create the sink filter used for receiving Captured frames.
sink_filter_ = new SinkFilter(this);
if (sink_filter_ == NULL) {
DVLOG(2) << "Failed to create send filter";
return false;
}
input_sink_pin_ = sink_filter_->GetPin(0);
hr = graph_builder_.CreateInstance(CLSID_FilterGraph, NULL,
CLSCTX_INPROC_SERVER);
if (FAILED(hr)) {
DVLOG(2) << "Failed to create graph builder.";
return false;
}
hr = graph_builder_.QueryInterface(media_control_.Receive());
if (FAILED(hr)) {
DVLOG(2) << "Failed to create media control builder.";
return false;
}
hr = graph_builder_->AddFilter(capture_filter_, NULL);
if (FAILED(hr)) {
DVLOG(2) << "Failed to add the capture device to the graph.";
return false;
}
hr = graph_builder_->AddFilter(sink_filter_, NULL);
if (FAILED(hr)) {
DVLOG(2)<< "Failed to add the send filter to the graph.";
return false;
}
return CreateCapabilityMap();
}
void VideoCaptureDeviceWin::AllocateAndStart(
const VideoCaptureParams& params,
scoped_ptr<VideoCaptureDevice::Client> client) {
DCHECK(CalledOnValidThread());
if (state_ != kIdle)
return;
client_ = client.Pass();
// Get the camera capability that best match the requested resolution.
const VideoCaptureCapabilityWin& found_capability =
capabilities_.GetBestMatchedFormat(
params.requested_format.frame_size.width(),
params.requested_format.frame_size.height(),
params.requested_format.frame_rate);
VideoCaptureFormat format = found_capability.supported_format;
// Reduce the frame rate if the requested frame rate is lower
// than the capability.
if (format.frame_rate > params.requested_format.frame_rate)
format.frame_rate = params.requested_format.frame_rate;
ScopedComPtr<IAMStreamConfig> stream_config;
HRESULT hr = output_capture_pin_.QueryInterface(stream_config.Receive());
if (FAILED(hr)) {
SetErrorState("Can't get the Capture format settings");
return;
}
int count = 0, size = 0;
hr = stream_config->GetNumberOfCapabilities(&count, &size);
if (FAILED(hr)) {
DVLOG(2) << "Failed to GetNumberOfCapabilities";
return;
}
scoped_ptr<BYTE[]> caps(new BYTE[size]);
ScopedMediaType media_type;
// Get the windows capability from the capture device.
hr = stream_config->GetStreamCaps(
found_capability.stream_index, media_type.Receive(), caps.get());
if (SUCCEEDED(hr)) {
if (media_type->formattype == FORMAT_VideoInfo) {
VIDEOINFOHEADER* h =
reinterpret_cast<VIDEOINFOHEADER*>(media_type->pbFormat);
if (format.frame_rate > 0)
h->AvgTimePerFrame = kSecondsToReferenceTime / format.frame_rate;
}
// Set the sink filter to request this format.
sink_filter_->SetRequestedMediaFormat(format);
// Order the capture device to use this format.
hr = stream_config->SetFormat(media_type.get());
}
if (FAILED(hr))
SetErrorState("Failed to set capture device output format");
if (format.pixel_format == PIXEL_FORMAT_MJPEG && !mjpg_filter_.get()) {
// Create MJPG filter if we need it.
hr = mjpg_filter_.CreateInstance(CLSID_MjpegDec, NULL, CLSCTX_INPROC);
if (SUCCEEDED(hr)) {
input_mjpg_pin_ = GetPin(mjpg_filter_, PINDIR_INPUT, GUID_NULL);
output_mjpg_pin_ = GetPin(mjpg_filter_, PINDIR_OUTPUT, GUID_NULL);
hr = graph_builder_->AddFilter(mjpg_filter_, NULL);
}
if (FAILED(hr)) {
mjpg_filter_.Release();
input_mjpg_pin_.Release();
output_mjpg_pin_.Release();
}
}
SetAntiFlickerInCaptureFilter();
if (format.pixel_format == PIXEL_FORMAT_MJPEG && mjpg_filter_.get()) {
// Connect the camera to the MJPEG decoder.
hr = graph_builder_->ConnectDirect(output_capture_pin_, input_mjpg_pin_,
NULL);
// Connect the MJPEG filter to the Capture filter.
hr += graph_builder_->ConnectDirect(output_mjpg_pin_, input_sink_pin_,
NULL);
} else if (media_type->subtype == kMediaSubTypeHDYC) {
// HDYC pixel format, used by the DeckLink capture card, needs an AVI
// decompressor filter after source, let |graph_builder_| add it.
hr = graph_builder_->Connect(output_capture_pin_, input_sink_pin_);
} else {
hr = graph_builder_->ConnectDirect(output_capture_pin_, input_sink_pin_,
NULL);
}
if (FAILED(hr)) {
SetErrorState("Failed to connect the Capture graph.");
return;
}
hr = media_control_->Pause();
if (FAILED(hr)) {
SetErrorState("Failed to Pause the Capture device. "
"Is it already occupied?");
return;
}
// Get the format back from the sink filter after the filter have been
// connected.
capture_format_ = sink_filter_->ResultingFormat();
// Start capturing.
hr = media_control_->Run();
if (FAILED(hr)) {
SetErrorState("Failed to start the Capture device.");
return;
}
state_ = kCapturing;
}
void VideoCaptureDeviceWin::StopAndDeAllocate() {
DCHECK(CalledOnValidThread());
if (state_ != kCapturing)
return;
HRESULT hr = media_control_->Stop();
if (FAILED(hr)) {
SetErrorState("Failed to stop the capture graph.");
return;
}
graph_builder_->Disconnect(output_capture_pin_);
graph_builder_->Disconnect(input_sink_pin_);
// If the _mjpg filter exist disconnect it even if it has not been used.
if (mjpg_filter_) {
graph_builder_->Disconnect(input_mjpg_pin_);
graph_builder_->Disconnect(output_mjpg_pin_);
}
if (FAILED(hr)) {
SetErrorState("Failed to Stop the Capture device");
return;
}
client_.reset();
state_ = kIdle;
}
// Implements SinkFilterObserver::SinkFilterObserver.
void VideoCaptureDeviceWin::FrameReceived(const uint8* buffer,
int length) {
client_->OnIncomingCapturedData(
buffer, length, capture_format_, 0, base::TimeTicks::Now());
}
bool VideoCaptureDeviceWin::CreateCapabilityMap() {
DCHECK(CalledOnValidThread());
ScopedComPtr<IAMStreamConfig> stream_config;
HRESULT hr = output_capture_pin_.QueryInterface(stream_config.Receive());
if (FAILED(hr)) {
DVLOG(2) << "Failed to get IAMStreamConfig interface from "
"capture device";
return false;
}
// Get interface used for getting the frame rate.
ScopedComPtr<IAMVideoControl> video_control;
hr = capture_filter_.QueryInterface(video_control.Receive());
DVLOG_IF(2, FAILED(hr)) << "IAMVideoControl Interface NOT SUPPORTED";
int count = 0, size = 0;
hr = stream_config->GetNumberOfCapabilities(&count, &size);
if (FAILED(hr)) {
DVLOG(2) << "Failed to GetNumberOfCapabilities";
return false;
}
scoped_ptr<BYTE[]> caps(new BYTE[size]);
for (int i = 0; i < count; ++i) {
ScopedMediaType media_type;
hr = stream_config->GetStreamCaps(i, media_type.Receive(), caps.get());
// GetStreamCaps() may return S_FALSE, so don't use FAILED() or SUCCEED()
// macros here since they'll trigger incorrectly.
if (hr != S_OK) {
DVLOG(2) << "Failed to GetStreamCaps";
return false;
}
if (media_type->majortype == MEDIATYPE_Video &&
media_type->formattype == FORMAT_VideoInfo) {
VideoCaptureCapabilityWin capability(i);
capability.supported_format.pixel_format =
TranslateMediaSubtypeToPixelFormat(media_type->subtype);
if (capability.supported_format.pixel_format == PIXEL_FORMAT_UNKNOWN)
continue;
VIDEOINFOHEADER* h =
reinterpret_cast<VIDEOINFOHEADER*>(media_type->pbFormat);
capability.supported_format.frame_size.SetSize(h->bmiHeader.biWidth,
h->bmiHeader.biHeight);
// Try to get a better |time_per_frame| from IAMVideoControl. If not, use
// the value from VIDEOINFOHEADER.
REFERENCE_TIME time_per_frame = h->AvgTimePerFrame;
if (video_control) {
ScopedCoMem<LONGLONG> max_fps;
LONG list_size = 0;
SIZE size = {capability.supported_format.frame_size.width(),
capability.supported_format.frame_size.height()};
// GetFrameRateList doesn't return max frame rate always
// eg: Logitech Notebook. This may be due to a bug in that API
// because GetFrameRateList array is reversed in the above camera. So
// a util method written. Can't assume the first value will return
// the max fps.
hr = video_control->GetFrameRateList(output_capture_pin_, i, size,
&list_size, &max_fps);
// Sometimes |list_size| will be > 0, but max_fps will be NULL. Some
// drivers may return an HRESULT of S_FALSE which SUCCEEDED() translates
// into success, so explicitly check S_OK. See http://crbug.com/306237.
if (hr == S_OK && list_size > 0 && max_fps) {
time_per_frame = *std::min_element(max_fps.get(),
max_fps.get() + list_size);
}
}
capability.supported_format.frame_rate =
(time_per_frame > 0)
? (kSecondsToReferenceTime / static_cast<float>(time_per_frame))
: 0.0;
// DirectShow works at the moment only on integer frame_rate but the
// best capability matching class works on rational frame rates.
capability.frame_rate_numerator = capability.supported_format.frame_rate;
capability.frame_rate_denominator = 1;
capabilities_.Add(capability);
}
}
return !capabilities_.empty();
}
// Set the power line frequency removal in |capture_filter_| if available.
void VideoCaptureDeviceWin::SetAntiFlickerInCaptureFilter() {
const int power_line_frequency = GetPowerLineFrequencyForLocation();
if (power_line_frequency != kPowerLine50Hz &&
power_line_frequency != kPowerLine60Hz) {
return;
}
ScopedComPtr<IKsPropertySet> ks_propset;
DWORD type_support = 0;
HRESULT hr;
if (SUCCEEDED(hr = ks_propset.QueryFrom(capture_filter_)) &&
SUCCEEDED(hr = ks_propset->QuerySupported(PROPSETID_VIDCAP_VIDEOPROCAMP,
KSPROPERTY_VIDEOPROCAMP_POWERLINE_FREQUENCY, &type_support)) &&
(type_support & KSPROPERTY_SUPPORT_SET)) {
KSPROPERTY_VIDEOPROCAMP_S data = {};
data.Property.Set = PROPSETID_VIDCAP_VIDEOPROCAMP;
data.Property.Id = KSPROPERTY_VIDEOPROCAMP_POWERLINE_FREQUENCY;
data.Property.Flags = KSPROPERTY_TYPE_SET;
data.Value = (power_line_frequency == kPowerLine50Hz) ? 1 : 2;
data.Flags = KSPROPERTY_VIDEOPROCAMP_FLAGS_MANUAL;
hr = ks_propset->Set(PROPSETID_VIDCAP_VIDEOPROCAMP,
KSPROPERTY_VIDEOPROCAMP_POWERLINE_FREQUENCY,
&data, sizeof(data), &data, sizeof(data));
DVLOG_IF(ERROR, FAILED(hr)) << "Anti-flicker setting failed.";
DVLOG_IF(2, SUCCEEDED(hr)) << "Anti-flicker set correctly.";
} else {
DVLOG(2) << "Anti-flicker setting not supported.";
}
}
void VideoCaptureDeviceWin::SetErrorState(const std::string& reason) {
DCHECK(CalledOnValidThread());
DVLOG(1) << reason;
state_ = kError;
client_->OnError(reason);
}
} // namespace media
| chromium2014/src | media/video/capture/win/video_capture_device_win.cc | C++ | bsd-3-clause | 18,399 | [
30522,
1013,
1013,
9385,
1006,
1039,
1007,
2262,
1996,
10381,
21716,
5007,
6048,
1012,
2035,
2916,
9235,
1012,
1013,
1013,
2224,
1997,
2023,
3120,
3642,
2003,
9950,
2011,
1037,
18667,
2094,
1011,
2806,
6105,
2008,
2064,
2022,
1013,
1013,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
* Copyright 2017 Google Inc. 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.
*/
using System;
namespace ApiAiSDK.Util
{
public static class ActionExtensions
{
public static void InvokeSafely(this Action action)
{
if (action != null)
{
action();
}
}
public static void InvokeSafely<T>(this Action<T> action, T arg)
{
if (action != null)
{
action(arg);
}
}
}
}
| dialogflow/dialogflow-dotnet-client | ApiAiSDK/Util/ActionExtensions.cs | C# | apache-2.0 | 1,068 | [
30522,
1013,
1008,
1008,
1008,
9385,
2418,
8224,
4297,
1012,
2035,
2916,
9235,
1012,
1008,
1008,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
1012,
1014,
1006,
1996,
1000,
6105,
1000,
1007,
1025,
1008,
2017,
2089,
2025,
2224,
2023,
53... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!doctype html>
<html>
<head>
<title>Firepad Tests</title>
<link rel="stylesheet" type="text/css" href="jasmine-1.3.1/jasmine.css">
<script type="text/javascript" src="jasmine-1.3.1/jasmine.js"></script>
<script type="text/javascript" src="jasmine-1.3.1/jasmine-html.js"></script>
<script type="text/javascript" src="codemirror/codemirror.js"></script>
<link rel="stylesheet" type="text/css" href="codemirror/codemirror.css">
<script src="firepad-debug.js"></script>
<script src="lib/helpers.js"></script>
<script src="lib/text-operation.spec.js"></script>
<script src="lib/cursor.spec.js"></script>
<script src="lib/wrapped-operation.spec.js"></script>
<script src="lib/undomanager.spec.js"></script>
<script src="lib/client.spec.js"></script>
<script src="lib/annotation-list.spec.js"></script>
<script src="lib/codemirror-adapter.spec.js"></script>
<script src="lib/parse-html.spec.js"></script>
<script type="text/javascript">
(function() {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function(spec) {
return htmlReporter.specFilter(spec);
};
window.onload = function() {
jasmineEnv.execute();
};
})();
</script>
</head>
<body>
</body>
</html>
| cben/firepad | test/index.html | HTML | mit | 1,398 | [
30522,
1026,
999,
9986,
13874,
16129,
1028,
1026,
16129,
1028,
1026,
2132,
1028,
1026,
2516,
1028,
2543,
15455,
5852,
1026,
1013,
2516,
1028,
1026,
4957,
2128,
2140,
1027,
1000,
6782,
21030,
2102,
1000,
2828,
1027,
1000,
3793,
1013,
20116,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
var yhr = require('./main.js');
module.exports = function(uri,opt){
return yhr('DELETE',uri,null,opt);
};
| manvalls/yhr | delete.js | JavaScript | lgpl-3.0 | 110 | [
30522,
13075,
1061,
8093,
1027,
5478,
1006,
1005,
1012,
1013,
2364,
1012,
1046,
2015,
1005,
1007,
1025,
11336,
1012,
14338,
1027,
3853,
1006,
24471,
2072,
1010,
23569,
1007,
1063,
2709,
1061,
8093,
1006,
1005,
3972,
12870,
1005,
1010,
24471... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* 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.
*/
/* $Id: BasicTranscoderTestSuite.java 1178747 2011-10-04 10:09:01Z vhennebert $ */
package org.apache.fop;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/**
* Test suite for basic functionality of FOP's transcoders.
*/
@RunWith(Suite.class)
@SuiteClasses({
BasicPDFTranscoderTestCase.class,
BasicPSTranscoderTestCase.class
})
public class BasicTranscoderTestSuite {
}
| pellcorp/fop | test/java/org/apache/fop/BasicTranscoderTestSuite.java | Java | apache-2.0 | 1,249 | [
30522,
1013,
1008,
1008,
7000,
2000,
1996,
15895,
4007,
3192,
1006,
2004,
2546,
1007,
2104,
2028,
2030,
2062,
1008,
12130,
6105,
10540,
1012,
2156,
1996,
5060,
5371,
5500,
2007,
1008,
2023,
2147,
2005,
3176,
2592,
4953,
9385,
6095,
1012,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal class SolutionCrawlerLogger
{
private const string Id = nameof(Id);
private const string Kind = nameof(Kind);
private const string Analyzer = nameof(Analyzer);
private const string DocumentCount = nameof(DocumentCount);
private const string HighPriority = nameof(HighPriority);
private const string Enabled = nameof(Enabled);
private const string AnalyzerCount = nameof(AnalyzerCount);
private const string PersistentStorage = nameof(PersistentStorage);
private const string GlobalOperation = nameof(GlobalOperation);
private const string HigherPriority = nameof(HigherPriority);
private const string LowerPriority = nameof(LowerPriority);
private const string TopLevel = nameof(TopLevel);
private const string MemberLevel = nameof(MemberLevel);
private const string NewWorkItem = nameof(NewWorkItem);
private const string UpdateWorkItem = nameof(UpdateWorkItem);
private const string ProjectEnqueue = nameof(ProjectEnqueue);
private const string ResetStates = nameof(ResetStates);
private const string ProjectNotExist = nameof(ProjectNotExist);
private const string DocumentNotExist = nameof(DocumentNotExist);
private const string ProcessProject = nameof(ProcessProject);
private const string OpenDocument = nameof(OpenDocument);
private const string CloseDocument = nameof(CloseDocument);
private const string SolutionHash = nameof(SolutionHash);
private const string ProcessDocument = nameof(ProcessDocument);
private const string ProcessDocumentCancellation = nameof(ProcessDocumentCancellation);
private const string ProcessProjectCancellation = nameof(ProcessProjectCancellation);
private const string ActiveFileEnqueue = nameof(ActiveFileEnqueue);
private const string ActiveFileProcessDocument = nameof(ActiveFileProcessDocument);
private const string ActiveFileProcessDocumentCancellation = nameof(ActiveFileProcessDocumentCancellation);
private const string Max = "Maximum";
private const string Min = "Minimum";
private const string Median = nameof(Median);
private const string Mean = nameof(Mean);
private const string Mode = nameof(Mode);
private const string Range = nameof(Range);
private const string Count = nameof(Count);
public static void LogRegistration(int correlationId, Workspace workspace)
{
Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Register, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
m[Kind] = workspace.Kind;
}));
}
public static void LogUnregistration(int correlationId)
{
Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Unregister, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
}));
}
public static void LogReanalyze(int correlationId, IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds, bool highPriority)
{
Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Reanalyze, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
m[Analyzer] = analyzer.ToString();
m[DocumentCount] = documentIds == null ? 0 : documentIds.Count();
m[HighPriority] = highPriority;
}));
}
public static void LogOptionChanged(int correlationId, bool value)
{
Logger.Log(FunctionId.WorkCoordinator_SolutionCrawlerOption, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
m[Enabled] = value;
}));
}
public static void LogActiveFileAnalyzers(int correlationId, Workspace workspace, ImmutableArray<IIncrementalAnalyzer> reordered)
{
LogAnalyzersWorker(
FunctionId.IncrementalAnalyzerProcessor_ActiveFileAnalyzers, FunctionId.IncrementalAnalyzerProcessor_ActiveFileAnalyzer,
correlationId, workspace, reordered);
}
public static void LogAnalyzers(int correlationId, Workspace workspace, ImmutableArray<IIncrementalAnalyzer> reordered)
{
LogAnalyzersWorker(
FunctionId.IncrementalAnalyzerProcessor_Analyzers, FunctionId.IncrementalAnalyzerProcessor_Analyzer,
correlationId, workspace, reordered);
}
private static void LogAnalyzersWorker(
FunctionId analyzersId, FunctionId analyzerId, int correlationId, Workspace workspace, ImmutableArray<IIncrementalAnalyzer> reordered)
{
if (workspace.Kind == WorkspaceKind.Preview)
{
return;
}
// log registered analyzers.
Logger.Log(analyzersId, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
m[AnalyzerCount] = reordered.Length;
}));
foreach (var analyzer in reordered)
{
Logger.Log(analyzerId, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
m[Analyzer] = analyzer.ToString();
}));
}
}
public static void LogWorkCoordinatorShutdownTimeout(int correlationId)
{
Logger.Log(FunctionId.WorkCoordinator_ShutdownTimeout, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
}));
}
public static void LogWorkspaceEvent(LogAggregator logAggregator, int kind)
{
logAggregator.IncreaseCount(kind);
}
public static void LogWorkCoordinatorShutdown(int correlationId, LogAggregator logAggregator)
{
Logger.Log(FunctionId.WorkCoordinator_Shutdown, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
foreach (var kv in logAggregator)
{
var change = ((WorkspaceChangeKind)kv.Key).ToString();
m[change] = kv.Value.GetCount();
}
}));
}
public static void LogGlobalOperation(LogAggregator logAggregator)
{
logAggregator.IncreaseCount(GlobalOperation);
}
public static void LogActiveFileEnqueue(LogAggregator logAggregator)
{
logAggregator.IncreaseCount(ActiveFileEnqueue);
}
public static void LogWorkItemEnqueue(LogAggregator logAggregator, ProjectId projectId)
{
logAggregator.IncreaseCount(ProjectEnqueue);
}
public static void LogWorkItemEnqueue(
LogAggregator logAggregator, string language, DocumentId documentId, InvocationReasons reasons, bool lowPriority, SyntaxPath activeMember, bool added)
{
logAggregator.IncreaseCount(language);
logAggregator.IncreaseCount(added ? NewWorkItem : UpdateWorkItem);
if (documentId != null)
{
logAggregator.IncreaseCount(activeMember == null ? TopLevel : MemberLevel);
if (lowPriority)
{
logAggregator.IncreaseCount(LowerPriority);
logAggregator.IncreaseCount(ValueTuple.Create(LowerPriority, documentId.Id));
}
}
foreach (var reason in reasons)
{
logAggregator.IncreaseCount(reason);
}
}
public static void LogHigherPriority(LogAggregator logAggregator, Guid documentId)
{
logAggregator.IncreaseCount(HigherPriority);
logAggregator.IncreaseCount(ValueTuple.Create(HigherPriority, documentId));
}
public static void LogResetStates(LogAggregator logAggregator)
{
logAggregator.IncreaseCount(ResetStates);
}
public static void LogIncrementalAnalyzerProcessorStatistics(int correlationId, Solution solution, LogAggregator logAggregator, ImmutableArray<IIncrementalAnalyzer> analyzers)
{
Logger.Log(FunctionId.IncrementalAnalyzerProcessor_Shutdown, KeyValueLogMessage.Create(m =>
{
var solutionHash = GetSolutionHash(solution);
m[Id] = correlationId;
m[SolutionHash] = solutionHash.ToString();
var statMap = new Dictionary<string, List<int>>();
foreach (var kv in logAggregator)
{
if (kv.Key is string)
{
m[kv.Key.ToString()] = kv.Value.GetCount();
continue;
}
if (kv.Key is ValueTuple<string, Guid>)
{
var tuple = (ValueTuple<string, Guid>)kv.Key;
var list = statMap.GetOrAdd(tuple.Item1, _ => new List<int>());
list.Add(kv.Value.GetCount());
continue;
}
throw ExceptionUtilities.Unreachable;
}
foreach (var kv in statMap)
{
var key = kv.Key.ToString();
var result = LogAggregator.GetStatistics(kv.Value);
m[CreateProperty(key, Max)] = result.Maximum;
m[CreateProperty(key, Min)] = result.Minimum;
m[CreateProperty(key, Median)] = result.Median;
m[CreateProperty(key, Mean)] = result.Mean;
m[CreateProperty(key, Mode)] = result.Mode;
m[CreateProperty(key, Range)] = result.Range;
m[CreateProperty(key, Count)] = result.Count;
}
}));
foreach (var analyzer in analyzers)
{
var diagIncrementalAnalyzer = analyzer as BaseDiagnosticIncrementalAnalyzer;
if (diagIncrementalAnalyzer != null)
{
diagIncrementalAnalyzer.LogAnalyzerCountSummary();
break;
}
}
}
private static int GetSolutionHash(Solution solution)
{
if (solution != null && solution.FilePath != null)
{
return solution.FilePath.ToLowerInvariant().GetHashCode();
}
return 0;
}
private static string CreateProperty(string parent, string child)
{
return parent + "." + child;
}
public static void LogProcessCloseDocument(LogAggregator logAggregator, Guid documentId)
{
logAggregator.IncreaseCount(CloseDocument);
logAggregator.IncreaseCount(ValueTuple.Create(CloseDocument, documentId));
}
public static void LogProcessOpenDocument(LogAggregator logAggregator, Guid documentId)
{
logAggregator.IncreaseCount(OpenDocument);
logAggregator.IncreaseCount(ValueTuple.Create(OpenDocument, documentId));
}
public static void LogProcessActiveFileDocument(LogAggregator logAggregator, Guid documentId, bool processed)
{
if (processed)
{
logAggregator.IncreaseCount(ActiveFileProcessDocument);
}
else
{
logAggregator.IncreaseCount(ActiveFileProcessDocumentCancellation);
}
}
public static void LogProcessDocument(LogAggregator logAggregator, Guid documentId, bool processed)
{
if (processed)
{
logAggregator.IncreaseCount(ProcessDocument);
}
else
{
logAggregator.IncreaseCount(ProcessDocumentCancellation);
}
logAggregator.IncreaseCount(ValueTuple.Create(ProcessDocument, documentId));
}
public static void LogProcessDocumentNotExist(LogAggregator logAggregator)
{
logAggregator.IncreaseCount(DocumentNotExist);
}
public static void LogProcessProject(LogAggregator logAggregator, Guid projectId, bool processed)
{
if (processed)
{
logAggregator.IncreaseCount(ProcessProject);
}
else
{
logAggregator.IncreaseCount(ProcessProjectCancellation);
}
logAggregator.IncreaseCount(ValueTuple.Create(ProcessProject, projectId));
}
public static void LogProcessProjectNotExist(LogAggregator logAggregator)
{
logAggregator.IncreaseCount(ProjectNotExist);
}
}
}
| basoundr/roslyn | src/Features/Core/Portable/SolutionCrawler/SolutionCrawlerLogger.cs | C# | apache-2.0 | 13,429 | [
30522,
1013,
1013,
9385,
1006,
1039,
1007,
7513,
1012,
2035,
2916,
9235,
1012,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
1012,
1014,
1012,
2156,
6105,
1012,
19067,
2102,
1999,
1996,
2622,
7117,
2005,
6105,
2592,
1012,
2478,
2291,
1... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module HTIG.IRCServer.Core
( IRCState(..)
, IRCM
, runIRCM
, runIRCM'
, getConn
, getGlobal
, setGlobal
, modifyGlobal
, modifyGlobal'
, getLocal
, setLocal
, modifyLocal
, modifyLocal'
, liftIO
) where
import Control.Applicative (Applicative(pure, (<*>)))
import Control.Concurrent.STM (TVar, atomically, readTVar, writeTVar)
import Control.Monad.Trans (MonadIO, liftIO)
import Control.Monad.Reader (ReaderT, MonadReader, runReaderT, asks)
import HTIG.IRCServer.Connection (Connection)
data IRCState g l = IRCState { ircGlobal :: TVar g
, ircLocal :: TVar l
, ircConn :: Connection
}
newtype IRCM g l a = IRCM { unIRCM :: ReaderT (IRCState g l) IO a }
deriving (Monad, Functor, MonadIO, MonadReader (IRCState g l))
instance Applicative (IRCM g l) where
pure = return
f <*> x = do
f' <- f
x' <- x
return $ f' x'
runIRCM :: IRCM g l a -> TVar g -> TVar l -> Connection -> IO a
runIRCM m g l conn = runIRCM' m $ IRCState g l conn
runIRCM' :: IRCM g l a -> IRCState g l -> IO a
runIRCM' m s = runReaderT (unIRCM m) s
getConn :: IRCM g l Connection
getConn = asks ircConn
getGlobal :: IRCM g l g
getGlobal = mkGet ircGlobal
setGlobal :: g -> IRCM g l ()
setGlobal g = mkSet ircGlobal g
modifyGlobal :: (g -> g) -> IRCM g l ()
modifyGlobal f = mkModify ircGlobal $ \g -> (f g, ())
modifyGlobal' :: (g -> (g, a)) -> IRCM g l a
modifyGlobal' f = mkModify ircGlobal f
getLocal :: IRCM g l l
getLocal = mkGet ircLocal
setLocal :: l -> IRCM g l ()
setLocal l = mkSet ircLocal l
modifyLocal :: (l -> l) -> IRCM g l ()
modifyLocal f = mkModify ircLocal $ \l -> (f l, ())
modifyLocal' :: (l -> (l, a)) -> IRCM g l a
modifyLocal' f = mkModify ircLocal f
mkGet :: (IRCState g l -> TVar a) -> IRCM g l a
mkGet f = liftIO . atomically . readTVar =<< asks f
mkSet :: (IRCState g l -> TVar a) -> a -> IRCM g l ()
mkSet f v = liftIO . atomically . flip writeTVar v =<< asks f
mkModify :: (IRCState g l -> TVar a) -> (a -> (a, b)) -> IRCM g l b
mkModify f f' = do
tv <- asks f
liftIO $ atomically $ do
v <- readTVar tv
let (v', r) = f' v
writeTVar tv v'
return r
| nakamuray/htig | HTIG/IRCServer/Core.hs | Haskell | bsd-3-clause | 2,338 | [
30522,
1063,
1011,
1001,
2653,
18960,
2638,
26677,
18863,
4063,
14966,
1001,
1011,
1065,
11336,
1044,
3775,
2290,
1012,
20868,
6169,
2121,
6299,
1012,
4563,
1006,
20868,
6169,
12259,
1006,
1012,
1012,
1007,
1010,
20868,
27487,
1010,
2448,
4... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
* || ____ _ __
* +------+ / __ )(_) /_______________ _____ ___
* | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
* +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
* || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
*
* Crazyflie 2.0 NRF Firmware
* Copyright (c) 2014, Bitcraze AB, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
*
* esb.c - Implementation of the Nordic ESB protocol in PRX mode for nRF51822
*/
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include "esb.h"
#include <nrf.h>
#ifdef BLE
#include <ble_gap.h>
#include <nrf_soc.h>
#endif
#define RXQ_LEN 16
#define TXQ_LEN 16
static bool isInit = true;
static int channel = 2;
static int datarate = esbDatarate2M;
static int txpower = RADIO_TXPOWER_TXPOWER_0dBm;
static bool contwave = false;
#ifdef CADDRESS
static uint64_t address = CADDRESS;
#else
static uint64_t address = 0xE7E7E7E7E7ULL;
#endif
static enum {doTx, doRx} rs; //Radio state
static EsbPacket rxPackets[TXQ_LEN];
static int rxq_head = 0;
static int rxq_tail = 0;
static EsbPacket txPackets[TXQ_LEN];
static int txq_head = 0;
static int txq_tail = 0;
// 1bit packet counters
static int curr_down = 1;
static int curr_up = 1;
static bool has_safelink;
static EsbPacket ackPacket; // Empty ack packet
static EsbPacket servicePacket; // Packet sent to answer a low level request
/* helper functions */
static uint32_t swap_bits(uint32_t inp)
{
uint32_t i;
uint32_t retval = 0;
inp = (inp & 0x000000FFUL);
for(i = 0; i < 8; i++)
{
retval |= ((inp >> i) & 0x01) << (7 - i);
}
return retval;
}
static uint32_t bytewise_bitswap(uint32_t inp)
{
return (swap_bits(inp >> 24) << 24)
| (swap_bits(inp >> 16) << 16)
| (swap_bits(inp >> 8) << 8)
| (swap_bits(inp));
}
/* Radio protocol implementation */
static bool isRetry(EsbPacket *pk)
{
static int prevPid;
static int prevCrc;
bool retry = false;
if ((prevPid == pk->pid) && (prevCrc == pk->crc)) {
retry = true;
}
prevPid = pk->pid;
prevCrc = pk->crc;
return retry;
}
// Handles the queue
static void setupTx(bool retry)
{
static EsbPacket * lastSentPacket;
if (retry) {
NRF_RADIO->PACKETPTR = (uint32_t)lastSentPacket;
} else {
if (lastSentPacket != &ackPacket) {
//No retry, TX payload has been sent!
if (txq_head != txq_tail) {
txq_tail = ((txq_tail+1)%TXQ_LEN);
}
}
if (lastSentPacket == &servicePacket) {
servicePacket.size = 0;
}
if (servicePacket.size) {
NRF_RADIO->PACKETPTR = (uint32_t)&servicePacket;
lastSentPacket = &servicePacket;
} else if (txq_tail != txq_head) {
// Send next TX packet
NRF_RADIO->PACKETPTR = (uint32_t)&txPackets[txq_tail];
if (has_safelink) {
txPackets[txq_tail].data[0] = (txPackets[txq_tail].data[0]&0xf3) | curr_down<<2;
}
lastSentPacket = &txPackets[txq_tail];
} else {
// Send empty ACK
#ifdef RSSI_ACK_PACKET
ackPacket.size = 3;
ackPacket.data[0] = 0xf3 | curr_down<<2;
ackPacket.data[1] = 0x01;
ackPacket.data[2] = NRF_RADIO->RSSISAMPLE;
#else
ackPacket.size = 1;
ackPacket.data[0] = 0xf3 | curr_down<<2;
#endif
NRF_RADIO->PACKETPTR = (uint32_t)&ackPacket;
lastSentPacket = &ackPacket;
}
}
//After being disabled the radio will automatically send the ACK
NRF_RADIO->SHORTS &= ~RADIO_SHORTS_DISABLED_RXEN_Msk;
NRF_RADIO->SHORTS |= RADIO_SHORTS_DISABLED_TXEN_Msk;
rs = doTx;
NRF_RADIO->TASKS_DISABLE = 1UL;
}
static void setupRx()
{
NRF_RADIO->PACKETPTR = (uint32_t)&rxPackets[rxq_head];
NRF_RADIO->SHORTS &= ~RADIO_SHORTS_DISABLED_TXEN_Msk;
NRF_RADIO->SHORTS |= RADIO_SHORTS_DISABLED_RXEN_Msk;
rs = doRx;
NRF_RADIO->TASKS_DISABLE = 1UL;
}
void RADIO_IRQHandler()
{
esbInterruptHandler();
}
void esbInterruptHandler()
{
EsbPacket *pk;
if (NRF_RADIO->EVENTS_END) {
NRF_RADIO->EVENTS_END = 0UL;
switch (rs){
case doRx:
//Wrong CRC packet are dropped
if (!NRF_RADIO->CRCSTATUS) {
NRF_RADIO->TASKS_START = 1UL;
return;
}
pk = &rxPackets[rxq_head];
pk->rssi = (uint8_t) NRF_RADIO->RSSISAMPLE;
pk->crc = NRF_RADIO->RXCRC;
// If no more space available on RX queue, drop packet!
if (((rxq_head+1)%RXQ_LEN) == rxq_tail) {
NRF_RADIO->TASKS_START = 1UL;
return;
}
// If this packet is a retry, send the same ACK again
if (isRetry(pk)) {
setupTx(true);
return;
}
// Match safeLink packet and answer it
#if 0 // Disabled until syslink is fixed in STM32, see bitcraze/crazyflie-firmware#69
if (pk->size == 3 && (pk->data[0]&0xf3) == 0xf3 && pk->data[1] == 0x05) {
has_safelink = pk->data[2];
memcpy(servicePacket.data, pk->data, 3);
servicePacket.size = 3;
setupTx(false);
// Reset packet counters
curr_down = 1;
curr_up = 1;
return;
}
#endif
// Good packet received, yea!
if (!has_safelink || (pk->data[0] & 0x08) != curr_up<<3) {
rxq_head = ((rxq_head+1)%RXQ_LEN);
curr_up = 1-curr_up;
}
if (!has_safelink || (pk->data[0]&0x04) != curr_down<<2) {
curr_down = 1-curr_down;
setupTx(false);
} else {
setupTx(true);
}
break;
case doTx:
//Setup RX for next packet
setupRx();
break;
}
}
}
/* Public API */
// S1 is used for compatibility with NRF24L0+. These three bits are used
// to store the PID and NO_ACK.
#define PACKET0_S1_SIZE (3UL)
// S0 is not used
#define PACKET0_S0_SIZE (0UL)
// The size of the packet length field is 6 bits
#define PACKET0_PAYLOAD_SIZE (6UL)
// The size of the base address field is 4 bytes
#define PACKET1_BASE_ADDRESS_LENGTH (4UL)
// Don't use any extra added length besides the length field when sending
#define PACKET1_STATIC_LENGTH (0UL)
// Max payload allowed in a packet
#define PACKET1_PAYLOAD_SIZE (32UL)
void esbInit()
{
NRF_RADIO->POWER = 1;
// Enable Radio interrupts
#ifndef BLE
NVIC_SetPriority(RADIO_IRQn, 3);
NVIC_EnableIRQ(RADIO_IRQn);
#else
NVIC_EnableIRQ(RADIO_IRQn);
#endif
NRF_RADIO->TXPOWER = (txpower << RADIO_TXPOWER_TXPOWER_Pos);
switch (datarate) {
case esbDatarate250K:
NRF_RADIO->MODE = (RADIO_MODE_MODE_Nrf_250Kbit << RADIO_MODE_MODE_Pos);
break;
case esbDatarate1M:
NRF_RADIO->MODE = (RADIO_MODE_MODE_Nrf_1Mbit << RADIO_MODE_MODE_Pos);
break;
case esbDatarate2M:
NRF_RADIO->MODE = (RADIO_MODE_MODE_Nrf_2Mbit << RADIO_MODE_MODE_Pos);
break;
}
NRF_RADIO->FREQUENCY = channel;
if (contwave) {
NRF_RADIO->TEST = 3;
NRF_RADIO->TASKS_RXEN = 1U;
return;
}
// Radio address config
// Using logical address 0 so only BASE0 and PREFIX0 & 0xFF are used
NRF_RADIO->PREFIX0 = 0xC4C3C200UL | (bytewise_bitswap(address >> 32) & 0xFF); // Prefix byte of addresses 3 to 0
NRF_RADIO->PREFIX1 = 0xC5C6C7C8UL; // Prefix byte of addresses 7 to 4
NRF_RADIO->BASE0 = bytewise_bitswap((uint32_t)address); // Base address for prefix 0
NRF_RADIO->BASE1 = 0x00C2C2C2UL; // Base address for prefix 1-7
NRF_RADIO->TXADDRESS = 0x00UL; // Set device address 0 to use when transmitting
NRF_RADIO->RXADDRESSES = 0x01UL; // Enable device address 0 to use which receiving
// Packet configuration
NRF_RADIO->PCNF0 = (PACKET0_S1_SIZE << RADIO_PCNF0_S1LEN_Pos) |
(PACKET0_S0_SIZE << RADIO_PCNF0_S0LEN_Pos) |
(PACKET0_PAYLOAD_SIZE << RADIO_PCNF0_LFLEN_Pos);
// Packet configuration
NRF_RADIO->PCNF1 = (RADIO_PCNF1_WHITEEN_Disabled << RADIO_PCNF1_WHITEEN_Pos) |
(RADIO_PCNF1_ENDIAN_Big << RADIO_PCNF1_ENDIAN_Pos) |
(PACKET1_BASE_ADDRESS_LENGTH << RADIO_PCNF1_BALEN_Pos) |
(PACKET1_STATIC_LENGTH << RADIO_PCNF1_STATLEN_Pos) |
(PACKET1_PAYLOAD_SIZE << RADIO_PCNF1_MAXLEN_Pos);
// CRC Config
NRF_RADIO->CRCCNF = (RADIO_CRCCNF_LEN_Two << RADIO_CRCCNF_LEN_Pos); // Number of checksum bits
NRF_RADIO->CRCINIT = 0xFFFFUL; // Initial value
NRF_RADIO->CRCPOLY = 0x11021UL; // CRC poly: x^16+x^12^x^5+1
// Enable interrupt for end event
NRF_RADIO->INTENSET = RADIO_INTENSET_END_Msk;
// Set all shorts so that RSSI is measured and only END is required interrupt
NRF_RADIO->SHORTS = RADIO_SHORTS_READY_START_Msk;
NRF_RADIO->SHORTS |= RADIO_SHORTS_ADDRESS_RSSISTART_Msk;
NRF_RADIO->SHORTS |= RADIO_SHORTS_DISABLED_TXEN_Msk;
NRF_RADIO->SHORTS |= RADIO_SHORTS_DISABLED_RSSISTOP_Enabled;
// Set RX buffer and start RX
rs = doRx;
NRF_RADIO->PACKETPTR = (uint32_t)&rxPackets[rxq_head];
NRF_RADIO->TASKS_RXEN = 1U;
isInit = true;
}
void esbReset()
{
if (!isInit) return;
#ifndef BLE
__disable_irq();
#endif
NRF_RADIO->TASKS_DISABLE = 1;
NRF_RADIO->POWER = 0;
NVIC_GetPendingIRQ(RADIO_IRQn);
__enable_irq();
#ifndef BLE
esbInit();
#endif
}
void esbDeinit()
{
#ifndef BLE
NVIC_DisableIRQ(RADIO_IRQn);
#endif
NRF_RADIO->INTENCLR = RADIO_INTENSET_END_Msk;
NRF_RADIO->SHORTS = 0;
NRF_RADIO->TASKS_DISABLE = 1;
NRF_RADIO->POWER = 0;
}
bool esbIsRxPacket()
{
return (rxq_head != rxq_tail);
}
EsbPacket * esbGetRxPacket()
{
EsbPacket *pk = NULL;
if (esbIsRxPacket()) {
pk = &rxPackets[rxq_tail];
}
return pk;
}
void esbReleaseRxPacket()
{
rxq_tail = (rxq_tail+1)%RXQ_LEN;
}
bool esbCanTxPacket()
{
return ((txq_head+1)%TXQ_LEN)!=txq_tail;
}
EsbPacket * esbGetTxPacket()
{
EsbPacket *pk = NULL;
if (esbCanTxPacket()) {
pk = &txPackets[txq_head];
}
return pk;
}
void esbSendTxPacket()
{
txq_head = (txq_head+1)%TXQ_LEN;
}
void esbSetDatarate(EsbDatarate dr)
{
datarate = dr;
esbReset();
}
void ble_advertising_stop(void);
void advertising_start(void);
void esbSetContwave(bool enable)
{
contwave = enable;
#ifdef BLE
if (enable)
ble_advertising_stop();
else
advertising_start();
#endif
esbReset();
}
void esbSetChannel(unsigned int ch)
{
if (channel < 126) {
channel = ch;
}
esbReset();
}
void esbSetTxPower(int power)
{
txpower = power;
esbReset();
}
void esbSetAddress(uint64_t addr)
{
address = addr;
esbReset();
}
| DroneBucket/Drone_Bucket_CrazyFlie2_NRF_Firmware | src/slave/esb.c | C | gpl-3.0 | 11,033 | [
30522,
1013,
1008,
1008,
1008,
1064,
1064,
1035,
1035,
1035,
1035,
1035,
1035,
1035,
1008,
1009,
1011,
1011,
1011,
1011,
1011,
1011,
1009,
1013,
1035,
1035,
1007,
1006,
1035,
1007,
1013,
1035,
1035,
1035,
1035,
1035,
1035,
1035,
1035,
103... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!--
~ Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
~
~ This program is free software; you can redistribute it and/or modify it
~ under the terms of the GNU General Public License as published by the Free
~ Software Foundation; either version 3 of the License, or (at your option)
~ any later version.
~ This program is distributed in the hope that it will be useful, but WITHOUT
~ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
~ FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
~ more details.
~
~ You should have received a copy of the GNU General Public License along
~ with this program; if not, see http://www.gnu.org/licenses/
-->
<html>
<head>
<title>VISAT Help - Reprojection Output Parameters</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" href="../style.css">
</head>
<body>
<table class="header">
<tr class="header">
<td class="header">
Reprojection Output Parameters
</td>
<td class="header" align="right"><a href="index.html">
<img src="../images/SeaDASHeader.png" border=0></a></td>
</tr>
</table>
<h3>Output Parameters</h3>
<table border="0">
<tr>
<td style="border-width:0;" valign="top">
</td>
</tr>
</table>
<p>This dialog lets you specify the position
of the reference pixel and the easting and northing at this pixel of the output product. Also you are able to set
the orientation angle and the pixel size. The orientation angle is the angle between geographic north and map grid
north (in degrees), with other words, the convergence angle of the projection's vertical axis from true north.
Easting and northing and also the pixel size are given in the units of the underlying map (e.g. dec. degree for
geographic and meter for the UTM projection).
</p>
<p>In order to force a certain width and height in pixels for the output product, you must deselect the fit product
size option. Otherwise the size is automatically adjusted, so that the entire source region is included in the new
region.
</p>
<p align="center"><img src="images/ReprojectionOutputParameters.png"></p>
<hr>
</body>
</html> | marpet/seadas | seadas-help/src/main/resources/doc/help/visat/ReprojectionOutputParametersDialog.html | HTML | gpl-3.0 | 2,309 | [
30522,
1026,
999,
1011,
1011,
1066,
9385,
1006,
1039,
1007,
2230,
13899,
5804,
23363,
18289,
1006,
18558,
1030,
13899,
5804,
1011,
23363,
1012,
2139,
1007,
1066,
1066,
2023,
2565,
2003,
2489,
4007,
1025,
2017,
2064,
2417,
2923,
3089,
8569,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* 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 org.apache.tephra.hbase.txprune;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableExistsException;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.tephra.TxConstants;
import org.apache.tephra.hbase.coprocessor.TransactionProcessor;
import org.apache.tephra.txprune.TransactionPruningPlugin;
import org.apache.tephra.util.TxUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* Default implementation of the {@link TransactionPruningPlugin} for HBase.
*
* This plugin determines the prune upper bound for transactional HBase tables that use
* coprocessor {@link TransactionProcessor}.
*
* <h3>State storage:</h3>
*
* This plugin expects the TransactionProcessor to save the prune upper bound for invalid transactions
* after every major compaction of a region. Let's call this <i>(region, prune upper bound)</i>.
* In addition, the plugin also persists the following information on a run at time <i>t</i>
* <ul>
* <li>
* <i>(t, set of regions)</i>: Set of transactional regions at time <i>t</i>.
* Transactional regions are regions of the tables that have the coprocessor TransactionProcessor
* attached to them.
* </li>
* <li>
* <i>(t, inactive transaction bound)</i>: This is the smallest not in-progress transaction that
* will not have writes in any HBase regions that are created after time <i>t</i>.
* This value is determined by the Transaction Service based on the transaction state at time <i>t</i>
* and passed on to the plugin.
* </li>
* </ul>
*
* <h3>Computing prune upper bound:</h3>
*
* In a typical HBase instance, there can be a constant change in the number of regions due to region creations,
* splits and merges. At any given time there can always be a region on which a major compaction has not been run.
* Since the prune upper bound will get recorded for a region only after a major compaction,
* using only the latest set of regions we may not be able to find the
* prune upper bounds for all the current regions. Hence we persist the set of regions that exist at that time
* of each run of the plugin, and use historical region set for time <i>t</i>, <i>t - 1</i>, etc.
* to determine the prune upper bound.
*
* From the regions saved at time <i>t</i>, <i>t - 1</i>, etc.,
* the plugin tries to find the latest <i>(t, set of regions)</i> where all regions have been major compacted,
* i.e, all regions have prune upper bound recorded in <i>(region, prune upper bound)</i>.
* <br/>
* If such a set is found for time <i>t1</i>, the prune upper bound returned by the plugin is the minimum of
* <ul>
* <li>Prune upper bounds of regions in set <i>(t1, set of regions)</i></li>
* <li>Inactive transaction bound from <i>(t1, inactive transaction bound)</i></li>
* </ul>
*
* <p/>
* Above, when we find <i>(t1, set of regions)</i>, there may a region that was created after time <i>t1</i>,
* but has a data write from an invalid transaction that is smaller than the prune upper bounds of all
* regions in <i>(t1, set of regions)</i>. This is possible because <i>(region, prune upper bound)</i> persisted by
* TransactionProcessor is always the latest prune upper bound for a region.
* <br/>
* However a region created after time <i>t1</i> cannot have writes from an invalid transaction that is smaller than
* inactive transaction bound at the time the region was created.
* Since we limit the plugin prune upper bound using <i>(t1, inactive transaction bound)</i>,
* there should be no invalid transactions smaller than the plugin prune upper bound with writes in any
* transactional region of this HBase instance.
*
* <p/>
* Note: If your tables uses a transactional coprocessor other than TransactionProcessor,
* then you may need to write a new plugin to compute prune upper bound for those tables.
*/
@SuppressWarnings("WeakerAccess")
public class HBaseTransactionPruningPlugin implements TransactionPruningPlugin {
public static final Logger LOG = LoggerFactory.getLogger(HBaseTransactionPruningPlugin.class);
protected Configuration conf;
protected Connection connection;
protected DataJanitorState dataJanitorState;
@Override
public void initialize(Configuration conf) throws IOException {
this.conf = conf;
this.connection = ConnectionFactory.createConnection(conf);
final TableName stateTable = TableName.valueOf(conf.get(TxConstants.TransactionPruning.PRUNE_STATE_TABLE,
TxConstants.TransactionPruning.DEFAULT_PRUNE_STATE_TABLE));
LOG.info("Initializing plugin with state table {}", stateTable.getNameWithNamespaceInclAsString());
createPruneTable(stateTable);
this.dataJanitorState = new DataJanitorState(new DataJanitorState.TableSupplier() {
@Override
public Table get() throws IOException {
return connection.getTable(stateTable);
}
});
}
/**
* Determines prune upper bound for the data store as mentioned above.
*/
@Override
public long fetchPruneUpperBound(long time, long inactiveTransactionBound) throws IOException {
LOG.debug("Fetching prune upper bound for time {} and inactive transaction bound {}",
time, inactiveTransactionBound);
if (time < 0 || inactiveTransactionBound < 0) {
return -1;
}
// Get all the current transactional regions
SortedSet<byte[]> transactionalRegions = getTransactionalRegions();
if (!transactionalRegions.isEmpty()) {
LOG.debug("Saving {} transactional regions for time {}", transactionalRegions.size(), time);
dataJanitorState.saveRegionsForTime(time, transactionalRegions);
// Save inactive transaction bound for time as the final step.
// We can then use its existence to make sure that the data for a given time is complete or not
LOG.debug("Saving inactive transaction bound {} for time {}", inactiveTransactionBound, time);
dataJanitorState.saveInactiveTransactionBoundForTime(time, inactiveTransactionBound);
}
return computePruneUpperBound(new TimeRegions(time, transactionalRegions));
}
/**
* After invalid list has been pruned, this cleans up state information that is no longer required.
* This includes -
* <ul>
* <li>
* <i>(region, prune upper bound)</i> - prune upper bound for regions that are older
* than maxPrunedInvalid
* </li>
* <li>
* <i>(t, set of regions) - Regions set that were recorded on or before the start time
* of maxPrunedInvalid
* </li>
* <li>
* (t, inactive transaction bound) - Smallest not in-progress transaction without any writes in new regions
* information recorded on or before the start time of maxPrunedInvalid
* </li>
* </ul>
*/
@Override
public void pruneComplete(long time, long maxPrunedInvalid) throws IOException {
LOG.debug("Prune complete for time {} and prune upper bound {}", time, maxPrunedInvalid);
if (time < 0 || maxPrunedInvalid < 0) {
return;
}
// Get regions for the current time, so as to not delete the prune upper bounds for them.
// The prune upper bounds for regions are recorded by TransactionProcessor and the deletion
// is done by this class. To avoid update/delete race condition, we only delete prune upper
// bounds for the stale regions.
TimeRegions regionsToExclude = dataJanitorState.getRegionsOnOrBeforeTime(time);
if (regionsToExclude != null) {
LOG.debug("Deleting prune upper bounds smaller than {} for stale regions", maxPrunedInvalid);
dataJanitorState.deletePruneUpperBounds(maxPrunedInvalid, regionsToExclude.getRegions());
} else {
LOG.warn("Cannot find saved regions on or before time {}", time);
}
long pruneTime = TxUtils.getTimestamp(maxPrunedInvalid);
LOG.debug("Deleting regions recorded before time {}", pruneTime);
dataJanitorState.deleteAllRegionsOnOrBeforeTime(pruneTime);
LOG.debug("Deleting inactive transaction bounds recorded on or before time {}", pruneTime);
dataJanitorState.deleteInactiveTransactionBoundsOnOrBeforeTime(pruneTime);
LOG.debug("Deleting empty regions recorded on or before time {}", pruneTime);
dataJanitorState.deleteEmptyRegionsOnOrBeforeTime(pruneTime);
}
@Override
public void destroy() {
LOG.info("Stopping plugin...");
try {
connection.close();
} catch (IOException e) {
LOG.error("Got exception while closing HBase connection", e);
}
}
/**
* Create the prune state table given the {@link TableName} if the table doesn't exist already.
*
* @param stateTable prune state table name
*/
protected void createPruneTable(TableName stateTable) throws IOException {
try (Admin admin = this.connection.getAdmin()) {
if (admin.tableExists(stateTable)) {
LOG.debug("Not creating pruneStateTable {} since it already exists.",
stateTable.getNameWithNamespaceInclAsString());
return;
}
HTableDescriptor htd = new HTableDescriptor(stateTable);
htd.addFamily(new HColumnDescriptor(DataJanitorState.FAMILY).setMaxVersions(1));
admin.createTable(htd);
LOG.info("Created pruneTable {}", stateTable.getNameWithNamespaceInclAsString());
} catch (TableExistsException ex) {
// Expected if the prune state table is being created at the same time by another client
LOG.debug("Not creating pruneStateTable {} since it already exists.",
stateTable.getNameWithNamespaceInclAsString(), ex);
}
}
/**
* Returns whether the table is a transactional table. By default, it is a table is identified as a transactional
* table if it has a the coprocessor {@link TransactionProcessor} attached to it. Should be overriden if the users
* attach a different coprocessor.
*
* @param tableDescriptor {@link HTableDescriptor} of the table
* @return true if the table is transactional
*/
protected boolean isTransactionalTable(HTableDescriptor tableDescriptor) {
return tableDescriptor.hasCoprocessor(TransactionProcessor.class.getName());
}
protected SortedSet<byte[]> getTransactionalRegions() throws IOException {
SortedSet<byte[]> regions = new TreeSet<>(Bytes.BYTES_COMPARATOR);
try (Admin admin = connection.getAdmin()) {
HTableDescriptor[] tableDescriptors = admin.listTables();
LOG.debug("Got {} tables to process", tableDescriptors == null ? 0 : tableDescriptors.length);
if (tableDescriptors != null) {
for (HTableDescriptor tableDescriptor : tableDescriptors) {
if (isTransactionalTable(tableDescriptor)) {
List<HRegionInfo> tableRegions = admin.getTableRegions(tableDescriptor.getTableName());
LOG.debug("Regions for table {}: {}", tableDescriptor.getTableName(), tableRegions);
if (tableRegions != null) {
for (HRegionInfo region : tableRegions) {
regions.add(region.getRegionName());
}
}
} else {
LOG.debug("{} is not a transactional table", tableDescriptor.getTableName());
}
}
}
}
return regions;
}
/**
* Try to find the latest set of regions in which all regions have been major compacted, and
* compute prune upper bound from them. Starting from newest to oldest, this looks into the
* region set that has been saved periodically, and joins it with the prune upper bound data
* for a region recorded after a major compaction.
*
* @param timeRegions the latest set of regions
* @return prune upper bound
* @throws IOException when not able to talk to HBase
*/
private long computePruneUpperBound(TimeRegions timeRegions) throws IOException {
do {
LOG.debug("Computing prune upper bound for {}", timeRegions);
SortedSet<byte[]> transactionalRegions = timeRegions.getRegions();
long time = timeRegions.getTime();
long inactiveTransactionBound = dataJanitorState.getInactiveTransactionBoundForTime(time);
LOG.debug("Got inactive transaction bound {}", inactiveTransactionBound);
// If inactiveTransactionBound is not recorded then that means the data is not complete for these regions
if (inactiveTransactionBound == -1) {
if (LOG.isDebugEnabled()) {
LOG.debug("Ignoring regions for time {} as no inactiveTransactionBound was found for that time, " +
"and hence the data must be incomplete", time);
}
continue;
}
// Get the prune upper bounds for all the transactional regions
Map<byte[], Long> pruneUpperBoundRegions =
dataJanitorState.getPruneUpperBoundForRegions(transactionalRegions);
logPruneUpperBoundRegions(pruneUpperBoundRegions);
// Use inactiveTransactionBound as the prune upper bound for the empty regions since the regions that are
// recorded as empty after inactiveTransactionBoundTime will not have invalid data
// for transactions started on or before inactiveTransactionBoundTime
pruneUpperBoundRegions = handleEmptyRegions(inactiveTransactionBound, transactionalRegions,
pruneUpperBoundRegions);
// If prune upper bounds are found for all the transactional regions, then compute the prune upper bound
// across all regions
if (!transactionalRegions.isEmpty() &&
pruneUpperBoundRegions.size() == transactionalRegions.size()) {
Long minPruneUpperBoundRegions = Collections.min(pruneUpperBoundRegions.values());
long pruneUpperBound = Math.min(inactiveTransactionBound, minPruneUpperBoundRegions);
LOG.debug("Found prune upper bound {} for time {}", pruneUpperBound, time);
return pruneUpperBound;
} else {
if (LOG.isDebugEnabled()) {
Sets.SetView<byte[]> difference =
Sets.difference(transactionalRegions, pruneUpperBoundRegions.keySet());
LOG.debug("Ignoring regions for time {} because the following regions did not record a pruneUpperBound: {}",
time, Iterables.transform(difference, TimeRegions.BYTE_ARR_TO_STRING_FN));
}
}
timeRegions = dataJanitorState.getRegionsOnOrBeforeTime(time - 1);
} while (timeRegions != null);
return -1;
}
private Map<byte[], Long> handleEmptyRegions(long inactiveTransactionBound,
SortedSet<byte[]> transactionalRegions,
Map<byte[], Long> pruneUpperBoundRegions) throws IOException {
long inactiveTransactionBoundTime = TxUtils.getTimestamp(inactiveTransactionBound);
SortedSet<byte[]> emptyRegions =
dataJanitorState.getEmptyRegionsAfterTime(inactiveTransactionBoundTime, transactionalRegions);
LOG.debug("Got empty transactional regions for inactive transaction bound time {}: {}",
inactiveTransactionBoundTime, Iterables.transform(emptyRegions, TimeRegions.BYTE_ARR_TO_STRING_FN));
// The regions that are recorded as empty after inactiveTransactionBoundTime will not have invalid data
// for transactions started before or on inactiveTransactionBoundTime. Hence we can consider the prune upper bound
// for these empty regions as inactiveTransactionBound
Map<byte[], Long> pubWithEmptyRegions = new TreeMap<>(Bytes.BYTES_COMPARATOR);
pubWithEmptyRegions.putAll(pruneUpperBoundRegions);
for (byte[] emptyRegion : emptyRegions) {
if (!pruneUpperBoundRegions.containsKey(emptyRegion)) {
pubWithEmptyRegions.put(emptyRegion, inactiveTransactionBound);
}
}
return Collections.unmodifiableMap(pubWithEmptyRegions);
}
private void logPruneUpperBoundRegions(Map<byte[], Long> pruneUpperBoundRegions) {
if (LOG.isDebugEnabled()) {
LOG.debug("Got region - prune upper bound map: {}",
Iterables.transform(pruneUpperBoundRegions.entrySet(),
new Function<Map.Entry<byte[], Long>, Map.Entry<String, Long>>() {
@Override
public Map.Entry<String, Long> apply(Map.Entry<byte[], Long> input) {
String regionName = TimeRegions.BYTE_ARR_TO_STRING_FN.apply(input.getKey());
return Maps.immutableEntry(regionName, input.getValue());
}
}));
}
}
}
| anwar6953/incubator-tephra | tephra-hbase-compat-1.1-base/src/main/java/org/apache/tephra/hbase/txprune/HBaseTransactionPruningPlugin.java | Java | apache-2.0 | 18,153 | [
30522,
1013,
30524,
2028,
1008,
2030,
2062,
12130,
6105,
10540,
1012,
2156,
1996,
5060,
5371,
1008,
5500,
2007,
2023,
2147,
2005,
3176,
2592,
1008,
4953,
9385,
6095,
1012,
1996,
2004,
2546,
15943,
2023,
5371,
1008,
2000,
2017,
2104,
1996,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Copyright (C) 2002-2010 The DOSBox Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/* $Id: cache.h,v 1.20 2009-07-12 20:13:05 c2woody Exp $ */
class CacheBlock {
public:
void Clear(void);
void LinkTo(Bitu index,CacheBlock * toblock) {
assert(toblock);
link[index].to=toblock;
link[index].next=toblock->link[index].from;
toblock->link[index].from=this;
}
struct {
Bit16u start,end; //Where the page is the original code
CodePageHandler * handler; //Page containing this code
} page;
struct {
Bit8u * start; //Where in the cache are we
Bitu size;
CacheBlock * next;
Bit8u * wmapmask;
Bit16u maskstart;
Bit16u masklen;
} cache;
struct {
Bitu index;
CacheBlock * next;
} hash;
struct {
CacheBlock * to;
CacheBlock * next;
CacheBlock * from;
} link[2];
CacheBlock * crossblock;
};
static struct {
struct {
CacheBlock * first;
CacheBlock * active;
CacheBlock * free;
CacheBlock * running;
} block;
Bit8u * pos;
CodePageHandler * free_pages;
CodePageHandler * used_pages;
CodePageHandler * last_page;
} cache;
static CacheBlock link_blocks[2];
class CodePageHandler : public PageHandler {
public:
CodePageHandler() {
invalidation_map=NULL;
}
void SetupAt(Bitu _phys_page,PageHandler * _old_pagehandler) {
phys_page=_phys_page;
old_pagehandler=_old_pagehandler;
flags=old_pagehandler->flags|PFLAG_HASCODE;
flags&=~PFLAG_WRITEABLE;
active_blocks=0;
active_count=16;
memset(&hash_map,0,sizeof(hash_map));
memset(&write_map,0,sizeof(write_map));
if (invalidation_map!=NULL) {
free(invalidation_map);
invalidation_map=NULL;
}
}
bool InvalidateRange(Bitu start,Bitu end) {
Bits index=1+(end>>DYN_HASH_SHIFT);
bool is_current_block=false;
Bit32u ip_point=SegPhys(cs)+reg_eip;
ip_point=(PAGING_GetPhysicalPage(ip_point)-(phys_page<<12))+(ip_point&0xfff);
while (index>=0) {
Bitu map=0;
for (Bitu count=start;count<=end;count++) map+=write_map[count];
if (!map) return is_current_block;
CacheBlock * block=hash_map[index];
while (block) {
CacheBlock * nextblock=block->hash.next;
if (start<=block->page.end && end>=block->page.start) {
if (ip_point<=block->page.end && ip_point>=block->page.start) is_current_block=true;
block->Clear();
}
block=nextblock;
}
index--;
}
return is_current_block;
}
void writeb(PhysPt addr,Bitu val){
if (GCC_UNLIKELY(old_pagehandler->flags&PFLAG_HASROM)) return;
if (GCC_UNLIKELY((old_pagehandler->flags&PFLAG_READABLE)!=PFLAG_READABLE)) {
E_Exit("wb:non-readable code page found that is no ROM page");
}
addr&=4095;
if (host_readb(hostmem+addr)==(Bit8u)val) return;
host_writeb(hostmem+addr,val);
if (!*(Bit8u*)&write_map[addr]) {
if (active_blocks) return;
active_count--;
if (!active_count) Release();
return;
} else if (!invalidation_map) {
invalidation_map=(Bit8u*)malloc(4096);
memset(invalidation_map,0,4096);
}
invalidation_map[addr]++;
InvalidateRange(addr,addr);
}
void writew(PhysPt addr,Bitu val){
if (GCC_UNLIKELY(old_pagehandler->flags&PFLAG_HASROM)) return;
if (GCC_UNLIKELY((old_pagehandler->flags&PFLAG_READABLE)!=PFLAG_READABLE)) {
E_Exit("ww:non-readable code page found that is no ROM page");
}
addr&=4095;
if (host_readw(hostmem+addr)==(Bit16u)val) return;
host_writew(hostmem+addr,val);
if (!*(Bit16u*)&write_map[addr]) {
if (active_blocks) return;
active_count--;
if (!active_count) Release();
return;
} else if (!invalidation_map) {
invalidation_map=(Bit8u*)malloc(4096);
memset(invalidation_map,0,4096);
}
(*(Bit16u*)&invalidation_map[addr])+=0x101;
InvalidateRange(addr,addr+1);
}
void writed(PhysPt addr,Bitu val){
if (GCC_UNLIKELY(old_pagehandler->flags&PFLAG_HASROM)) return;
if (GCC_UNLIKELY((old_pagehandler->flags&PFLAG_READABLE)!=PFLAG_READABLE)) {
E_Exit("wd:non-readable code page found that is no ROM page");
}
addr&=4095;
if (host_readd(hostmem+addr)==(Bit32u)val) return;
host_writed(hostmem+addr,val);
if (!*(Bit32u*)&write_map[addr]) {
if (active_blocks) return;
active_count--;
if (!active_count) Release();
return;
} else if (!invalidation_map) {
invalidation_map=(Bit8u*)malloc(4096);
memset(invalidation_map,0,4096);
}
(*(Bit32u*)&invalidation_map[addr])+=0x1010101;
InvalidateRange(addr,addr+3);
}
bool writeb_checked(PhysPt addr,Bitu val) {
if (GCC_UNLIKELY(old_pagehandler->flags&PFLAG_HASROM)) return false;
if (GCC_UNLIKELY((old_pagehandler->flags&PFLAG_READABLE)!=PFLAG_READABLE)) {
E_Exit("cb:non-readable code page found that is no ROM page");
}
addr&=4095;
if (host_readb(hostmem+addr)==(Bit8u)val) return false;
if (!*(Bit8u*)&write_map[addr]) {
if (!active_blocks) {
active_count--;
if (!active_count) Release();
}
} else {
if (!invalidation_map) {
invalidation_map=(Bit8u*)malloc(4096);
memset(invalidation_map,0,4096);
}
invalidation_map[addr]++;
if (InvalidateRange(addr,addr)) {
cpu.exception.which=SMC_CURRENT_BLOCK;
return true;
}
}
host_writeb(hostmem+addr,val);
return false;
}
bool writew_checked(PhysPt addr,Bitu val) {
if (GCC_UNLIKELY(old_pagehandler->flags&PFLAG_HASROM)) return false;
if (GCC_UNLIKELY((old_pagehandler->flags&PFLAG_READABLE)!=PFLAG_READABLE)) {
E_Exit("cw:non-readable code page found that is no ROM page");
}
addr&=4095;
if (host_readw(hostmem+addr)==(Bit16u)val) return false;
if (!*(Bit16u*)&write_map[addr]) {
if (!active_blocks) {
active_count--;
if (!active_count) Release();
}
} else {
if (!invalidation_map) {
invalidation_map=(Bit8u*)malloc(4096);
memset(invalidation_map,0,4096);
}
(*(Bit16u*)&invalidation_map[addr])+=0x101;
if (InvalidateRange(addr,addr+1)) {
cpu.exception.which=SMC_CURRENT_BLOCK;
return true;
}
}
host_writew(hostmem+addr,val);
return false;
}
bool writed_checked(PhysPt addr,Bitu val) {
if (GCC_UNLIKELY(old_pagehandler->flags&PFLAG_HASROM)) return false;
if (GCC_UNLIKELY((old_pagehandler->flags&PFLAG_READABLE)!=PFLAG_READABLE)) {
E_Exit("cd:non-readable code page found that is no ROM page");
}
addr&=4095;
if (host_readd(hostmem+addr)==(Bit32u)val) return false;
if (!*(Bit32u*)&write_map[addr]) {
if (!active_blocks) {
active_count--;
if (!active_count) Release();
}
} else {
if (!invalidation_map) {
invalidation_map=(Bit8u*)malloc(4096);
memset(invalidation_map,0,4096);
}
(*(Bit32u*)&invalidation_map[addr])+=0x1010101;
if (InvalidateRange(addr,addr+3)) {
cpu.exception.which=SMC_CURRENT_BLOCK;
return true;
}
}
host_writed(hostmem+addr,val);
return false;
}
void AddCacheBlock(CacheBlock * block) {
Bitu index=1+(block->page.start>>DYN_HASH_SHIFT);
block->hash.next=hash_map[index];
block->hash.index=index;
hash_map[index]=block;
block->page.handler=this;
active_blocks++;
}
void AddCrossBlock(CacheBlock * block) {
block->hash.next=hash_map[0];
block->hash.index=0;
hash_map[0]=block;
block->page.handler=this;
active_blocks++;
}
void DelCacheBlock(CacheBlock * block) {
active_blocks--;
active_count=16;
CacheBlock * * where=&hash_map[block->hash.index];
while (*where!=block) {
where=&((*where)->hash.next);
//Will crash if a block isn't found, which should never happen.
}
*where=block->hash.next;
if (GCC_UNLIKELY(block->cache.wmapmask!=NULL)) {
for (Bitu i=block->page.start;i<block->cache.maskstart;i++) {
if (write_map[i]) write_map[i]--;
}
Bitu maskct=0;
for (Bitu i=block->cache.maskstart;i<=block->page.end;i++,maskct++) {
if (write_map[i]) {
if ((maskct>=block->cache.masklen) || (!block->cache.wmapmask[maskct])) write_map[i]--;
}
}
free(block->cache.wmapmask);
block->cache.wmapmask=NULL;
} else {
for (Bitu i=block->page.start;i<=block->page.end;i++) {
if (write_map[i]) write_map[i]--;
}
}
}
void Release(void) {
MEM_SetPageHandler(phys_page,1,old_pagehandler);
PAGING_ClearTLB();
if (prev) prev->next=next;
else cache.used_pages=next;
if (next) next->prev=prev;
else cache.last_page=prev;
next=cache.free_pages;
cache.free_pages=this;
prev=0;
}
void ClearRelease(void) {
for (Bitu index=0;index<(1+DYN_PAGE_HASH);index++) {
CacheBlock * block=hash_map[index];
while (block) {
CacheBlock * nextblock=block->hash.next;
block->page.handler=0; //No need, full clear
block->Clear();
block=nextblock;
}
}
Release();
}
CacheBlock * FindCacheBlock(Bitu start) {
CacheBlock * block=hash_map[1+(start>>DYN_HASH_SHIFT)];
while (block) {
if (block->page.start==start) return block;
block=block->hash.next;
}
return 0;
}
HostPt GetHostReadPt(Bitu phys_page) {
hostmem=old_pagehandler->GetHostReadPt(phys_page);
return hostmem;
}
HostPt GetHostWritePt(Bitu phys_page) {
return GetHostReadPt( phys_page );
}
public:
Bit8u write_map[4096];
Bit8u * invalidation_map;
CodePageHandler * next, * prev;
private:
PageHandler * old_pagehandler;
CacheBlock * hash_map[1+DYN_PAGE_HASH];
Bitu active_blocks;
Bitu active_count;
HostPt hostmem;
Bitu phys_page;
};
static INLINE void cache_addunsedblock(CacheBlock * block) {
block->cache.next=cache.block.free;
cache.block.free=block;
}
static CacheBlock * cache_getblock(void) {
CacheBlock * ret=cache.block.free;
if (!ret) E_Exit("Ran out of CacheBlocks" );
cache.block.free=ret->cache.next;
ret->cache.next=0;
return ret;
}
void CacheBlock::Clear(void) {
Bitu ind;
/* Check if this is not a cross page block */
if (hash.index) for (ind=0;ind<2;ind++) {
CacheBlock * fromlink=link[ind].from;
link[ind].from=0;
while (fromlink) {
CacheBlock * nextlink=fromlink->link[ind].next;
fromlink->link[ind].next=0;
fromlink->link[ind].to=&link_blocks[ind];
fromlink=nextlink;
}
if (link[ind].to!=&link_blocks[ind]) {
CacheBlock * * wherelink=&link[ind].to->link[ind].from;
while (*wherelink != this && *wherelink) {
wherelink = &(*wherelink)->link[ind].next;
}
if(*wherelink)
*wherelink = (*wherelink)->link[ind].next;
else
LOG(LOG_CPU,LOG_ERROR)("Cache anomaly. please investigate");
}
} else
cache_addunsedblock(this);
if (crossblock) {
crossblock->crossblock=0;
crossblock->Clear();
crossblock=0;
}
if (page.handler) {
page.handler->DelCacheBlock(this);
page.handler=0;
}
if (cache.wmapmask){
free(cache.wmapmask);
cache.wmapmask=NULL;
}
}
static CacheBlock * cache_openblock(void) {
CacheBlock * block=cache.block.active;
/* check for enough space in this block */
Bitu size=block->cache.size;
CacheBlock * nextblock=block->cache.next;
if (block->page.handler)
block->Clear();
while (size<CACHE_MAXSIZE) {
if (!nextblock)
goto skipresize;
size+=nextblock->cache.size;
CacheBlock * tempblock=nextblock->cache.next;
if (nextblock->page.handler)
nextblock->Clear();
cache_addunsedblock(nextblock);
nextblock=tempblock;
}
skipresize:
block->cache.size=size;
block->cache.next=nextblock;
cache.pos=block->cache.start;
return block;
}
static void cache_closeblock(void) {
CacheBlock * block=cache.block.active;
block->link[0].to=&link_blocks[0];
block->link[1].to=&link_blocks[1];
block->link[0].from=0;
block->link[1].from=0;
block->link[0].next=0;
block->link[1].next=0;
/* Close the block with correct alignments */
Bitu written=cache.pos-block->cache.start;
if (written>block->cache.size) {
if (!block->cache.next) {
if (written>block->cache.size+CACHE_MAXSIZE) E_Exit("CacheBlock overrun 1 %d",written-block->cache.size);
} else E_Exit("CacheBlock overrun 2 written %d size %d",written,block->cache.size);
} else {
Bitu new_size;
Bitu left=block->cache.size-written;
/* Smaller than cache align then don't bother to resize */
if (left>CACHE_ALIGN) {
new_size=((written-1)|(CACHE_ALIGN-1))+1;
CacheBlock * newblock=cache_getblock();
newblock->cache.start=block->cache.start+new_size;
newblock->cache.size=block->cache.size-new_size;
newblock->cache.next=block->cache.next;
block->cache.next=newblock;
block->cache.size=new_size;
}
}
/* Advance the active block pointer */
if (!block->cache.next) {
// LOG_MSG("Cache full restarting");
cache.block.active=cache.block.first;
} else {
cache.block.active=block->cache.next;
}
}
static INLINE void cache_addb(Bit8u val) {
*cache.pos++=val;
}
static INLINE void cache_addw(Bit16u val) {
*(Bit16u*)cache.pos=val;
cache.pos+=2;
}
static INLINE void cache_addd(Bit32u val) {
*(Bit32u*)cache.pos=val;
cache.pos+=4;
}
static void gen_return(BlockReturn retcode);
static Bit8u * cache_code_start_ptr=NULL;
static Bit8u * cache_code=NULL;
static Bit8u * cache_code_link_blocks=NULL;
static CacheBlock * cache_blocks=NULL;
/* Define temporary pagesize so the MPROTECT case and the regular case share as much code as possible */
#if (C_HAVE_MPROTECT)
#define PAGESIZE_TEMP PAGESIZE
#else
#define PAGESIZE_TEMP 4096
#endif
static bool cache_initialized = false;
static void cache_init(bool enable) {
Bits i;
if (enable) {
if (cache_initialized) return;
cache_initialized = true;
if (cache_blocks == NULL) {
cache_blocks=(CacheBlock*)malloc(CACHE_BLOCKS*sizeof(CacheBlock));
if(!cache_blocks) E_Exit("Allocating cache_blocks has failed");
memset(cache_blocks,0,sizeof(CacheBlock)*CACHE_BLOCKS);
cache.block.free=&cache_blocks[0];
for (i=0;i<CACHE_BLOCKS-1;i++) {
cache_blocks[i].link[0].to=(CacheBlock *)1;
cache_blocks[i].link[1].to=(CacheBlock *)1;
cache_blocks[i].cache.next=&cache_blocks[i+1];
}
}
if (cache_code_start_ptr==NULL) {
#if defined (WIN32)
cache_code_start_ptr=(Bit8u*)VirtualAlloc(0,CACHE_TOTAL+CACHE_MAXSIZE+PAGESIZE_TEMP-1+PAGESIZE_TEMP,
MEM_COMMIT,PAGE_EXECUTE_READWRITE);
if (!cache_code_start_ptr)
cache_code_start_ptr=(Bit8u*)malloc(CACHE_TOTAL+CACHE_MAXSIZE+PAGESIZE_TEMP-1+PAGESIZE_TEMP);
#else
cache_code_start_ptr=(Bit8u*)malloc(CACHE_TOTAL+CACHE_MAXSIZE+PAGESIZE_TEMP-1+PAGESIZE_TEMP);
#endif
if(!cache_code_start_ptr) E_Exit("Allocating dynamic core cache memory failed");
cache_code=(Bit8u*)(((Bitu)cache_code_start_ptr + PAGESIZE_TEMP-1) & ~(PAGESIZE_TEMP-1)); //Bitu is same size as a pointer.
cache_code_link_blocks=cache_code;
cache_code+=PAGESIZE_TEMP;
#if (C_HAVE_MPROTECT)
if(mprotect(cache_code_link_blocks,CACHE_TOTAL+CACHE_MAXSIZE+PAGESIZE_TEMP,PROT_WRITE|PROT_READ|PROT_EXEC))
LOG_MSG("Setting excute permission on the code cache has failed!");
#endif
CacheBlock * block=cache_getblock();
cache.block.first=block;
cache.block.active=block;
block->cache.start=&cache_code[0];
block->cache.size=CACHE_TOTAL;
block->cache.next=0; //Last block in the list
}
/* Setup the default blocks for block linkage returns */
cache.pos=&cache_code_link_blocks[0];
link_blocks[0].cache.start=cache.pos;
gen_return(BR_Link1);
cache.pos=&cache_code_link_blocks[32];
link_blocks[1].cache.start=cache.pos;
gen_return(BR_Link2);
cache.free_pages=0;
cache.last_page=0;
cache.used_pages=0;
/* Setup the code pages */
for (i=0;i<CACHE_PAGES;i++) {
CodePageHandler * newpage=new CodePageHandler();
newpage->next=cache.free_pages;
cache.free_pages=newpage;
}
}
}
static void cache_close(void) {
/* for (;;) {
if (cache.used_pages) {
CodePageHandler * cpage=cache.used_pages;
CodePageHandler * npage=cache.used_pages->next;
cpage->ClearRelease();
delete cpage;
cache.used_pages=npage;
} else break;
}
if (cache_blocks != NULL) {
free(cache_blocks);
cache_blocks = NULL;
}
if (cache_code_start_ptr != NULL) {
### care: under windows VirtualFree() has to be used if
### VirtualAlloc was used for memory allocation
free(cache_code_start_ptr);
cache_code_start_ptr = NULL;
}
cache_code = NULL;
cache_code_link_blocks = NULL;
cache_initialized = false; */
}
static void cache_reset(void) {
if (cache_initialized) {
for (;;) {
if (cache.used_pages) {
CodePageHandler * cpage=cache.used_pages;
CodePageHandler * npage=cache.used_pages->next;
cpage->ClearRelease();
delete cpage;
cache.used_pages=npage;
} else break;
}
if (cache_blocks == NULL) {
cache_blocks=(CacheBlock*)malloc(CACHE_BLOCKS*sizeof(CacheBlock));
if(!cache_blocks) E_Exit("Allocating cache_blocks has failed");
}
memset(cache_blocks,0,sizeof(CacheBlock)*CACHE_BLOCKS);
cache.block.free=&cache_blocks[0];
for (Bits i=0;i<CACHE_BLOCKS-1;i++) {
cache_blocks[i].link[0].to=(CacheBlock *)1;
cache_blocks[i].link[1].to=(CacheBlock *)1;
cache_blocks[i].cache.next=&cache_blocks[i+1];
}
if (cache_code_start_ptr==NULL) {
#if defined (WIN32)
cache_code_start_ptr=(Bit8u*)VirtualAlloc(0,CACHE_TOTAL+CACHE_MAXSIZE+PAGESIZE_TEMP-1+PAGESIZE_TEMP,
MEM_COMMIT,PAGE_EXECUTE_READWRITE);
if (!cache_code_start_ptr)
cache_code_start_ptr=(Bit8u*)malloc(CACHE_TOTAL+CACHE_MAXSIZE+PAGESIZE_TEMP-1+PAGESIZE_TEMP);
#else
cache_code_start_ptr=(Bit8u*)malloc(CACHE_TOTAL+CACHE_MAXSIZE+PAGESIZE_TEMP-1+PAGESIZE_TEMP);
#endif
if (!cache_code_start_ptr) E_Exit("Allocating dynamic core cache memory failed");
cache_code=(Bit8u*)(((Bitu)cache_code_start_ptr + PAGESIZE_TEMP-1) & ~(PAGESIZE_TEMP-1)); //Bitu is same size as a pointer.
cache_code_link_blocks=cache_code;
cache_code+=PAGESIZE_TEMP;
#if (C_HAVE_MPROTECT)
if(mprotect(cache_code_link_blocks,CACHE_TOTAL+CACHE_MAXSIZE+PAGESIZE_TEMP,PROT_WRITE|PROT_READ|PROT_EXEC))
LOG_MSG("Setting excute permission on the code cache has failed!");
#endif
}
CacheBlock * block=cache_getblock();
cache.block.first=block;
cache.block.active=block;
block->cache.start=&cache_code[0];
block->cache.size=CACHE_TOTAL;
block->cache.next=0; //Last block in the list
/* Setup the default blocks for block linkage returns */
cache.pos=&cache_code_link_blocks[0];
link_blocks[0].cache.start=cache.pos;
gen_return(BR_Link1);
cache.pos=&cache_code_link_blocks[32];
link_blocks[1].cache.start=cache.pos;
gen_return(BR_Link2);
cache.free_pages=0;
cache.last_page=0;
cache.used_pages=0;
/* Setup the code pages */
for (Bitu i=0;i<CACHE_PAGES;i++) {
CodePageHandler * newpage=new CodePageHandler();
newpage->next=cache.free_pages;
cache.free_pages=newpage;
}
}
}
| litchie/dospad | dosbox/src/cpu/core_dyn_x86/cache.h | C | gpl-2.0 | 19,107 | [
30522,
1013,
1008,
1008,
9385,
1006,
1039,
1007,
2526,
1011,
2230,
1996,
9998,
8758,
2136,
1008,
1008,
2023,
2565,
2003,
2489,
4007,
1025,
2017,
2064,
2417,
2923,
3089,
8569,
2618,
2009,
1998,
1013,
2030,
19933,
1008,
2009,
2104,
1996,
34... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
require 'optparse'
require 'uri'
require 'puma/server'
require 'puma/const'
require 'puma/configuration'
require 'puma/binder'
require 'puma/detect'
require 'puma/daemon_ext'
require 'puma/util'
require 'puma/single'
require 'puma/cluster'
require 'puma/commonlogger'
module Puma
class << self
# The CLI exports its Puma::Configuration object here to allow
# apps to pick it up. An app needs to use it conditionally though
# since it is not set if the app is launched via another
# mechanism than the CLI class.
attr_accessor :cli_config
end
# Handles invoke a Puma::Server in a command line style.
#
class CLI
# Create a new CLI object using +argv+ as the command line
# arguments.
#
# +stdout+ and +stderr+ can be set to IO-like objects which
# this object will report status on.
#
def initialize(argv, events=Events.stdio)
@debug = false
@argv = argv
@events = events
@status = nil
@runner = nil
@config = nil
ENV['NEWRELIC_DISPATCHER'] ||= "Puma"
setup_options
generate_restart_data
@binder = Binder.new(@events)
@binder.import_from_env
end
# The Binder object containing the sockets bound to.
attr_reader :binder
# The Configuration object used.
attr_reader :config
# The Hash of options used to configure puma.
attr_reader :options
# The Events object used to output information.
attr_reader :events
# Delegate +log+ to +@events+
#
def log(str)
@events.log str
end
# Delegate +error+ to +@events+
#
def error(str)
@events.error str
end
def debug(str)
@events.log "- #{str}" if @options[:debug]
end
def clustered?
@options[:workers] > 0
end
def prune_bundler?
@options[:prune_bundler] && clustered? && !@options[:preload_app]
end
def jruby?
IS_JRUBY
end
def windows?
RUBY_PLATFORM =~ /mswin32|ming32/
end
def env
@options[:environment] || ENV['RACK_ENV'] || 'development'
end
def write_state
write_pid
path = @options[:state]
return unless path
state = { 'pid' => Process.pid }
cfg = @config.dup
[
:logger,
:before_worker_shutdown, :before_worker_boot, :before_worker_fork,
:after_worker_boot,
:on_restart, :lowlevel_error_handler
].each { |k| cfg.options.delete(k) }
state['config'] = cfg
require 'yaml'
File.open(path, 'w') { |f| f.write state.to_yaml }
end
# If configured, write the pid of the current process out
# to a file.
#
def write_pid
path = @options[:pidfile]
return unless path
File.open(path, 'w') { |f| f.puts Process.pid }
cur = Process.pid
at_exit do
delete_pidfile if cur == Process.pid
end
end
def delete_pidfile
path = @options[:pidfile]
File.unlink(path) if path && File.exist?(path)
end
def graceful_stop
@runner.stop_blocked
log "=== puma shutdown: #{Time.now} ==="
log "- Goodbye!"
end
def jruby_daemon_start
require 'puma/jruby_restart'
JRubyRestart.daemon_start(@restart_dir, restart_args)
end
def restart!
@options[:on_restart].each do |block|
block.call self
end
if jruby?
close_binder_listeners
require 'puma/jruby_restart'
JRubyRestart.chdir_exec(@restart_dir, restart_args)
elsif windows?
close_binder_listeners
argv = restart_args
Dir.chdir(@restart_dir)
argv += [redirects] if RUBY_VERSION >= '1.9'
Kernel.exec(*argv)
else
redirects = {:close_others => true}
@binder.listeners.each_with_index do |(l, io), i|
ENV["PUMA_INHERIT_#{i}"] = "#{io.to_i}:#{l}"
redirects[io.to_i] = io.to_i
end
argv = restart_args
Dir.chdir(@restart_dir)
argv += [redirects] if RUBY_VERSION >= '1.9'
Kernel.exec(*argv)
end
end
# Parse the options, load the rackup, start the server and wait
# for it to finish.
#
def run
begin
parse_options
rescue UnsupportedOption
exit 1
end
dir = @options[:directory]
Dir.chdir(dir) if dir
prune_bundler if prune_bundler?
set_rack_environment
if clustered?
@events.formatter = Events::PidFormatter.new
@options[:logger] = @events
@runner = Cluster.new(self)
else
@runner = Single.new(self)
end
setup_signals
set_process_title
@status = :run
@runner.run
case @status
when :halt
log "* Stopping immediately!"
when :run, :stop
graceful_stop
when :restart
log "* Restarting..."
@runner.before_restart
restart!
when :exit
# nothing
end
end
def stop
@status = :stop
@runner.stop
end
def restart
@status = :restart
@runner.restart
end
def reload_worker_directory
@runner.reload_worker_directory if @runner.respond_to?(:reload_worker_directory)
end
def phased_restart
unless @runner.respond_to?(:phased_restart) and @runner.phased_restart
log "* phased-restart called but not available, restarting normally."
return restart
end
true
end
def redirect_io
@runner.redirect_io
end
def stats
@runner.stats
end
def halt
@status = :halt
@runner.halt
end
private
def title
buffer = "puma #{Puma::Const::VERSION} (#{@options[:binds].join(',')})"
buffer << " [#{@options[:tag]}]" if @options[:tag]
buffer
end
def unsupported(str)
@events.error(str)
raise UnsupportedOption
end
def restart_args
cmd = @options[:restart_cmd]
if cmd
cmd.split(' ') + @original_argv
else
@restart_argv
end
end
def set_process_title
Process.respond_to?(:setproctitle) ? Process.setproctitle(title) : $0 = title
end
def find_config
if @options[:config_file] == '-'
@options[:config_file] = nil
else
@options[:config_file] ||= %W(config/puma/#{env}.rb config/puma.rb).find { |f| File.exist?(f) }
end
end
# Build the OptionParser object to handle the available options.
#
def setup_options
@options = {
:min_threads => 0,
:max_threads => 16,
:quiet => false,
:debug => false,
:binds => [],
:workers => 0,
:daemon => false,
:before_worker_shutdown => [],
:before_worker_boot => [],
:before_worker_fork => [],
:after_worker_boot => []
}
@parser = OptionParser.new do |o|
o.on "-b", "--bind URI", "URI to bind to (tcp://, unix://, ssl://)" do |arg|
@options[:binds] << arg
end
o.on "-C", "--config PATH", "Load PATH as a config file" do |arg|
@options[:config_file] = arg
end
o.on "--control URL", "The bind url to use for the control server",
"Use 'auto' to use temp unix server" do |arg|
if arg
@options[:control_url] = arg
elsif jruby?
unsupported "No default url available on JRuby"
end
end
o.on "--control-token TOKEN",
"The token to use as authentication for the control server" do |arg|
@options[:control_auth_token] = arg
end
o.on "-d", "--daemon", "Daemonize the server into the background" do
@options[:daemon] = true
@options[:quiet] = true
end
o.on "--debug", "Log lowlevel debugging information" do
@options[:debug] = true
end
o.on "--dir DIR", "Change to DIR before starting" do |d|
@options[:directory] = d.to_s
@options[:worker_directory] = d.to_s
end
o.on "-e", "--environment ENVIRONMENT",
"The environment to run the Rack app on (default development)" do |arg|
@options[:environment] = arg
end
o.on "-I", "--include PATH", "Specify $LOAD_PATH directories" do |arg|
$LOAD_PATH.unshift(*arg.split(':'))
end
o.on "-p", "--port PORT", "Define the TCP port to bind to",
"Use -b for more advanced options" do |arg|
@options[:binds] << "tcp://#{Configuration::DefaultTCPHost}:#{arg}"
end
o.on "--pidfile PATH", "Use PATH as a pidfile" do |arg|
@options[:pidfile] = arg
end
o.on "--preload", "Preload the app. Cluster mode only" do
@options[:preload_app] = true
end
o.on "--prune-bundler", "Prune out the bundler env if possible" do
@options[:prune_bundler] = true
end
o.on "-q", "--quiet", "Quiet down the output" do
@options[:quiet] = true
end
o.on "-R", "--restart-cmd CMD",
"The puma command to run during a hot restart",
"Default: inferred" do |cmd|
@options[:restart_cmd] = cmd
end
o.on "-S", "--state PATH", "Where to store the state details" do |arg|
@options[:state] = arg
end
o.on '-t', '--threads INT', "min:max threads to use (default 0:16)" do |arg|
min, max = arg.split(":")
if max
@options[:min_threads] = min
@options[:max_threads] = max
else
@options[:min_threads] = 0
@options[:max_threads] = arg
end
end
o.on "--tcp-mode", "Run the app in raw TCP mode instead of HTTP mode" do
@options[:mode] = :tcp
end
o.on "-V", "--version", "Print the version information" do
puts "puma version #{Puma::Const::VERSION}"
exit 0
end
o.on "-w", "--workers COUNT",
"Activate cluster mode: How many worker processes to create" do |arg|
@options[:workers] = arg.to_i
end
o.on "--tag NAME", "Additional text to display in process listing" do |arg|
@options[:tag] = arg
end
o.banner = "puma <options> <rackup file>"
o.on_tail "-h", "--help", "Show help" do
log o
exit 0
end
end
end
def generate_restart_data
# Use the same trick as unicorn, namely favor PWD because
# it will contain an unresolved symlink, useful for when
# the pwd is /data/releases/current.
if dir = ENV['PWD']
s_env = File.stat(dir)
s_pwd = File.stat(Dir.pwd)
if s_env.ino == s_pwd.ino and (jruby? or s_env.dev == s_pwd.dev)
@restart_dir = dir
@options[:worker_directory] = dir
end
end
@restart_dir ||= Dir.pwd
@original_argv = @argv.dup
require 'rubygems'
# if $0 is a file in the current directory, then restart
# it the same, otherwise add -S on there because it was
# picked up in PATH.
#
if File.exist?($0)
arg0 = [Gem.ruby, $0]
else
arg0 = [Gem.ruby, "-S", $0]
end
# Detect and reinject -Ilib from the command line
lib = File.expand_path "lib"
arg0[1,0] = ["-I", lib] if $:[0] == lib
if defined? Puma::WILD_ARGS
@restart_argv = arg0 + Puma::WILD_ARGS + @original_argv
else
@restart_argv = arg0 + @original_argv
end
end
def set_rack_environment
@options[:environment] = env
ENV['RACK_ENV'] = env
end
def setup_signals
begin
Signal.trap "SIGUSR2" do
restart
end
rescue Exception
log "*** SIGUSR2 not implemented, signal based restart unavailable!"
end
begin
Signal.trap "SIGUSR1" do
phased_restart
end
rescue Exception
log "*** SIGUSR1 not implemented, signal based restart unavailable!"
end
begin
Signal.trap "SIGTERM" do
stop
end
rescue Exception
log "*** SIGTERM not implemented, signal based gracefully stopping unavailable!"
end
begin
Signal.trap "SIGHUP" do
redirect_io
end
rescue Exception
log "*** SIGHUP not implemented, signal based logs reopening unavailable!"
end
if jruby?
Signal.trap("INT") do
@status = :exit
graceful_stop
exit
end
end
end
def close_binder_listeners
@binder.listeners.each do |l, io|
io.close
uri = URI.parse(l)
next unless uri.scheme == 'unix'
File.unlink("#{uri.host}#{uri.path}")
end
end
def parse_options
@parser.parse! @argv
@options[:rackup] = @argv.shift if @argv.last
find_config
@config = Puma::Configuration.new @options
# Advertise the Configuration
Puma.cli_config = @config
@config.load
if clustered? && (jruby? || windows?)
unsupported 'worker mode not supported on JRuby or Windows'
end
if @options[:daemon] && windows?
unsupported 'daemon mode not supported on Windows'
end
end
def prune_bundler
return unless defined?(Bundler)
puma = Bundler.rubygems.loaded_specs("puma")
dirs = puma.require_paths.map { |x| File.join(puma.full_gem_path, x) }
puma_lib_dir = dirs.detect { |x| File.exist? File.join(x, '../bin/puma-wild') }
unless puma_lib_dir
log "! Unable to prune Bundler environment, continuing"
return
end
deps = puma.runtime_dependencies.map do |d|
spec = Bundler.rubygems.loaded_specs(d.name)
"#{d.name}:#{spec.version.to_s}"
end
log '* Pruning Bundler environment'
home = ENV['GEM_HOME']
Bundler.with_clean_env do
ENV['GEM_HOME'] = home
wild = File.expand_path(File.join(puma_lib_dir, "../bin/puma-wild"))
args = [Gem.ruby, wild, '-I', dirs.join(':'), deps.join(',')] + @original_argv
Kernel.exec(*args)
end
end
end
end
| praveenperera/qrideshare | vendor/cache/ruby/2.2.0/gems/puma-2.12.0/lib/puma/cli.rb | Ruby | mit | 14,321 | [
30522,
5478,
1005,
23569,
19362,
3366,
1005,
5478,
1005,
24471,
2072,
1005,
5478,
1005,
16405,
2863,
1013,
8241,
1005,
5478,
1005,
16405,
2863,
1013,
9530,
3367,
1005,
5478,
1005,
16405,
2863,
1013,
9563,
1005,
5478,
1005,
16405,
2863,
1013... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Copyright (C) 2008 The Guava 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 com.google.common.collect;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;
/**
* A {@link ListMultimap} whose contents will never change, with many other important properties
* detailed at {@link ImmutableCollection}.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/ImmutableCollectionsExplained"> immutable collections</a>.
*
* @author Jared Levy
* @since 2.0
*/
@GwtCompatible(serializable = true, emulated = true)
public class ImmutableListMultimap<K, V> extends ImmutableMultimap<K, V>
implements ListMultimap<K, V> {
/** Returns the empty multimap. */
// Casting is safe because the multimap will never hold any elements.
@SuppressWarnings("unchecked")
public static <K, V> ImmutableListMultimap<K, V> of() {
return (ImmutableListMultimap<K, V>) EmptyImmutableListMultimap.INSTANCE;
}
/** Returns an immutable multimap containing a single entry. */
public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1) {
ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder();
builder.put(k1, v1);
return builder.build();
}
/** Returns an immutable multimap containing the given entries, in order. */
public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1, K k2, V v2) {
ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
return builder.build();
}
/** Returns an immutable multimap containing the given entries, in order. */
public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
builder.put(k3, v3);
return builder.build();
}
/** Returns an immutable multimap containing the given entries, in order. */
public static <K, V> ImmutableListMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
builder.put(k3, v3);
builder.put(k4, v4);
return builder.build();
}
/** Returns an immutable multimap containing the given entries, in order. */
public static <K, V> ImmutableListMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
builder.put(k3, v3);
builder.put(k4, v4);
builder.put(k5, v5);
return builder.build();
}
// looking for of() with > 5 entries? Use the builder instead.
/**
* Returns a new builder. The generated builder is equivalent to the builder created by the {@link
* Builder} constructor.
*/
public static <K, V> Builder<K, V> builder() {
return new Builder<>();
}
/**
* A builder for creating immutable {@code ListMultimap} instances, especially {@code public
* static final} multimaps ("constant multimaps"). Example:
*
* <pre>{@code
* static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
* new ImmutableListMultimap.Builder<String, Integer>()
* .put("one", 1)
* .putAll("several", 1, 2, 3)
* .putAll("many", 1, 2, 3, 4, 5)
* .build();
* }</pre>
*
* <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
* multiple multimaps in series. Each multimap contains the key-value mappings in the previously
* created multimaps.
*
* @since 2.0
*/
public static final class Builder<K, V> extends ImmutableMultimap.Builder<K, V> {
/**
* Creates a new builder. The returned builder is equivalent to the builder generated by {@link
* ImmutableListMultimap#builder}.
*/
public Builder() {}
@CanIgnoreReturnValue
@Override
public Builder<K, V> put(K key, V value) {
super.put(key, value);
return this;
}
/**
* {@inheritDoc}
*
* @since 11.0
*/
@CanIgnoreReturnValue
@Override
public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
super.put(entry);
return this;
}
/**
* {@inheritDoc}
*
* @since 19.0
*/
@CanIgnoreReturnValue
@Beta
@Override
public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
super.putAll(entries);
return this;
}
@CanIgnoreReturnValue
@Override
public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
super.putAll(key, values);
return this;
}
@CanIgnoreReturnValue
@Override
public Builder<K, V> putAll(K key, V... values) {
super.putAll(key, values);
return this;
}
@CanIgnoreReturnValue
@Override
public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) {
super.putAll(multimap);
return this;
}
/**
* {@inheritDoc}
*
* @since 8.0
*/
@CanIgnoreReturnValue
@Override
public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
super.orderKeysBy(keyComparator);
return this;
}
/**
* {@inheritDoc}
*
* @since 8.0
*/
@CanIgnoreReturnValue
@Override
public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
super.orderValuesBy(valueComparator);
return this;
}
/** Returns a newly-created immutable list multimap. */
@Override
public ImmutableListMultimap<K, V> build() {
return (ImmutableListMultimap<K, V>) super.build();
}
}
/**
* Returns an immutable multimap containing the same mappings as {@code multimap}. The generated
* multimap's key and value orderings correspond to the iteration ordering of the {@code
* multimap.asMap()} view.
*
* <p>Despite the method name, this method attempts to avoid actually copying the data when it is
* safe to do so. The exact circumstances under which a copy will or will not be performed are
* undocumented and subject to change.
*
* @throws NullPointerException if any key or value in {@code multimap} is null
*/
public static <K, V> ImmutableListMultimap<K, V> copyOf(
Multimap<? extends K, ? extends V> multimap) {
if (multimap.isEmpty()) {
return of();
}
// TODO(lowasser): copy ImmutableSetMultimap by using asList() on the sets
if (multimap instanceof ImmutableListMultimap) {
@SuppressWarnings("unchecked") // safe since multimap is not writable
ImmutableListMultimap<K, V> kvMultimap = (ImmutableListMultimap<K, V>) multimap;
if (!kvMultimap.isPartialView()) {
return kvMultimap;
}
}
return fromMapEntries(multimap.asMap().entrySet(), null);
}
/** Creates an ImmutableListMultimap from an asMap.entrySet. */
static <K, V> ImmutableListMultimap<K, V> fromMapEntries(
Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries,
@NullableDecl Comparator<? super V> valueComparator) {
if (mapEntries.isEmpty()) {
return of();
}
ImmutableMap.Builder<K, ImmutableList<V>> builder =
new ImmutableMap.Builder<>(mapEntries.size());
int size = 0;
for (Entry<? extends K, ? extends Collection<? extends V>> entry : mapEntries) {
K key = entry.getKey();
Collection<? extends V> values = entry.getValue();
ImmutableList<V> list =
(valueComparator == null)
? ImmutableList.copyOf(values)
: ImmutableList.sortedCopyOf(valueComparator, values);
if (!list.isEmpty()) {
builder.put(key, list);
size += list.size();
}
}
return new ImmutableListMultimap<>(builder.build(), size);
}
/**
* Returns an immutable multimap containing the specified entries. The returned multimap iterates
* over keys in the order they were first encountered in the input, and the values for each key
* are iterated in the order they were encountered.
*
* @throws NullPointerException if any key, value, or entry is null
* @since 19.0
*/
@Beta
public static <K, V> ImmutableListMultimap<K, V> copyOf(
Iterable<? extends Entry<? extends K, ? extends V>> entries) {
return new Builder<K, V>().putAll(entries).build();
}
ImmutableListMultimap(ImmutableMap<K, ImmutableList<V>> map, int size) {
super(map, size);
}
// views
/**
* Returns an immutable list of the values for the given key. If no mappings in the multimap have
* the provided key, an empty immutable list is returned. The values are in the same order as the
* parameters used to build this multimap.
*/
@Override
public ImmutableList<V> get(@NullableDecl K key) {
// This cast is safe as its type is known in constructor.
ImmutableList<V> list = (ImmutableList<V>) map.get(key);
return (list == null) ? ImmutableList.<V>of() : list;
}
@LazyInit @RetainedWith private transient ImmutableListMultimap<V, K> inverse;
/**
* {@inheritDoc}
*
* <p>Because an inverse of a list multimap can contain multiple pairs with the same key and
* value, this method returns an {@code ImmutableListMultimap} rather than the {@code
* ImmutableMultimap} specified in the {@code ImmutableMultimap} class.
*
* @since 11.0
*/
@Override
public ImmutableListMultimap<V, K> inverse() {
ImmutableListMultimap<V, K> result = inverse;
return (result == null) ? (inverse = invert()) : result;
}
private ImmutableListMultimap<V, K> invert() {
Builder<V, K> builder = builder();
for (Entry<K, V> entry : entries()) {
builder.put(entry.getValue(), entry.getKey());
}
ImmutableListMultimap<V, K> invertedMultimap = builder.build();
invertedMultimap.inverse = this;
return invertedMultimap;
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
public ImmutableList<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
public ImmutableList<V> replaceValues(K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
/**
* @serialData number of distinct keys, and then for each distinct key: the key, the number of
* values for that key, and the key's values
*/
@GwtIncompatible // java.io.ObjectOutputStream
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
Serialization.writeMultimap(this, stream);
}
@GwtIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int keyCount = stream.readInt();
if (keyCount < 0) {
throw new InvalidObjectException("Invalid key count " + keyCount);
}
ImmutableMap.Builder<Object, ImmutableList<Object>> builder = ImmutableMap.builder();
int tmpSize = 0;
for (int i = 0; i < keyCount; i++) {
Object key = stream.readObject();
int valueCount = stream.readInt();
if (valueCount <= 0) {
throw new InvalidObjectException("Invalid value count " + valueCount);
}
ImmutableList.Builder<Object> valuesBuilder = ImmutableList.builder();
for (int j = 0; j < valueCount; j++) {
valuesBuilder.add(stream.readObject());
}
builder.put(key, valuesBuilder.build());
tmpSize += valueCount;
}
ImmutableMap<Object, ImmutableList<Object>> tmpMap;
try {
tmpMap = builder.build();
} catch (IllegalArgumentException e) {
throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
}
FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
}
@GwtIncompatible // Not needed in emulated source
private static final long serialVersionUID = 0;
}
| berndhopp/guava | android/guava/src/com/google/common/collect/ImmutableListMultimap.java | Java | apache-2.0 | 13,676 | [
30522,
1013,
1008,
1008,
9385,
1006,
1039,
1007,
2263,
1996,
19739,
12462,
6048,
1008,
1008,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
1012,
1014,
1006,
1996,
1000,
6105,
1000,
1007,
1025,
1008,
2017,
2089,
2025,
2224,
2023,
5371,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
using System;
using System.Collections.Generic;
using Roguelike.Core.Elements.Inventory;
using Roguelike.Entities;
using RLNET;
namespace Roguelike.Systems {
public class InventorySystem {
private Player player;
public InventorySystem() {
player = Game.Player;
}
void SelectEquipment(Equipment pressedOn) {
if (pressedOn.GetType() == typeof(HeadEquipment)) {
SelectHeadEquipment((HeadEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(BodyEquipment)) {
SelectBodyEquipment((BodyEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(ArmEquipment)) {
SelectArmEquipment((ArmEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(LegEquipment)) {
SelectLegEquipment((LegEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(HandEquipment)) {
SelectHandEquipment((HandEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(FeetEquipment)) {
SelectFeetEquipment((FeetEquipment)pressedOn);
}
Game.Render();
}
void DiscardEquipment(Equipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
Game.Render();
}
void SelectHeadEquipment(HeadEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if(player.Head != null && player.Head != HeadEquipment.None()) {
player.AddEquipment(player.Head);
}
player.Head = pressedOn;
}
void SelectBodyEquipment(BodyEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Body != null && player.Body != BodyEquipment.None()) {
player.AddEquipment(player.Body);
}
player.Body = pressedOn;
}
void SelectArmEquipment(ArmEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Arms != null && player.Arms != ArmEquipment.None()) {
player.AddEquipment(player.Arms);
}
player.Arms = pressedOn;
}
void SelectLegEquipment(LegEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Legs != null && player.Legs != LegEquipment.None()) {
player.AddEquipment(player.Legs);
}
player.Legs = pressedOn;
}
void SelectHandEquipment(HandEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Hands != null && player.Hands != HandEquipment.None()) {
player.AddEquipment(player.Hands);
}
player.Hands = pressedOn;
}
void SelectFeetEquipment(FeetEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Feet != null && player.Feet != FeetEquipment.None()) {
player.AddEquipment(player.Feet);
}
player.Feet = pressedOn;
}
public Equipment EquipArmourFromInventory(int x, int y) {
for (int i = 0; i < player.equipmentInInventory.Count; i++) {
int lengthOfString = player.equipmentInInventory[i].Name.Length;
int numberOfLines = 0;
if(lengthOfString >= 20) {
numberOfLines = 2;
} else {
numberOfLines = 1;
}
int xStartPosition = 0;
int yPosition = (3 * i) + 3;
if(i < 6) {
xStartPosition = 22;
} else {
yPosition = (3 * i) - 15;
xStartPosition = 44;
}
if(numberOfLines == 1) {
if(x >= xStartPosition && x < xStartPosition + lengthOfString && y == yPosition) {
SelectEquipment(player.equipmentInInventory[i]);
}
}else if(numberOfLines == 2) {
string topString = TopLine(player.equipmentInInventory[i].Name);
string bottomString = BottomLine(player.equipmentInInventory[i].Name, topString);
if(y == yPosition) {
if(x >= xStartPosition && x < xStartPosition + topString.Length - 1) {
SelectEquipment(player.equipmentInInventory[i]);
}
} else if(y == yPosition + 1) {
if (x >= xStartPosition && x < xStartPosition + bottomString.Length) {
SelectEquipment(player.equipmentInInventory[i]);
}
}
}
}
return null;
}
public void DiscardArmourFromInventory(int x, int y) {
for (int i = 0; i < player.equipmentInInventory.Count; i++) {
int lengthOfString = player.equipmentInInventory[i].Name.Length;
int numberOfLines = 0;
if (lengthOfString >= 20) {
numberOfLines = 2;
} else {
numberOfLines = 1;
}
int xStartPosition = 0;
int yPosition = (3 * i) + 3;
if (i < 6) {
xStartPosition = 22;
} else {
yPosition = (3 * i) - 15;
xStartPosition = 44;
}
if (numberOfLines == 1) {
if (x >= xStartPosition && x < xStartPosition + lengthOfString && y == yPosition) {
DiscardEquipment(player.equipmentInInventory[i]);
}
} else if (numberOfLines == 2) {
string topString = TopLine(player.equipmentInInventory[i].Name);
string bottomString = BottomLine(player.equipmentInInventory[i].Name, topString);
if (y == yPosition) {
if (x >= xStartPosition && x < xStartPosition + topString.Length - 1) {
DiscardEquipment(player.equipmentInInventory[i]);
}
} else if (y == yPosition + 1) {
if (x >= xStartPosition && x < xStartPosition + bottomString.Length) {
DiscardEquipment(player.equipmentInInventory[i]);
}
}
}
}
}
public void RemoveEquipment(int x, int y) {
if (y == 3) {
if (x >= 1 && x <= 14) {
HeadEquipment toRemove = player.Head;
player.Head = HeadEquipment.None();
player.equipmentInInventory.Add(toRemove);
} else if (x > 14 && x < 28) {
LegEquipment toRemove = player.Legs;
player.Legs = LegEquipment.None();
player.equipmentInInventory.Add(toRemove);
}
} else if (y == 5) {
if (x >= 1 && x <= 14) {
BodyEquipment toRemove = player.Body;
player.Body = BodyEquipment.None();
player.equipmentInInventory.Add(toRemove);
} else if (x > 14 && x < 28) {
HandEquipment toRemove = player.Hands;
player.Hands = HandEquipment.None();
player.equipmentInInventory.Add(toRemove);
}
} else if (y == 7) {
if (x >= 1 && x <= 14) {
ArmEquipment toRemove = player.Arms;
player.Arms = ArmEquipment.None();
player.equipmentInInventory.Add(toRemove);
} else if (x > 14 && x < 28) {
FeetEquipment toRemove = player.Feet;
player.Feet = FeetEquipment.None();
player.equipmentInInventory.Add(toRemove);
}
}
Game.Render();
}
public Equipment RemoveCurrentArmour(int x, int y) {
if(y == 3 || y == 4) {
ClickedOnHead(x, y);
} else if(y == 6 || y == 7) {
ClickedOnBody(x, y);
} else if (y == 9 || y == 10) {
ClickedOnArms(x, y);
} else if (y == 12 || y == 13) {
ClickedOnLegs(x, y);
} else if (y == 15 || y == 16) {
ClickedOnHands(x, y);
} else if (y == 18 || y == 19) {
ClickedOnFeet(x, y);
}
return null;
}
private void ClickedOnHead(int x, int y) {
string topLine = TopLine("Head: " + player.Head.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Head: " + player.Head.Name, topLine);
} catch {
}
if (y == 4) {
if (bottomLine != "") {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Head);
}
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Head);
}
}
}
public void ClickedOnBody(int x, int y) {
string topLine = TopLine("Body: " + player.Body.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Body: " + player.Body.Name, topLine);
} catch {
}
if (y == 7) {
if (bottomLine != "") {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Body);
}
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Body);
}
}
}
public void ClickedOnArms(int x, int y) {
string topLine = TopLine("Arms: " + player.Arms.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Arms: " + player.Arms.Name, topLine);
} catch {
}
if (y == 10) {
if (bottomLine != "") {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Arms);
}
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Arms);
}
}
}
public void ClickedOnLegs(int x, int y) {
string topLine = TopLine("Legs: " + player.Legs.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Legs: " + player.Legs.Name, topLine);
} catch {
}
if (y == 13) {
if (bottomLine != "") {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Legs);
}
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Legs);
}
}
}
public void ClickedOnHands(int x, int y) {
string topLine = TopLine("Hands: " + player.Hands.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Hands: " + player.Hands.Name, topLine);
} catch {
}
if (y == 16) {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Hands);
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Hands);
}
}
}
private void ClickedOnFeet(int x, int y) {
string topLine = TopLine("Feet: " + player.Feet.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Feet: " + player.Feet.Name, topLine);
} catch {
}
if (y == 19) {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Feet);
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Feet);
}
}
}
public bool DidClickOnString(int x, int y, bool secondLine,string topLine, string bottomLine = "") {
int xStartPosition = 1;
int topXEndPosition = xStartPosition + topLine.Length;
int bottomXEndPosition = xStartPosition + bottomLine.Length;
if (bottomLine != "") {
if (secondLine) {
if (x >= xStartPosition && x <= bottomXEndPosition) {
return true;
} else {
return false;
}
} else {
if (x >= xStartPosition && x <= topXEndPosition) {
return true;
} else {
return false;
}
}
} else {
if(x >= xStartPosition && x <= topXEndPosition) {
return true;
} else {
return false;
}
}
}
private void UnequipArmour(Equipment toUnequip) {
if (toUnequip.GetType() == typeof(HeadEquipment) && toUnequip != HeadEquipment.None()) {
UnSelectHeadEquipment((HeadEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(BodyEquipment) && toUnequip != BodyEquipment.None()) {
UnSelectBodyEquipment((BodyEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(ArmEquipment) && toUnequip != ArmEquipment.None()) {
UnSelectArmEquipment((ArmEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(LegEquipment) && toUnequip != LegEquipment.None()) {
UnSelectLegEquipment((LegEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(HandEquipment) && toUnequip != HandEquipment.None()) {
UnSelectHandEquipment((HandEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(FeetEquipment) && toUnequip != FeetEquipment.None()) {
UnSelectFeetEquipment((FeetEquipment)toUnequip);
}
Game.Render();
}
private void UnSelectHeadEquipment(HeadEquipment toUnequip) {
if(player.equipmentInInventory.Count < 12) {
player.Head = HeadEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectBodyEquipment(BodyEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Body = BodyEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectArmEquipment(ArmEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Arms = ArmEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectLegEquipment(LegEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Legs = LegEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectHandEquipment(HandEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Hands = HandEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectFeetEquipment(FeetEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Feet = FeetEquipment.None();
player.AddEquipment(toUnequip);
}
}
private string TopLine(string totalString, int wrapLength = 18) {
List<string> wordsInString = new List<string>();
string currentString = "";
for (int i = 0; i < totalString.Length; i++) {
char character = totalString[i];
if (character == ' ') {
wordsInString.Add(currentString);
currentString = "";
}else if(i == totalString.Length - 1) {
currentString += character;
wordsInString.Add(currentString);
currentString = "";
} else {
currentString += character;
}
}
int lengthSoFar = 0;
string topLine = "";
for (int i = 0; i < wordsInString.Count; i++) {
if (lengthSoFar + wordsInString[i].Length >= wrapLength) {
break;
}
lengthSoFar += wordsInString[i].Length;
topLine += wordsInString[i];
topLine += " ";
}
return topLine;
}
private string BottomLine(string totalString, string topLine) {
string bottom = totalString;
bottom = bottom.Substring(topLine.Length);
return bottom;
}
}
}
| SamFergie/Roguelike | Roguelike/Systems/InventorySystem.cs | C# | mit | 18,045 | [
30522,
2478,
2291,
1025,
2478,
2291,
1012,
6407,
1012,
12391,
1025,
2478,
12406,
10359,
1012,
4563,
1012,
3787,
1012,
12612,
1025,
2478,
12406,
10359,
1012,
11422,
1025,
2478,
1054,
19666,
3388,
1025,
3415,
15327,
12406,
10359,
1012,
3001,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
from django.conf.urls import url
from externals.views import (
PartnerVendorNumberAPIView,
PartnerExternalDetailsAPIView,
PartnerBasicInfoAPIView,
)
urlpatterns = [
url(r'^vendor-number/partner/$', PartnerVendorNumberAPIView.as_view(), name="vendor-number-create"),
url(r'^vendor-number/partner/(?P<pk>\d+)/$', PartnerVendorNumberAPIView.as_view(), name="vendor-number-details"),
url(
r'^partner-details/(?P<agency_id>\d+)/(?P<partner_id>\d+)/$',
PartnerExternalDetailsAPIView.as_view(),
name="partner-external-details"
),
url(
r'^partner-basic-info/$',
PartnerBasicInfoAPIView.as_view(),
name="partner-basic-info"
),
]
| unicef/un-partner-portal | backend/unpp_api/apps/externals/urls.py | Python | apache-2.0 | 707 | [
30522,
2013,
6520,
23422,
1012,
9530,
2546,
1012,
24471,
4877,
12324,
24471,
2140,
2013,
6327,
2015,
1012,
5328,
12324,
1006,
4256,
8159,
7983,
19172,
5677,
9331,
12848,
2666,
2860,
1010,
4256,
10288,
16451,
19058,
12928,
12146,
9331,
12848,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#include "substdio.h"
#include "subfd.h"
#include "stralloc.h"
#include "dns.h"
#include "dnsdoe.h"
#include "ip.h"
#include "ipalloc.h"
#include "exit.h"
stralloc sa = {0};
ipalloc ia = {0};
void main(argc,argv)
int argc;
char **argv;
{
if (!argv[1]) _exit(100);
if (!stralloc_copys(&sa,argv[1]))
{ substdio_putsflush(subfderr,"out of memory\n"); _exit(111); }
dns_init(1);
dnsdoe(dns_ip(&ia,&sa));
if (ia.len <= 0)
{
substdio_putsflush(subfderr,"no IP addresses\n"); _exit(100);
}
dnsdoe(dns_ptr(&sa,&ia.ix[0].ip));
substdio_putflush(subfdout,sa.s,sa.len);
substdio_putsflush(subfdout,"\n");
_exit(0);
}
| NikolaMandic/containers | qmail/qmail/dnsfq.c | C | mit | 628 | [
30522,
1001,
2421,
1000,
4942,
3367,
20617,
1012,
1044,
1000,
1001,
2421,
1000,
4942,
2546,
2094,
1012,
1044,
1000,
1001,
2421,
1000,
2358,
7941,
4135,
2278,
1012,
1044,
1000,
1001,
2421,
1000,
1040,
3619,
1012,
1044,
1000,
1001,
2421,
10... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
## Non Organizational Rolodexes [/research-common/api/v1/non-organizational-rolodexes/]
### Get Non Organizational Rolodexes by Key [GET /research-common/api/v1/non-organizational-rolodexes/(key)]
+ Request
+ Headers
Authorization: Bearer {api-key}
Content-Type: application/json
+ Response 200
+ Headers
Content-Type: application/json;charset=UTF-8
+ Body
{"rolodexId": "(val)","addressLine1": "(val)","addressLine2": "(val)","addressLine3": "(val)","city": "(val)","comments": "(val)","countryCode": "(val)","county": "(val)","createUser": "(val)","deleteFlag": "(val)","emailAddress": "(val)","faxNumber": "(val)","firstName": "(val)","lastName": "(val)","middleName": "(val)","organization": "(val)","ownedByUnit": "(val)","phoneNumber": "(val)","postalCode": "(val)","prefix": "(val)","sponsorAddressFlag": "(val)","sponsorCode": "(val)","state": "(val)","suffix": "(val)","title": "(val)","_primaryKey": "(val)"}
### Get All Non Organizational Rolodexes [GET /research-common/api/v1/non-organizational-rolodexes/]
+ Request
+ Headers
Authorization: Bearer {api-key}
Content-Type: application/json
+ Response 200
+ Headers
Content-Type: application/json;charset=UTF-8
+ Body
[
{"rolodexId": "(val)","addressLine1": "(val)","addressLine2": "(val)","addressLine3": "(val)","city": "(val)","comments": "(val)","countryCode": "(val)","county": "(val)","createUser": "(val)","deleteFlag": "(val)","emailAddress": "(val)","faxNumber": "(val)","firstName": "(val)","lastName": "(val)","middleName": "(val)","organization": "(val)","ownedByUnit": "(val)","phoneNumber": "(val)","postalCode": "(val)","prefix": "(val)","sponsorAddressFlag": "(val)","sponsorCode": "(val)","state": "(val)","suffix": "(val)","title": "(val)","_primaryKey": "(val)"},
{"rolodexId": "(val)","addressLine1": "(val)","addressLine2": "(val)","addressLine3": "(val)","city": "(val)","comments": "(val)","countryCode": "(val)","county": "(val)","createUser": "(val)","deleteFlag": "(val)","emailAddress": "(val)","faxNumber": "(val)","firstName": "(val)","lastName": "(val)","middleName": "(val)","organization": "(val)","ownedByUnit": "(val)","phoneNumber": "(val)","postalCode": "(val)","prefix": "(val)","sponsorAddressFlag": "(val)","sponsorCode": "(val)","state": "(val)","suffix": "(val)","title": "(val)","_primaryKey": "(val)"}
]
### Get All Non Organizational Rolodexes with Filtering [GET /research-common/api/v1/non-organizational-rolodexes/]
+ Parameters
+ rolodexId (optional) - Rolodex Id. Maximum length is 6.
+ addressLine1 (optional) - Address Line 1. Maximum length is 80.
+ addressLine2 (optional) - Address Line 2. Maximum length is 80.
+ addressLine3 (optional) - Address Line 3. Maximum length is 80.
+ city (optional) - City. Maximum length is 30.
+ comments (optional) - Comments. Maximum length is 300.
+ countryCode (optional) - Country Code. Maximum length is 3.
+ county (optional) - County. Maximum length is 30.
+ createUser (optional) -
+ deleteFlag (optional) - Delete Flag. Maximum length is 1.
+ emailAddress (optional) - Email Address. Maximum length is 60.
+ faxNumber (optional) - Fax Number. Maximum length is 20.
+ firstName (optional) - First Name. Maximum length is 20.
+ lastName (optional) - Last Name. Maximum length is 20.
+ middleName (optional) - Middle Name. Maximum length is 20.
+ organization (optional) - Organization. Maximum length is 80.
+ ownedByUnit (optional) - Owned By Unit. Maximum length is 8.
+ phoneNumber (optional) - Phone Number. Maximum length is 20.
+ postalCode (optional) - Postal Code. Maximum length is 15.
+ prefix (optional) - Prefix. Maximum length is 10.
+ sponsorAddressFlag (optional) - Sponsor Address Flag. Maximum length is 1.
+ sponsorCode (optional) - Sponsor Code. Maximum length is 6.
+ state (optional) - State. Maximum length is 30.
+ suffix (optional) - Suffix. Maximum length is 10.
+ title (optional) - Title. Maximum length is 35.
+ Request
+ Headers
Authorization: Bearer {api-key}
Content-Type: application/json
+ Response 200
+ Headers
Content-Type: application/json;charset=UTF-8
+ Body
[
{"rolodexId": "(val)","addressLine1": "(val)","addressLine2": "(val)","addressLine3": "(val)","city": "(val)","comments": "(val)","countryCode": "(val)","county": "(val)","createUser": "(val)","deleteFlag": "(val)","emailAddress": "(val)","faxNumber": "(val)","firstName": "(val)","lastName": "(val)","middleName": "(val)","organization": "(val)","ownedByUnit": "(val)","phoneNumber": "(val)","postalCode": "(val)","prefix": "(val)","sponsorAddressFlag": "(val)","sponsorCode": "(val)","state": "(val)","suffix": "(val)","title": "(val)","_primaryKey": "(val)"},
{"rolodexId": "(val)","addressLine1": "(val)","addressLine2": "(val)","addressLine3": "(val)","city": "(val)","comments": "(val)","countryCode": "(val)","county": "(val)","createUser": "(val)","deleteFlag": "(val)","emailAddress": "(val)","faxNumber": "(val)","firstName": "(val)","lastName": "(val)","middleName": "(val)","organization": "(val)","ownedByUnit": "(val)","phoneNumber": "(val)","postalCode": "(val)","prefix": "(val)","sponsorAddressFlag": "(val)","sponsorCode": "(val)","state": "(val)","suffix": "(val)","title": "(val)","_primaryKey": "(val)"}
]
### Get Schema for Non Organizational Rolodexes [GET /research-common/api/v1/non-organizational-rolodexes/]
+ Parameters
+ _schema (required) - will instruct the endpoint to return a schema data structure for the resource
+ Request
+ Headers
Authorization: Bearer {api-key}
Content-Type: application/json
+ Response 200
+ Headers
Content-Type: application/json;charset=UTF-8
+ Body
{"columns":["rolodexId","addressLine1","addressLine2","addressLine3","city","comments","countryCode","county","createUser","deleteFlag","emailAddress","faxNumber","firstName","lastName","middleName","organization","ownedByUnit","phoneNumber","postalCode","prefix","sponsorAddressFlag","sponsorCode","state","suffix","title"],"primaryKey":"rolodexId"}
### Get Blueprint API specification for Non Organizational Rolodexes [GET /research-common/api/v1/non-organizational-rolodexes/]
+ Parameters
+ _blueprint (required) - will instruct the endpoint to return an api blueprint markdown file for the resource
+ Request
+ Headers
Authorization: Bearer {api-key}
Content-Type: text/markdown
+ Response 200
+ Headers
Content-Type: text/markdown;charset=UTF-8
Content-Disposition:attachment; filename="Non Organizational Rolodexes.md"
transfer-encoding:chunked
### Update Non Organizational Rolodexes [PUT /research-common/api/v1/non-organizational-rolodexes/(key)]
+ Request
+ Headers
Authorization: Bearer {api-key}
Content-Type: application/json
+ Body
{"rolodexId": "(val)","addressLine1": "(val)","addressLine2": "(val)","addressLine3": "(val)","city": "(val)","comments": "(val)","countryCode": "(val)","county": "(val)","createUser": "(val)","deleteFlag": "(val)","emailAddress": "(val)","faxNumber": "(val)","firstName": "(val)","lastName": "(val)","middleName": "(val)","organization": "(val)","ownedByUnit": "(val)","phoneNumber": "(val)","postalCode": "(val)","prefix": "(val)","sponsorAddressFlag": "(val)","sponsorCode": "(val)","state": "(val)","suffix": "(val)","title": "(val)","_primaryKey": "(val)"}
+ Response 204
### Update Multiple Non Organizational Rolodexes [PUT /research-common/api/v1/non-organizational-rolodexes/]
+ Request
+ Headers
Authorization: Bearer {api-key}
Content-Type: application/json
+ Body
[
{"rolodexId": "(val)","addressLine1": "(val)","addressLine2": "(val)","addressLine3": "(val)","city": "(val)","comments": "(val)","countryCode": "(val)","county": "(val)","createUser": "(val)","deleteFlag": "(val)","emailAddress": "(val)","faxNumber": "(val)","firstName": "(val)","lastName": "(val)","middleName": "(val)","organization": "(val)","ownedByUnit": "(val)","phoneNumber": "(val)","postalCode": "(val)","prefix": "(val)","sponsorAddressFlag": "(val)","sponsorCode": "(val)","state": "(val)","suffix": "(val)","title": "(val)","_primaryKey": "(val)"},
{"rolodexId": "(val)","addressLine1": "(val)","addressLine2": "(val)","addressLine3": "(val)","city": "(val)","comments": "(val)","countryCode": "(val)","county": "(val)","createUser": "(val)","deleteFlag": "(val)","emailAddress": "(val)","faxNumber": "(val)","firstName": "(val)","lastName": "(val)","middleName": "(val)","organization": "(val)","ownedByUnit": "(val)","phoneNumber": "(val)","postalCode": "(val)","prefix": "(val)","sponsorAddressFlag": "(val)","sponsorCode": "(val)","state": "(val)","suffix": "(val)","title": "(val)","_primaryKey": "(val)"}
]
+ Response 204
### Insert Non Organizational Rolodexes [POST /research-common/api/v1/non-organizational-rolodexes/]
+ Request
+ Headers
Authorization: Bearer {api-key}
Content-Type: application/json
+ Body
{"rolodexId": "(val)","addressLine1": "(val)","addressLine2": "(val)","addressLine3": "(val)","city": "(val)","comments": "(val)","countryCode": "(val)","county": "(val)","createUser": "(val)","deleteFlag": "(val)","emailAddress": "(val)","faxNumber": "(val)","firstName": "(val)","lastName": "(val)","middleName": "(val)","organization": "(val)","ownedByUnit": "(val)","phoneNumber": "(val)","postalCode": "(val)","prefix": "(val)","sponsorAddressFlag": "(val)","sponsorCode": "(val)","state": "(val)","suffix": "(val)","title": "(val)","_primaryKey": "(val)"}
+ Response 201
+ Body
{"rolodexId": "(val)","addressLine1": "(val)","addressLine2": "(val)","addressLine3": "(val)","city": "(val)","comments": "(val)","countryCode": "(val)","county": "(val)","createUser": "(val)","deleteFlag": "(val)","emailAddress": "(val)","faxNumber": "(val)","firstName": "(val)","lastName": "(val)","middleName": "(val)","organization": "(val)","ownedByUnit": "(val)","phoneNumber": "(val)","postalCode": "(val)","prefix": "(val)","sponsorAddressFlag": "(val)","sponsorCode": "(val)","state": "(val)","suffix": "(val)","title": "(val)","_primaryKey": "(val)"}
### Insert Multiple Non Organizational Rolodexes [POST /research-common/api/v1/non-organizational-rolodexes/]
+ Request
+ Headers
Authorization: Bearer {api-key}
Content-Type: application/json
+ Body
[
{"rolodexId": "(val)","addressLine1": "(val)","addressLine2": "(val)","addressLine3": "(val)","city": "(val)","comments": "(val)","countryCode": "(val)","county": "(val)","createUser": "(val)","deleteFlag": "(val)","emailAddress": "(val)","faxNumber": "(val)","firstName": "(val)","lastName": "(val)","middleName": "(val)","organization": "(val)","ownedByUnit": "(val)","phoneNumber": "(val)","postalCode": "(val)","prefix": "(val)","sponsorAddressFlag": "(val)","sponsorCode": "(val)","state": "(val)","suffix": "(val)","title": "(val)","_primaryKey": "(val)"},
{"rolodexId": "(val)","addressLine1": "(val)","addressLine2": "(val)","addressLine3": "(val)","city": "(val)","comments": "(val)","countryCode": "(val)","county": "(val)","createUser": "(val)","deleteFlag": "(val)","emailAddress": "(val)","faxNumber": "(val)","firstName": "(val)","lastName": "(val)","middleName": "(val)","organization": "(val)","ownedByUnit": "(val)","phoneNumber": "(val)","postalCode": "(val)","prefix": "(val)","sponsorAddressFlag": "(val)","sponsorCode": "(val)","state": "(val)","suffix": "(val)","title": "(val)","_primaryKey": "(val)"}
]
+ Response 201
+ Body
[
{"rolodexId": "(val)","addressLine1": "(val)","addressLine2": "(val)","addressLine3": "(val)","city": "(val)","comments": "(val)","countryCode": "(val)","county": "(val)","createUser": "(val)","deleteFlag": "(val)","emailAddress": "(val)","faxNumber": "(val)","firstName": "(val)","lastName": "(val)","middleName": "(val)","organization": "(val)","ownedByUnit": "(val)","phoneNumber": "(val)","postalCode": "(val)","prefix": "(val)","sponsorAddressFlag": "(val)","sponsorCode": "(val)","state": "(val)","suffix": "(val)","title": "(val)","_primaryKey": "(val)"},
{"rolodexId": "(val)","addressLine1": "(val)","addressLine2": "(val)","addressLine3": "(val)","city": "(val)","comments": "(val)","countryCode": "(val)","county": "(val)","createUser": "(val)","deleteFlag": "(val)","emailAddress": "(val)","faxNumber": "(val)","firstName": "(val)","lastName": "(val)","middleName": "(val)","organization": "(val)","ownedByUnit": "(val)","phoneNumber": "(val)","postalCode": "(val)","prefix": "(val)","sponsorAddressFlag": "(val)","sponsorCode": "(val)","state": "(val)","suffix": "(val)","title": "(val)","_primaryKey": "(val)"}
]
### Delete Non Organizational Rolodexes by Key [DELETE /research-common/api/v1/non-organizational-rolodexes/(key)]
+ Request
+ Headers
Authorization: Bearer {api-key}
Content-Type: application/json
+ Response 204
### Delete All Non Organizational Rolodexes [DELETE /research-common/api/v1/non-organizational-rolodexes/]
+ Parameters
+ _allowMulti (boolean, required) - flag to allow multiple resources to be deleted in one operation
+ Request
+ Headers
Authorization: Bearer {api-key}
Content-Type: application/json
+ Response 204
### Delete All Non Organizational Rolodexes with Matching [DELETE /research-common/api/v1/non-organizational-rolodexes/]
+ Parameters
+ _allowMulti (boolean, required) - flag to allow multiple resources to be deleted in one operation
+ rolodexId (optional) - Rolodex Id. Maximum length is 6.
+ addressLine1 (optional) - Address Line 1. Maximum length is 80.
+ addressLine2 (optional) - Address Line 2. Maximum length is 80.
+ addressLine3 (optional) - Address Line 3. Maximum length is 80.
+ city (optional) - City. Maximum length is 30.
+ comments (optional) - Comments. Maximum length is 300.
+ countryCode (optional) - Country Code. Maximum length is 3.
+ county (optional) - County. Maximum length is 30.
+ createUser (optional) -
+ deleteFlag (optional) - Delete Flag. Maximum length is 1.
+ emailAddress (optional) - Email Address. Maximum length is 60.
+ faxNumber (optional) - Fax Number. Maximum length is 20.
+ firstName (optional) - First Name. Maximum length is 20.
+ lastName (optional) - Last Name. Maximum length is 20.
+ middleName (optional) - Middle Name. Maximum length is 20.
+ organization (optional) - Organization. Maximum length is 80.
+ ownedByUnit (optional) - Owned By Unit. Maximum length is 8.
+ phoneNumber (optional) - Phone Number. Maximum length is 20.
+ postalCode (optional) - Postal Code. Maximum length is 15.
+ prefix (optional) - Prefix. Maximum length is 10.
+ sponsorAddressFlag (optional) - Sponsor Address Flag. Maximum length is 1.
+ sponsorCode (optional) - Sponsor Code. Maximum length is 6.
+ state (optional) - State. Maximum length is 30.
+ suffix (optional) - Suffix. Maximum length is 10.
+ title (optional) - Title. Maximum length is 35.
+ Request
+ Headers
Authorization: Bearer {api-key}
Content-Type: application/json
+ Response 204
| iu-uits-es/kc | coeus-webapp/src/main/jsfrontend/apidocs/common/non-organizational-rolodexes.md | Markdown | agpl-3.0 | 16,003 | [
30522,
1001,
1001,
2512,
13296,
20996,
4135,
3207,
20156,
1031,
1013,
2470,
1011,
2691,
1013,
17928,
1013,
1058,
2487,
1013,
2512,
1011,
13296,
1011,
20996,
4135,
3207,
20156,
1013,
1033,
1001,
1001,
1001,
2131,
2512,
13296,
20996,
4135,
32... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* mxser.c -- MOXA Smartio/Industio family multiport serial driver.
*
* Copyright (C) 1999-2006 Moxa Technologies (support@moxa.com.tw).
* Copyright (C) 2006-2007 Jiri Slaby <jirislaby@gmail.com>
*
* This code is loosely based on the 1.8 moxa driver which is based on
* Linux serial driver, written by Linus Torvalds, Theodore T'so and
* others.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Fed through a cleanup, indent and remove of non 2.6 code by Alan Cox
* <alan@redhat.com>. The original 1.8 code is available on www.moxa.com.
* - Fixed x86_64 cleanness
* - Fixed sleep with spinlock held in mxser_send_break
*/
#include <linux/module.h>
#include <linux/autoconf.h>
#include <linux/errno.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/timer.h>
#include <linux/interrupt.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include <linux/serial.h>
#include <linux/serial_reg.h>
#include <linux/major.h>
#include <linux/string.h>
#include <linux/fcntl.h>
#include <linux/ptrace.h>
#include <linux/gfp.h>
#include <linux/ioport.h>
#include <linux/mm.h>
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/bitops.h>
#include <asm/system.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/uaccess.h>
#include "mxser_new.h"
#define MXSER_VERSION "2.0.2" /* 1.10 */
#define MXSERMAJOR 174
#define MXSERCUMAJOR 175
#define MXSER_BOARDS 4 /* Max. boards */
#define MXSER_PORTS_PER_BOARD 8 /* Max. ports per board */
#define MXSER_PORTS (MXSER_BOARDS * MXSER_PORTS_PER_BOARD)
#define MXSER_ISR_PASS_LIMIT 100
#define MXSER_ERR_IOADDR -1
#define MXSER_ERR_IRQ -2
#define MXSER_ERR_IRQ_CONFLIT -3
#define MXSER_ERR_VECTOR -4
/*CheckIsMoxaMust return value*/
#define MOXA_OTHER_UART 0x00
#define MOXA_MUST_MU150_HWID 0x01
#define MOXA_MUST_MU860_HWID 0x02
#define WAKEUP_CHARS 256
#define UART_MCR_AFE 0x20
#define UART_LSR_SPECIAL 0x1E
#define PCI_DEVICE_ID_CB108 0x1080
#define PCI_DEVICE_ID_CB114 0x1142
#define PCI_DEVICE_ID_CB134I 0x1341
#define PCI_DEVICE_ID_CP138U 0x1380
#define PCI_DEVICE_ID_POS104UL 0x1044
#define C168_ASIC_ID 1
#define C104_ASIC_ID 2
#define C102_ASIC_ID 0xB
#define CI132_ASIC_ID 4
#define CI134_ASIC_ID 3
#define CI104J_ASIC_ID 5
#define MXSER_HIGHBAUD 1
#define MXSER_HAS2 2
/* This is only for PCI */
static const struct {
int type;
int tx_fifo;
int rx_fifo;
int xmit_fifo_size;
int rx_high_water;
int rx_trigger;
int rx_low_water;
long max_baud;
} Gpci_uart_info[] = {
{MOXA_OTHER_UART, 16, 16, 16, 14, 14, 1, 921600L},
{MOXA_MUST_MU150_HWID, 64, 64, 64, 48, 48, 16, 230400L},
{MOXA_MUST_MU860_HWID, 128, 128, 128, 96, 96, 32, 921600L}
};
#define UART_INFO_NUM ARRAY_SIZE(Gpci_uart_info)
struct mxser_cardinfo {
unsigned int nports;
char *name;
unsigned int flags;
};
static const struct mxser_cardinfo mxser_cards[] = {
/* 0*/ { 8, "C168 series", },
{ 4, "C104 series", },
{ 4, "CI-104J series", },
{ 8, "C168H/PCI series", },
{ 4, "C104H/PCI series", },
/* 5*/ { 4, "C102 series", MXSER_HAS2 }, /* C102-ISA */
{ 4, "CI-132 series", MXSER_HAS2 },
{ 4, "CI-134 series", },
{ 2, "CP-132 series", },
{ 4, "CP-114 series", },
/*10*/ { 4, "CT-114 series", },
{ 2, "CP-102 series", MXSER_HIGHBAUD },
{ 4, "CP-104U series", },
{ 8, "CP-168U series", },
{ 2, "CP-132U series", },
/*15*/ { 4, "CP-134U series", },
{ 4, "CP-104JU series", },
{ 8, "Moxa UC7000 Serial", }, /* RC7000 */
{ 8, "CP-118U series", },
{ 2, "CP-102UL series", },
/*20*/ { 2, "CP-102U series", },
{ 8, "CP-118EL series", },
{ 8, "CP-168EL series", },
{ 4, "CP-104EL series", },
{ 8, "CB-108 series", },
/*25*/ { 4, "CB-114 series", },
{ 4, "CB-134I series", },
{ 8, "CP-138U series", },
{ 4, "POS-104UL series", }
};
/* driver_data correspond to the lines in the structure above
see also ISA probe function before you change something */
static struct pci_device_id mxser_pcibrds[] = {
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_MOXA_C168), .driver_data = 3 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_MOXA_C104), .driver_data = 4 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_MOXA_CP132), .driver_data = 8 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_MOXA_CP114), .driver_data = 9 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_MOXA_CT114), .driver_data = 10 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_MOXA_CP102), .driver_data = 11 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_MOXA_CP104U), .driver_data = 12 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_MOXA_CP168U), .driver_data = 13 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_MOXA_CP132U), .driver_data = 14 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_MOXA_CP134U), .driver_data = 15 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_MOXA_CP104JU),.driver_data = 16 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_MOXA_RC7000), .driver_data = 17 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_MOXA_CP118U), .driver_data = 18 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_MOXA_CP102UL),.driver_data = 19 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_MOXA_CP102U), .driver_data = 20 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_MOXA_CP118EL),.driver_data = 21 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_MOXA_CP168EL),.driver_data = 22 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_MOXA_CP104EL),.driver_data = 23 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_CB108), .driver_data = 24 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_CB114), .driver_data = 25 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_CB134I), .driver_data = 26 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_CP138U), .driver_data = 27 },
{ PCI_VDEVICE(MOXA, PCI_DEVICE_ID_POS104UL), .driver_data = 28 },
{ }
};
MODULE_DEVICE_TABLE(pci, mxser_pcibrds);
static int mxvar_baud_table[] = {
0, 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400,
4800, 9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600
};
static unsigned int mxvar_baud_table1[] = {
0, B50, B75, B110, B134, B150, B200, B300, B600, B1200, B1800, B2400,
B4800, B9600, B19200, B38400, B57600, B115200, B230400, B460800, B921600
};
#define BAUD_TABLE_NO ARRAY_SIZE(mxvar_baud_table)
#define B_SPEC B2000000
static int ioaddr[MXSER_BOARDS] = { 0, 0, 0, 0 };
static int ttymajor = MXSERMAJOR;
static int calloutmajor = MXSERCUMAJOR;
/* Variables for insmod */
MODULE_AUTHOR("Casper Yang");
MODULE_DESCRIPTION("MOXA Smartio/Industio Family Multiport Board Device Driver");
module_param_array(ioaddr, int, NULL, 0);
module_param(ttymajor, int, 0);
MODULE_LICENSE("GPL");
struct mxser_log {
int tick;
unsigned long rxcnt[MXSER_PORTS];
unsigned long txcnt[MXSER_PORTS];
};
struct mxser_mon {
unsigned long rxcnt;
unsigned long txcnt;
unsigned long up_rxcnt;
unsigned long up_txcnt;
int modem_status;
unsigned char hold_reason;
};
struct mxser_mon_ext {
unsigned long rx_cnt[32];
unsigned long tx_cnt[32];
unsigned long up_rxcnt[32];
unsigned long up_txcnt[32];
int modem_status[32];
long baudrate[32];
int databits[32];
int stopbits[32];
int parity[32];
int flowctrl[32];
int fifo[32];
int iftype[32];
};
struct mxser_board;
struct mxser_port {
struct mxser_board *board;
struct tty_struct *tty;
unsigned long ioaddr;
unsigned long opmode_ioaddr;
int max_baud;
int rx_high_water;
int rx_trigger; /* Rx fifo trigger level */
int rx_low_water;
int baud_base; /* max. speed */
long realbaud;
int type; /* UART type */
int flags; /* defined in tty.h */
int speed;
int x_char; /* xon/xoff character */
int IER; /* Interrupt Enable Register */
int MCR; /* Modem control register */
unsigned char stop_rx;
unsigned char ldisc_stop_rx;
int custom_divisor;
int close_delay;
unsigned short closing_wait;
unsigned char err_shadow;
unsigned long event;
int count; /* # of fd on device */
int blocked_open; /* # of blocked opens */
struct async_icount icount; /* kernel counters for 4 input interrupts */
int timeout;
int read_status_mask;
int ignore_status_mask;
int xmit_fifo_size;
unsigned char *xmit_buf;
int xmit_head;
int xmit_tail;
int xmit_cnt;
struct ktermios normal_termios;
struct mxser_mon mon_data;
spinlock_t slock;
wait_queue_head_t open_wait;
wait_queue_head_t delta_msr_wait;
};
struct mxser_board {
unsigned int idx;
int irq;
const struct mxser_cardinfo *info;
unsigned long vector;
unsigned long vector_mask;
int chip_flag;
int uart_type;
struct mxser_port ports[MXSER_PORTS_PER_BOARD];
};
struct mxser_mstatus {
tcflag_t cflag;
int cts;
int dsr;
int ri;
int dcd;
};
static struct mxser_mstatus GMStatus[MXSER_PORTS];
static int mxserBoardCAP[MXSER_BOARDS] = {
0, 0, 0, 0
/* 0x180, 0x280, 0x200, 0x320 */
};
static struct mxser_board mxser_boards[MXSER_BOARDS];
static struct tty_driver *mxvar_sdriver;
static struct mxser_log mxvar_log;
static int mxvar_diagflag;
static unsigned char mxser_msr[MXSER_PORTS + 1];
static struct mxser_mon_ext mon_data_ext;
static int mxser_set_baud_method[MXSER_PORTS + 1];
#ifdef CONFIG_PCI
static int __devinit CheckIsMoxaMust(int io)
{
u8 oldmcr, hwid;
int i;
outb(0, io + UART_LCR);
DISABLE_MOXA_MUST_ENCHANCE_MODE(io);
oldmcr = inb(io + UART_MCR);
outb(0, io + UART_MCR);
SET_MOXA_MUST_XON1_VALUE(io, 0x11);
if ((hwid = inb(io + UART_MCR)) != 0) {
outb(oldmcr, io + UART_MCR);
return MOXA_OTHER_UART;
}
GET_MOXA_MUST_HARDWARE_ID(io, &hwid);
for (i = 1; i < UART_INFO_NUM; i++) { /* 0 = OTHER_UART */
if (hwid == Gpci_uart_info[i].type)
return (int)hwid;
}
return MOXA_OTHER_UART;
}
#endif
static void process_txrx_fifo(struct mxser_port *info)
{
int i;
if ((info->type == PORT_16450) || (info->type == PORT_8250)) {
info->rx_trigger = 1;
info->rx_high_water = 1;
info->rx_low_water = 1;
info->xmit_fifo_size = 1;
} else
for (i = 0; i < UART_INFO_NUM; i++)
if (info->board->chip_flag == Gpci_uart_info[i].type) {
info->rx_trigger = Gpci_uart_info[i].rx_trigger;
info->rx_low_water = Gpci_uart_info[i].rx_low_water;
info->rx_high_water = Gpci_uart_info[i].rx_high_water;
info->xmit_fifo_size = Gpci_uart_info[i].xmit_fifo_size;
break;
}
}
static unsigned char mxser_get_msr(int baseaddr, int mode, int port)
{
unsigned char status = 0;
status = inb(baseaddr + UART_MSR);
mxser_msr[port] &= 0x0F;
mxser_msr[port] |= status;
status = mxser_msr[port];
if (mode)
mxser_msr[port] = 0;
return status;
}
static int mxser_block_til_ready(struct tty_struct *tty, struct file *filp,
struct mxser_port *port)
{
DECLARE_WAITQUEUE(wait, current);
int retval;
int do_clocal = 0;
unsigned long flags;
/*
* If non-blocking mode is set, or the port is not enabled,
* then make the check up front and then exit.
*/
if ((filp->f_flags & O_NONBLOCK) ||
test_bit(TTY_IO_ERROR, &tty->flags)) {
port->flags |= ASYNC_NORMAL_ACTIVE;
return 0;
}
if (tty->termios->c_cflag & CLOCAL)
do_clocal = 1;
/*
* Block waiting for the carrier detect and the line to become
* free (i.e., not in use by the callout). While we are in
* this loop, port->count is dropped by one, so that
* mxser_close() knows when to free things. We restore it upon
* exit, either normal or abnormal.
*/
retval = 0;
add_wait_queue(&port->open_wait, &wait);
spin_lock_irqsave(&port->slock, flags);
if (!tty_hung_up_p(filp))
port->count--;
spin_unlock_irqrestore(&port->slock, flags);
port->blocked_open++;
while (1) {
spin_lock_irqsave(&port->slock, flags);
outb(inb(port->ioaddr + UART_MCR) |
UART_MCR_DTR | UART_MCR_RTS, port->ioaddr + UART_MCR);
spin_unlock_irqrestore(&port->slock, flags);
set_current_state(TASK_INTERRUPTIBLE);
if (tty_hung_up_p(filp) || !(port->flags & ASYNC_INITIALIZED)) {
if (port->flags & ASYNC_HUP_NOTIFY)
retval = -EAGAIN;
else
retval = -ERESTARTSYS;
break;
}
if (!(port->flags & ASYNC_CLOSING) &&
(do_clocal ||
(inb(port->ioaddr + UART_MSR) & UART_MSR_DCD)))
break;
if (signal_pending(current)) {
retval = -ERESTARTSYS;
break;
}
schedule();
}
set_current_state(TASK_RUNNING);
remove_wait_queue(&port->open_wait, &wait);
if (!tty_hung_up_p(filp))
port->count++;
port->blocked_open--;
if (retval)
return retval;
port->flags |= ASYNC_NORMAL_ACTIVE;
return 0;
}
static int mxser_set_baud(struct mxser_port *info, long newspd)
{
unsigned int i;
int quot = 0;
unsigned char cval;
int ret = 0;
if (!info->tty || !info->tty->termios)
return ret;
if (!(info->ioaddr))
return ret;
if (newspd > info->max_baud)
return 0;
info->realbaud = newspd;
for (i = 0; i < BAUD_TABLE_NO; i++)
if (newspd == mxvar_baud_table[i])
break;
if (i == BAUD_TABLE_NO) {
quot = info->baud_base / info->speed;
if (info->speed <= 0 || info->speed > info->max_baud)
quot = 0;
} else {
if (newspd == 134) {
quot = (2 * info->baud_base / 269);
} else if (newspd) {
quot = info->baud_base / newspd;
if (quot == 0)
quot = 1;
} else {
quot = 0;
}
}
info->timeout = ((info->xmit_fifo_size * HZ * 10 * quot) / info->baud_base);
info->timeout += HZ / 50; /* Add .02 seconds of slop */
if (quot) {
info->MCR |= UART_MCR_DTR;
outb(info->MCR, info->ioaddr + UART_MCR);
} else {
info->MCR &= ~UART_MCR_DTR;
outb(info->MCR, info->ioaddr + UART_MCR);
return ret;
}
cval = inb(info->ioaddr + UART_LCR);
outb(cval | UART_LCR_DLAB, info->ioaddr + UART_LCR); /* set DLAB */
outb(quot & 0xff, info->ioaddr + UART_DLL); /* LS of divisor */
outb(quot >> 8, info->ioaddr + UART_DLM); /* MS of divisor */
outb(cval, info->ioaddr + UART_LCR); /* reset DLAB */
if (i == BAUD_TABLE_NO) {
quot = info->baud_base % info->speed;
quot *= 8;
if ((quot % info->speed) > (info->speed / 2)) {
quot /= info->speed;
quot++;
} else {
quot /= info->speed;
}
SET_MOXA_MUST_ENUM_VALUE(info->ioaddr, quot);
} else
SET_MOXA_MUST_ENUM_VALUE(info->ioaddr, 0);
return ret;
}
/*
* This routine is called to set the UART divisor registers to match
* the specified baud rate for a serial port.
*/
static int mxser_change_speed(struct mxser_port *info,
struct ktermios *old_termios)
{
unsigned cflag, cval, fcr;
int ret = 0;
unsigned char status;
long baud;
if (!info->tty || !info->tty->termios)
return ret;
cflag = info->tty->termios->c_cflag;
if (!(info->ioaddr))
return ret;
if (mxser_set_baud_method[info->tty->index] == 0) {
if ((cflag & CBAUD) == B_SPEC)
baud = info->speed;
else
baud = tty_get_baud_rate(info->tty);
mxser_set_baud(info, baud);
}
/* byte size and parity */
switch (cflag & CSIZE) {
case CS5:
cval = 0x00;
break;
case CS6:
cval = 0x01;
break;
case CS7:
cval = 0x02;
break;
case CS8:
cval = 0x03;
break;
default:
cval = 0x00;
break; /* too keep GCC shut... */
}
if (cflag & CSTOPB)
cval |= 0x04;
if (cflag & PARENB)
cval |= UART_LCR_PARITY;
if (!(cflag & PARODD))
cval |= UART_LCR_EPAR;
if (cflag & CMSPAR)
cval |= UART_LCR_SPAR;
if ((info->type == PORT_8250) || (info->type == PORT_16450)) {
if (info->board->chip_flag) {
fcr = UART_FCR_ENABLE_FIFO;
fcr |= MOXA_MUST_FCR_GDA_MODE_ENABLE;
SET_MOXA_MUST_FIFO_VALUE(info);
} else
fcr = 0;
} else {
fcr = UART_FCR_ENABLE_FIFO;
if (info->board->chip_flag) {
fcr |= MOXA_MUST_FCR_GDA_MODE_ENABLE;
SET_MOXA_MUST_FIFO_VALUE(info);
} else {
switch (info->rx_trigger) {
case 1:
fcr |= UART_FCR_TRIGGER_1;
break;
case 4:
fcr |= UART_FCR_TRIGGER_4;
break;
case 8:
fcr |= UART_FCR_TRIGGER_8;
break;
default:
fcr |= UART_FCR_TRIGGER_14;
break;
}
}
}
/* CTS flow control flag and modem status interrupts */
info->IER &= ~UART_IER_MSI;
info->MCR &= ~UART_MCR_AFE;
if (cflag & CRTSCTS) {
info->flags |= ASYNC_CTS_FLOW;
info->IER |= UART_IER_MSI;
if ((info->type == PORT_16550A) || (info->board->chip_flag)) {
info->MCR |= UART_MCR_AFE;
} else {
status = inb(info->ioaddr + UART_MSR);
if (info->tty->hw_stopped) {
if (status & UART_MSR_CTS) {
info->tty->hw_stopped = 0;
if (info->type != PORT_16550A &&
!info->board->chip_flag) {
outb(info->IER & ~UART_IER_THRI,
info->ioaddr +
UART_IER);
info->IER |= UART_IER_THRI;
outb(info->IER, info->ioaddr +
UART_IER);
}
tty_wakeup(info->tty);
}
} else {
if (!(status & UART_MSR_CTS)) {
info->tty->hw_stopped = 1;
if ((info->type != PORT_16550A) &&
(!info->board->chip_flag)) {
info->IER &= ~UART_IER_THRI;
outb(info->IER, info->ioaddr +
UART_IER);
}
}
}
}
} else {
info->flags &= ~ASYNC_CTS_FLOW;
}
outb(info->MCR, info->ioaddr + UART_MCR);
if (cflag & CLOCAL) {
info->flags &= ~ASYNC_CHECK_CD;
} else {
info->flags |= ASYNC_CHECK_CD;
info->IER |= UART_IER_MSI;
}
outb(info->IER, info->ioaddr + UART_IER);
/*
* Set up parity check flag
*/
info->read_status_mask = UART_LSR_OE | UART_LSR_THRE | UART_LSR_DR;
if (I_INPCK(info->tty))
info->read_status_mask |= UART_LSR_FE | UART_LSR_PE;
if (I_BRKINT(info->tty) || I_PARMRK(info->tty))
info->read_status_mask |= UART_LSR_BI;
info->ignore_status_mask = 0;
if (I_IGNBRK(info->tty)) {
info->ignore_status_mask |= UART_LSR_BI;
info->read_status_mask |= UART_LSR_BI;
/*
* If we're ignore parity and break indicators, ignore
* overruns too. (For real raw support).
*/
if (I_IGNPAR(info->tty)) {
info->ignore_status_mask |=
UART_LSR_OE |
UART_LSR_PE |
UART_LSR_FE;
info->read_status_mask |=
UART_LSR_OE |
UART_LSR_PE |
UART_LSR_FE;
}
}
if (info->board->chip_flag) {
SET_MOXA_MUST_XON1_VALUE(info->ioaddr, START_CHAR(info->tty));
SET_MOXA_MUST_XOFF1_VALUE(info->ioaddr, STOP_CHAR(info->tty));
if (I_IXON(info->tty)) {
ENABLE_MOXA_MUST_RX_SOFTWARE_FLOW_CONTROL(info->ioaddr);
} else {
DISABLE_MOXA_MUST_RX_SOFTWARE_FLOW_CONTROL(info->ioaddr);
}
if (I_IXOFF(info->tty)) {
ENABLE_MOXA_MUST_TX_SOFTWARE_FLOW_CONTROL(info->ioaddr);
} else {
DISABLE_MOXA_MUST_TX_SOFTWARE_FLOW_CONTROL(info->ioaddr);
}
}
outb(fcr, info->ioaddr + UART_FCR); /* set fcr */
outb(cval, info->ioaddr + UART_LCR);
return ret;
}
static void mxser_check_modem_status(struct mxser_port *port, int status)
{
/* update input line counters */
if (status & UART_MSR_TERI)
port->icount.rng++;
if (status & UART_MSR_DDSR)
port->icount.dsr++;
if (status & UART_MSR_DDCD)
port->icount.dcd++;
if (status & UART_MSR_DCTS)
port->icount.cts++;
port->mon_data.modem_status = status;
wake_up_interruptible(&port->delta_msr_wait);
if ((port->flags & ASYNC_CHECK_CD) && (status & UART_MSR_DDCD)) {
if (status & UART_MSR_DCD)
wake_up_interruptible(&port->open_wait);
}
if (port->flags & ASYNC_CTS_FLOW) {
if (port->tty->hw_stopped) {
if (status & UART_MSR_CTS) {
port->tty->hw_stopped = 0;
if ((port->type != PORT_16550A) &&
(!port->board->chip_flag)) {
outb(port->IER & ~UART_IER_THRI,
port->ioaddr + UART_IER);
port->IER |= UART_IER_THRI;
outb(port->IER, port->ioaddr +
UART_IER);
}
tty_wakeup(port->tty);
}
} else {
if (!(status & UART_MSR_CTS)) {
port->tty->hw_stopped = 1;
if (port->type != PORT_16550A &&
!port->board->chip_flag) {
port->IER &= ~UART_IER_THRI;
outb(port->IER, port->ioaddr +
UART_IER);
}
}
}
}
}
static int mxser_startup(struct mxser_port *info)
{
unsigned long page;
unsigned long flags;
page = __get_free_page(GFP_KERNEL);
if (!page)
return -ENOMEM;
spin_lock_irqsave(&info->slock, flags);
if (info->flags & ASYNC_INITIALIZED) {
free_page(page);
spin_unlock_irqrestore(&info->slock, flags);
return 0;
}
if (!info->ioaddr || !info->type) {
if (info->tty)
set_bit(TTY_IO_ERROR, &info->tty->flags);
free_page(page);
spin_unlock_irqrestore(&info->slock, flags);
return 0;
}
if (info->xmit_buf)
free_page(page);
else
info->xmit_buf = (unsigned char *) page;
/*
* Clear the FIFO buffers and disable them
* (they will be reenabled in mxser_change_speed())
*/
if (info->board->chip_flag)
outb((UART_FCR_CLEAR_RCVR |
UART_FCR_CLEAR_XMIT |
MOXA_MUST_FCR_GDA_MODE_ENABLE), info->ioaddr + UART_FCR);
else
outb((UART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT),
info->ioaddr + UART_FCR);
/*
* At this point there's no way the LSR could still be 0xFF;
* if it is, then bail out, because there's likely no UART
* here.
*/
if (inb(info->ioaddr + UART_LSR) == 0xff) {
spin_unlock_irqrestore(&info->slock, flags);
if (capable(CAP_SYS_ADMIN)) {
if (info->tty)
set_bit(TTY_IO_ERROR, &info->tty->flags);
return 0;
} else
return -ENODEV;
}
/*
* Clear the interrupt registers.
*/
(void) inb(info->ioaddr + UART_LSR);
(void) inb(info->ioaddr + UART_RX);
(void) inb(info->ioaddr + UART_IIR);
(void) inb(info->ioaddr + UART_MSR);
/*
* Now, initialize the UART
*/
outb(UART_LCR_WLEN8, info->ioaddr + UART_LCR); /* reset DLAB */
info->MCR = UART_MCR_DTR | UART_MCR_RTS;
outb(info->MCR, info->ioaddr + UART_MCR);
/*
* Finally, enable interrupts
*/
info->IER = UART_IER_MSI | UART_IER_RLSI | UART_IER_RDI;
if (info->board->chip_flag)
info->IER |= MOXA_MUST_IER_EGDAI;
outb(info->IER, info->ioaddr + UART_IER); /* enable interrupts */
/*
* And clear the interrupt registers again for luck.
*/
(void) inb(info->ioaddr + UART_LSR);
(void) inb(info->ioaddr + UART_RX);
(void) inb(info->ioaddr + UART_IIR);
(void) inb(info->ioaddr + UART_MSR);
if (info->tty)
clear_bit(TTY_IO_ERROR, &info->tty->flags);
info->xmit_cnt = info->xmit_head = info->xmit_tail = 0;
/*
* and set the speed of the serial port
*/
mxser_change_speed(info, NULL);
info->flags |= ASYNC_INITIALIZED;
spin_unlock_irqrestore(&info->slock, flags);
return 0;
}
/*
* This routine will shutdown a serial port; interrupts maybe disabled, and
* DTR is dropped if the hangup on close termio flag is on.
*/
static void mxser_shutdown(struct mxser_port *info)
{
unsigned long flags;
if (!(info->flags & ASYNC_INITIALIZED))
return;
spin_lock_irqsave(&info->slock, flags);
/*
* clear delta_msr_wait queue to avoid mem leaks: we may free the irq
* here so the queue might never be waken up
*/
wake_up_interruptible(&info->delta_msr_wait);
/*
* Free the IRQ, if necessary
*/
if (info->xmit_buf) {
free_page((unsigned long) info->xmit_buf);
info->xmit_buf = NULL;
}
info->IER = 0;
outb(0x00, info->ioaddr + UART_IER);
if (!info->tty || (info->tty->termios->c_cflag & HUPCL))
info->MCR &= ~(UART_MCR_DTR | UART_MCR_RTS);
outb(info->MCR, info->ioaddr + UART_MCR);
/* clear Rx/Tx FIFO's */
if (info->board->chip_flag)
outb(UART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT |
MOXA_MUST_FCR_GDA_MODE_ENABLE,
info->ioaddr + UART_FCR);
else
outb(UART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT,
info->ioaddr + UART_FCR);
/* read data port to reset things */
(void) inb(info->ioaddr + UART_RX);
if (info->tty)
set_bit(TTY_IO_ERROR, &info->tty->flags);
info->flags &= ~ASYNC_INITIALIZED;
if (info->board->chip_flag)
SET_MOXA_MUST_NO_SOFTWARE_FLOW_CONTROL(info->ioaddr);
spin_unlock_irqrestore(&info->slock, flags);
}
/*
* This routine is called whenever a serial port is opened. It
* enables interrupts for a serial port, linking in its async structure into
* the IRQ chain. It also performs the serial-specific
* initialization for the tty structure.
*/
static int mxser_open(struct tty_struct *tty, struct file *filp)
{
struct mxser_port *info;
unsigned long flags;
int retval, line;
line = tty->index;
if (line == MXSER_PORTS)
return 0;
if (line < 0 || line > MXSER_PORTS)
return -ENODEV;
info = &mxser_boards[line / MXSER_PORTS_PER_BOARD].ports[line % MXSER_PORTS_PER_BOARD];
if (!info->ioaddr)
return -ENODEV;
tty->driver_data = info;
info->tty = tty;
/*
* Start up serial port
*/
spin_lock_irqsave(&info->slock, flags);
info->count++;
spin_unlock_irqrestore(&info->slock, flags);
retval = mxser_startup(info);
if (retval)
return retval;
retval = mxser_block_til_ready(tty, filp, info);
if (retval)
return retval;
/* unmark here for very high baud rate (ex. 921600 bps) used */
tty->low_latency = 1;
return 0;
}
/*
* This routine is called when the serial port gets closed. First, we
* wait for the last remaining data to be sent. Then, we unlink its
* async structure from the interrupt chain if necessary, and we free
* that IRQ if nothing is left in the chain.
*/
static void mxser_close(struct tty_struct *tty, struct file *filp)
{
struct mxser_port *info = tty->driver_data;
unsigned long timeout;
unsigned long flags;
if (tty->index == MXSER_PORTS)
return;
if (!info)
return;
spin_lock_irqsave(&info->slock, flags);
if (tty_hung_up_p(filp)) {
spin_unlock_irqrestore(&info->slock, flags);
return;
}
if ((tty->count == 1) && (info->count != 1)) {
/*
* Uh, oh. tty->count is 1, which means that the tty
* structure will be freed. Info->count should always
* be one in these conditions. If it's greater than
* one, we've got real problems, since it means the
* serial port won't be shutdown.
*/
printk(KERN_ERR "mxser_close: bad serial port count; "
"tty->count is 1, info->count is %d\n", info->count);
info->count = 1;
}
if (--info->count < 0) {
printk(KERN_ERR "mxser_close: bad serial port count for "
"ttys%d: %d\n", tty->index, info->count);
info->count = 0;
}
if (info->count) {
spin_unlock_irqrestore(&info->slock, flags);
return;
}
info->flags |= ASYNC_CLOSING;
spin_unlock_irqrestore(&info->slock, flags);
/*
* Save the termios structure, since this port may have
* separate termios for callout and dialin.
*/
if (info->flags & ASYNC_NORMAL_ACTIVE)
info->normal_termios = *tty->termios;
/*
* Now we wait for the transmit buffer to clear; and we notify
* the line discipline to only process XON/XOFF characters.
*/
tty->closing = 1;
if (info->closing_wait != ASYNC_CLOSING_WAIT_NONE)
tty_wait_until_sent(tty, info->closing_wait);
/*
* At this point we stop accepting input. To do this, we
* disable the receive line status interrupts, and tell the
* interrupt driver to stop checking the data ready bit in the
* line status register.
*/
info->IER &= ~UART_IER_RLSI;
if (info->board->chip_flag)
info->IER &= ~MOXA_MUST_RECV_ISR;
if (info->flags & ASYNC_INITIALIZED) {
outb(info->IER, info->ioaddr + UART_IER);
/*
* Before we drop DTR, make sure the UART transmitter
* has completely drained; this is especially
* important if there is a transmit FIFO!
*/
timeout = jiffies + HZ;
while (!(inb(info->ioaddr + UART_LSR) & UART_LSR_TEMT)) {
schedule_timeout_interruptible(5);
if (time_after(jiffies, timeout))
break;
}
}
mxser_shutdown(info);
if (tty->driver->flush_buffer)
tty->driver->flush_buffer(tty);
tty_ldisc_flush(tty);
tty->closing = 0;
info->event = 0;
info->tty = NULL;
if (info->blocked_open) {
if (info->close_delay)
schedule_timeout_interruptible(info->close_delay);
wake_up_interruptible(&info->open_wait);
}
info->flags &= ~(ASYNC_NORMAL_ACTIVE | ASYNC_CLOSING);
}
static int mxser_write(struct tty_struct *tty, const unsigned char *buf, int count)
{
int c, total = 0;
struct mxser_port *info = tty->driver_data;
unsigned long flags;
if (!info->xmit_buf)
return 0;
while (1) {
c = min_t(int, count, min(SERIAL_XMIT_SIZE - info->xmit_cnt - 1,
SERIAL_XMIT_SIZE - info->xmit_head));
if (c <= 0)
break;
memcpy(info->xmit_buf + info->xmit_head, buf, c);
spin_lock_irqsave(&info->slock, flags);
info->xmit_head = (info->xmit_head + c) &
(SERIAL_XMIT_SIZE - 1);
info->xmit_cnt += c;
spin_unlock_irqrestore(&info->slock, flags);
buf += c;
count -= c;
total += c;
}
if (info->xmit_cnt && !tty->stopped) {
if (!tty->hw_stopped ||
(info->type == PORT_16550A) ||
(info->board->chip_flag)) {
spin_lock_irqsave(&info->slock, flags);
outb(info->IER & ~UART_IER_THRI, info->ioaddr +
UART_IER);
info->IER |= UART_IER_THRI;
outb(info->IER, info->ioaddr + UART_IER);
spin_unlock_irqrestore(&info->slock, flags);
}
}
return total;
}
static void mxser_put_char(struct tty_struct *tty, unsigned char ch)
{
struct mxser_port *info = tty->driver_data;
unsigned long flags;
if (!info->xmit_buf)
return;
if (info->xmit_cnt >= SERIAL_XMIT_SIZE - 1)
return;
spin_lock_irqsave(&info->slock, flags);
info->xmit_buf[info->xmit_head++] = ch;
info->xmit_head &= SERIAL_XMIT_SIZE - 1;
info->xmit_cnt++;
spin_unlock_irqrestore(&info->slock, flags);
if (!tty->stopped) {
if (!tty->hw_stopped ||
(info->type == PORT_16550A) ||
info->board->chip_flag) {
spin_lock_irqsave(&info->slock, flags);
outb(info->IER & ~UART_IER_THRI, info->ioaddr + UART_IER);
info->IER |= UART_IER_THRI;
outb(info->IER, info->ioaddr + UART_IER);
spin_unlock_irqrestore(&info->slock, flags);
}
}
}
static void mxser_flush_chars(struct tty_struct *tty)
{
struct mxser_port *info = tty->driver_data;
unsigned long flags;
if (info->xmit_cnt <= 0 ||
tty->stopped ||
!info->xmit_buf ||
(tty->hw_stopped &&
(info->type != PORT_16550A) &&
(!info->board->chip_flag)
))
return;
spin_lock_irqsave(&info->slock, flags);
outb(info->IER & ~UART_IER_THRI, info->ioaddr + UART_IER);
info->IER |= UART_IER_THRI;
outb(info->IER, info->ioaddr + UART_IER);
spin_unlock_irqrestore(&info->slock, flags);
}
static int mxser_write_room(struct tty_struct *tty)
{
struct mxser_port *info = tty->driver_data;
int ret;
ret = SERIAL_XMIT_SIZE - info->xmit_cnt - 1;
if (ret < 0)
ret = 0;
return ret;
}
static int mxser_chars_in_buffer(struct tty_struct *tty)
{
struct mxser_port *info = tty->driver_data;
return info->xmit_cnt;
}
static void mxser_flush_buffer(struct tty_struct *tty)
{
struct mxser_port *info = tty->driver_data;
char fcr;
unsigned long flags;
spin_lock_irqsave(&info->slock, flags);
info->xmit_cnt = info->xmit_head = info->xmit_tail = 0;
fcr = inb(info->ioaddr + UART_FCR);
outb((fcr | UART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT),
info->ioaddr + UART_FCR);
outb(fcr, info->ioaddr + UART_FCR);
spin_unlock_irqrestore(&info->slock, flags);
tty_wakeup(tty);
}
/*
* ------------------------------------------------------------
* friends of mxser_ioctl()
* ------------------------------------------------------------
*/
static int mxser_get_serial_info(struct mxser_port *info,
struct serial_struct __user *retinfo)
{
struct serial_struct tmp;
if (!retinfo)
return -EFAULT;
memset(&tmp, 0, sizeof(tmp));
tmp.type = info->type;
tmp.line = info->tty->index;
tmp.port = info->ioaddr;
tmp.irq = info->board->irq;
tmp.flags = info->flags;
tmp.baud_base = info->baud_base;
tmp.close_delay = info->close_delay;
tmp.closing_wait = info->closing_wait;
tmp.custom_divisor = info->custom_divisor;
tmp.hub6 = 0;
if (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
return -EFAULT;
return 0;
}
static int mxser_set_serial_info(struct mxser_port *info,
struct serial_struct __user *new_info)
{
struct serial_struct new_serial;
unsigned long sl_flags;
unsigned int flags;
int retval = 0;
if (!new_info || !info->ioaddr)
return -EFAULT;
if (copy_from_user(&new_serial, new_info, sizeof(new_serial)))
return -EFAULT;
if ((new_serial.irq != info->board->irq) ||
(new_serial.port != info->ioaddr) ||
(new_serial.custom_divisor != info->custom_divisor) ||
(new_serial.baud_base != info->baud_base))
return -EPERM;
flags = info->flags & ASYNC_SPD_MASK;
if (!capable(CAP_SYS_ADMIN)) {
if ((new_serial.baud_base != info->baud_base) ||
(new_serial.close_delay != info->close_delay) ||
((new_serial.flags & ~ASYNC_USR_MASK) != (info->flags & ~ASYNC_USR_MASK)))
return -EPERM;
info->flags = ((info->flags & ~ASYNC_USR_MASK) |
(new_serial.flags & ASYNC_USR_MASK));
} else {
/*
* OK, past this point, all the error checking has been done.
* At this point, we start making changes.....
*/
info->flags = ((info->flags & ~ASYNC_FLAGS) |
(new_serial.flags & ASYNC_FLAGS));
info->close_delay = new_serial.close_delay * HZ / 100;
info->closing_wait = new_serial.closing_wait * HZ / 100;
info->tty->low_latency =
(info->flags & ASYNC_LOW_LATENCY) ? 1 : 0;
info->tty->low_latency = 0;
}
info->type = new_serial.type;
process_txrx_fifo(info);
if (info->flags & ASYNC_INITIALIZED) {
if (flags != (info->flags & ASYNC_SPD_MASK)) {
spin_lock_irqsave(&info->slock, sl_flags);
mxser_change_speed(info, NULL);
spin_unlock_irqrestore(&info->slock, sl_flags);
}
} else
retval = mxser_startup(info);
return retval;
}
/*
* mxser_get_lsr_info - get line status register info
*
* Purpose: Let user call ioctl() to get info when the UART physically
* is emptied. On bus types like RS485, the transmitter must
* release the bus after transmitting. This must be done when
* the transmit shift register is empty, not be done when the
* transmit holding register is empty. This functionality
* allows an RS485 driver to be written in user space.
*/
static int mxser_get_lsr_info(struct mxser_port *info,
unsigned int __user *value)
{
unsigned char status;
unsigned int result;
unsigned long flags;
spin_lock_irqsave(&info->slock, flags);
status = inb(info->ioaddr + UART_LSR);
spin_unlock_irqrestore(&info->slock, flags);
result = ((status & UART_LSR_TEMT) ? TIOCSER_TEMT : 0);
return put_user(result, value);
}
/*
* This routine sends a break character out the serial port.
*/
static void mxser_send_break(struct mxser_port *info, int duration)
{
unsigned long flags;
if (!info->ioaddr)
return;
set_current_state(TASK_INTERRUPTIBLE);
spin_lock_irqsave(&info->slock, flags);
outb(inb(info->ioaddr + UART_LCR) | UART_LCR_SBC,
info->ioaddr + UART_LCR);
spin_unlock_irqrestore(&info->slock, flags);
schedule_timeout(duration);
spin_lock_irqsave(&info->slock, flags);
outb(inb(info->ioaddr + UART_LCR) & ~UART_LCR_SBC,
info->ioaddr + UART_LCR);
spin_unlock_irqrestore(&info->slock, flags);
}
static int mxser_tiocmget(struct tty_struct *tty, struct file *file)
{
struct mxser_port *info = tty->driver_data;
unsigned char control, status;
unsigned long flags;
if (tty->index == MXSER_PORTS)
return -ENOIOCTLCMD;
if (test_bit(TTY_IO_ERROR, &tty->flags))
return -EIO;
control = info->MCR;
spin_lock_irqsave(&info->slock, flags);
status = inb(info->ioaddr + UART_MSR);
if (status & UART_MSR_ANY_DELTA)
mxser_check_modem_status(info, status);
spin_unlock_irqrestore(&info->slock, flags);
return ((control & UART_MCR_RTS) ? TIOCM_RTS : 0) |
((control & UART_MCR_DTR) ? TIOCM_DTR : 0) |
((status & UART_MSR_DCD) ? TIOCM_CAR : 0) |
((status & UART_MSR_RI) ? TIOCM_RNG : 0) |
((status & UART_MSR_DSR) ? TIOCM_DSR : 0) |
((status & UART_MSR_CTS) ? TIOCM_CTS : 0);
}
static int mxser_tiocmset(struct tty_struct *tty, struct file *file,
unsigned int set, unsigned int clear)
{
struct mxser_port *info = tty->driver_data;
unsigned long flags;
if (tty->index == MXSER_PORTS)
return -ENOIOCTLCMD;
if (test_bit(TTY_IO_ERROR, &tty->flags))
return -EIO;
spin_lock_irqsave(&info->slock, flags);
if (set & TIOCM_RTS)
info->MCR |= UART_MCR_RTS;
if (set & TIOCM_DTR)
info->MCR |= UART_MCR_DTR;
if (clear & TIOCM_RTS)
info->MCR &= ~UART_MCR_RTS;
if (clear & TIOCM_DTR)
info->MCR &= ~UART_MCR_DTR;
outb(info->MCR, info->ioaddr + UART_MCR);
spin_unlock_irqrestore(&info->slock, flags);
return 0;
}
static int __init mxser_program_mode(int port)
{
int id, i, j, n;
outb(0, port);
outb(0, port);
outb(0, port);
(void)inb(port);
(void)inb(port);
outb(0, port);
(void)inb(port);
id = inb(port + 1) & 0x1F;
if ((id != C168_ASIC_ID) &&
(id != C104_ASIC_ID) &&
(id != C102_ASIC_ID) &&
(id != CI132_ASIC_ID) &&
(id != CI134_ASIC_ID) &&
(id != CI104J_ASIC_ID))
return -1;
for (i = 0, j = 0; i < 4; i++) {
n = inb(port + 2);
if (n == 'M') {
j = 1;
} else if ((j == 1) && (n == 1)) {
j = 2;
break;
} else
j = 0;
}
if (j != 2)
id = -2;
return id;
}
static void __init mxser_normal_mode(int port)
{
int i, n;
outb(0xA5, port + 1);
outb(0x80, port + 3);
outb(12, port + 0); /* 9600 bps */
outb(0, port + 1);
outb(0x03, port + 3); /* 8 data bits */
outb(0x13, port + 4); /* loop back mode */
for (i = 0; i < 16; i++) {
n = inb(port + 5);
if ((n & 0x61) == 0x60)
break;
if ((n & 1) == 1)
(void)inb(port);
}
outb(0x00, port + 4);
}
#define CHIP_SK 0x01 /* Serial Data Clock in Eprom */
#define CHIP_DO 0x02 /* Serial Data Output in Eprom */
#define CHIP_CS 0x04 /* Serial Chip Select in Eprom */
#define CHIP_DI 0x08 /* Serial Data Input in Eprom */
#define EN_CCMD 0x000 /* Chip's command register */
#define EN0_RSARLO 0x008 /* Remote start address reg 0 */
#define EN0_RSARHI 0x009 /* Remote start address reg 1 */
#define EN0_RCNTLO 0x00A /* Remote byte count reg WR */
#define EN0_RCNTHI 0x00B /* Remote byte count reg WR */
#define EN0_DCFG 0x00E /* Data configuration reg WR */
#define EN0_PORT 0x010 /* Rcv missed frame error counter RD */
#define ENC_PAGE0 0x000 /* Select page 0 of chip registers */
#define ENC_PAGE3 0x0C0 /* Select page 3 of chip registers */
static int __init mxser_read_register(int port, unsigned short *regs)
{
int i, k, value, id;
unsigned int j;
id = mxser_program_mode(port);
if (id < 0)
return id;
for (i = 0; i < 14; i++) {
k = (i & 0x3F) | 0x180;
for (j = 0x100; j > 0; j >>= 1) {
outb(CHIP_CS, port);
if (k & j) {
outb(CHIP_CS | CHIP_DO, port);
outb(CHIP_CS | CHIP_DO | CHIP_SK, port); /* A? bit of read */
} else {
outb(CHIP_CS, port);
outb(CHIP_CS | CHIP_SK, port); /* A? bit of read */
}
}
(void)inb(port);
value = 0;
for (k = 0, j = 0x8000; k < 16; k++, j >>= 1) {
outb(CHIP_CS, port);
outb(CHIP_CS | CHIP_SK, port);
if (inb(port) & CHIP_DI)
value |= j;
}
regs[i] = value;
outb(0, port);
}
mxser_normal_mode(port);
return id;
}
static int mxser_ioctl_special(unsigned int cmd, void __user *argp)
{
struct mxser_port *port;
int result, status;
unsigned int i, j;
switch (cmd) {
case MOXA_GET_CONF:
/* if (copy_to_user(argp, mxsercfg,
sizeof(struct mxser_hwconf) * 4))
return -EFAULT;
return 0;*/
return -ENXIO;
case MOXA_GET_MAJOR:
if (copy_to_user(argp, &ttymajor, sizeof(int)))
return -EFAULT;
return 0;
case MOXA_GET_CUMAJOR:
if (copy_to_user(argp, &calloutmajor, sizeof(int)))
return -EFAULT;
return 0;
case MOXA_CHKPORTENABLE:
result = 0;
for (i = 0; i < MXSER_BOARDS; i++)
for (j = 0; j < MXSER_PORTS_PER_BOARD; j++)
if (mxser_boards[i].ports[j].ioaddr)
result |= (1 << i);
return put_user(result, (unsigned long __user *)argp);
case MOXA_GETDATACOUNT:
if (copy_to_user(argp, &mxvar_log, sizeof(mxvar_log)))
return -EFAULT;
return 0;
case MOXA_GETMSTATUS:
for (i = 0; i < MXSER_BOARDS; i++)
for (j = 0; j < MXSER_PORTS_PER_BOARD; j++) {
port = &mxser_boards[i].ports[j];
GMStatus[i].ri = 0;
if (!port->ioaddr) {
GMStatus[i].dcd = 0;
GMStatus[i].dsr = 0;
GMStatus[i].cts = 0;
continue;
}
if (!port->tty || !port->tty->termios)
GMStatus[i].cflag =
port->normal_termios.c_cflag;
else
GMStatus[i].cflag =
port->tty->termios->c_cflag;
status = inb(port->ioaddr + UART_MSR);
if (status & 0x80 /*UART_MSR_DCD */ )
GMStatus[i].dcd = 1;
else
GMStatus[i].dcd = 0;
if (status & 0x20 /*UART_MSR_DSR */ )
GMStatus[i].dsr = 1;
else
GMStatus[i].dsr = 0;
if (status & 0x10 /*UART_MSR_CTS */ )
GMStatus[i].cts = 1;
else
GMStatus[i].cts = 0;
}
if (copy_to_user(argp, GMStatus,
sizeof(struct mxser_mstatus) * MXSER_PORTS))
return -EFAULT;
return 0;
case MOXA_ASPP_MON_EXT: {
int p, shiftbit;
unsigned long opmode;
unsigned cflag, iflag;
for (i = 0; i < MXSER_BOARDS; i++)
for (j = 0; j < MXSER_PORTS_PER_BOARD; j++) {
port = &mxser_boards[i].ports[j];
if (!port->ioaddr)
continue;
status = mxser_get_msr(port->ioaddr, 0, i);
if (status & UART_MSR_TERI)
port->icount.rng++;
if (status & UART_MSR_DDSR)
port->icount.dsr++;
if (status & UART_MSR_DDCD)
port->icount.dcd++;
if (status & UART_MSR_DCTS)
port->icount.cts++;
port->mon_data.modem_status = status;
mon_data_ext.rx_cnt[i] = port->mon_data.rxcnt;
mon_data_ext.tx_cnt[i] = port->mon_data.txcnt;
mon_data_ext.up_rxcnt[i] =
port->mon_data.up_rxcnt;
mon_data_ext.up_txcnt[i] =
port->mon_data.up_txcnt;
mon_data_ext.modem_status[i] =
port->mon_data.modem_status;
mon_data_ext.baudrate[i] = port->realbaud;
if (!port->tty || !port->tty->termios) {
cflag = port->normal_termios.c_cflag;
iflag = port->normal_termios.c_iflag;
} else {
cflag = port->tty->termios->c_cflag;
iflag = port->tty->termios->c_iflag;
}
mon_data_ext.databits[i] = cflag & CSIZE;
mon_data_ext.stopbits[i] = cflag & CSTOPB;
mon_data_ext.parity[i] =
cflag & (PARENB | PARODD | CMSPAR);
mon_data_ext.flowctrl[i] = 0x00;
if (cflag & CRTSCTS)
mon_data_ext.flowctrl[i] |= 0x03;
if (iflag & (IXON | IXOFF))
mon_data_ext.flowctrl[i] |= 0x0C;
if (port->type == PORT_16550A)
mon_data_ext.fifo[i] = 1;
else
mon_data_ext.fifo[i] = 0;
p = i % 4;
shiftbit = p * 2;
opmode = inb(port->opmode_ioaddr) >> shiftbit;
opmode &= OP_MODE_MASK;
mon_data_ext.iftype[i] = opmode;
}
if (copy_to_user(argp, &mon_data_ext,
sizeof(mon_data_ext)))
return -EFAULT;
return 0;
} default:
return -ENOIOCTLCMD;
}
return 0;
}
static int mxser_ioctl(struct tty_struct *tty, struct file *file,
unsigned int cmd, unsigned long arg)
{
struct mxser_port *info = tty->driver_data;
struct async_icount cprev, cnow; /* kernel counter temps */
struct serial_icounter_struct __user *p_cuser;
unsigned long templ;
unsigned long flags;
unsigned int i;
void __user *argp = (void __user *)arg;
int retval;
if (tty->index == MXSER_PORTS)
return mxser_ioctl_special(cmd, argp);
if (cmd == MOXA_SET_OP_MODE || cmd == MOXA_GET_OP_MODE) {
int p;
unsigned long opmode;
static unsigned char ModeMask[] = { 0xfc, 0xf3, 0xcf, 0x3f };
int shiftbit;
unsigned char val, mask;
p = tty->index % 4;
if (cmd == MOXA_SET_OP_MODE) {
if (get_user(opmode, (int __user *) argp))
return -EFAULT;
if (opmode != RS232_MODE &&
opmode != RS485_2WIRE_MODE &&
opmode != RS422_MODE &&
opmode != RS485_4WIRE_MODE)
return -EFAULT;
mask = ModeMask[p];
shiftbit = p * 2;
val = inb(info->opmode_ioaddr);
val &= mask;
val |= (opmode << shiftbit);
outb(val, info->opmode_ioaddr);
} else {
shiftbit = p * 2;
opmode = inb(info->opmode_ioaddr) >> shiftbit;
opmode &= OP_MODE_MASK;
if (copy_to_user(argp, &opmode, sizeof(int)))
return -EFAULT;
}
return 0;
}
if (cmd == MOXA_SET_SPECIAL_BAUD_RATE) {
int speed;
if (get_user(speed, (int __user *)argp))
return -EFAULT;
if (speed <= 0 || speed > info->max_baud)
return -EFAULT;
if (!info->tty || !info->tty->termios || !info->ioaddr)
return 0;
info->tty->termios->c_cflag &= ~(CBAUD | CBAUDEX);
for (i = 0; i < BAUD_TABLE_NO; i++)
if (speed == mxvar_baud_table[i])
break;
if (i == BAUD_TABLE_NO) {
info->tty->termios->c_cflag |= B_SPEC;
} else if (speed != 0)
info->tty->termios->c_cflag |= mxvar_baud_table1[i];
info->speed = speed;
spin_lock_irqsave(&info->slock, flags);
mxser_change_speed(info, NULL);
spin_unlock_irqrestore(&info->slock, flags);
return 0;
} else if (cmd == MOXA_GET_SPECIAL_BAUD_RATE) {
if (copy_to_user(argp, &info->speed, sizeof(int)))
return -EFAULT;
return 0;
}
if (cmd != TIOCGSERIAL && cmd != TIOCMIWAIT && cmd != TIOCGICOUNT &&
test_bit(TTY_IO_ERROR, &tty->flags))
return -EIO;
switch (cmd) {
case TCSBRK: /* SVID version: non-zero arg --> no break */
retval = tty_check_change(tty);
if (retval)
return retval;
tty_wait_until_sent(tty, 0);
if (!arg)
mxser_send_break(info, HZ / 4); /* 1/4 second */
return 0;
case TCSBRKP: /* support for POSIX tcsendbreak() */
retval = tty_check_change(tty);
if (retval)
return retval;
tty_wait_until_sent(tty, 0);
mxser_send_break(info, arg ? arg * (HZ / 10) : HZ / 4);
return 0;
case TIOCGSOFTCAR:
return put_user(C_CLOCAL(tty) ? 1 : 0, (unsigned long __user *)argp);
case TIOCSSOFTCAR:
if (get_user(templ, (unsigned long __user *) argp))
return -EFAULT;
arg = templ;
tty->termios->c_cflag = ((tty->termios->c_cflag & ~CLOCAL) | (arg ? CLOCAL : 0));
return 0;
case TIOCGSERIAL:
return mxser_get_serial_info(info, argp);
case TIOCSSERIAL:
return mxser_set_serial_info(info, argp);
case TIOCSERGETLSR: /* Get line status register */
return mxser_get_lsr_info(info, argp);
/*
* Wait for any of the 4 modem inputs (DCD,RI,DSR,CTS) to change
* - mask passed in arg for lines of interest
* (use |'ed TIOCM_RNG/DSR/CD/CTS for masking)
* Caller should use TIOCGICOUNT to see which one it was
*/
case TIOCMIWAIT:
spin_lock_irqsave(&info->slock, flags);
cnow = info->icount; /* note the counters on entry */
spin_unlock_irqrestore(&info->slock, flags);
wait_event_interruptible(info->delta_msr_wait, ({
cprev = cnow;
spin_lock_irqsave(&info->slock, flags);
cnow = info->icount; /* atomic copy */
spin_unlock_irqrestore(&info->slock, flags);
((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) ||
((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) ||
((arg & TIOCM_CD) && (cnow.dcd != cprev.dcd)) ||
((arg & TIOCM_CTS) && (cnow.cts != cprev.cts));
}));
break;
/*
* Get counter of input serial line interrupts (DCD,RI,DSR,CTS)
* Return: write counters to the user passed counter struct
* NB: both 1->0 and 0->1 transitions are counted except for
* RI where only 0->1 is counted.
*/
case TIOCGICOUNT:
spin_lock_irqsave(&info->slock, flags);
cnow = info->icount;
spin_unlock_irqrestore(&info->slock, flags);
p_cuser = argp;
if (put_user(cnow.frame, &p_cuser->frame))
return -EFAULT;
if (put_user(cnow.brk, &p_cuser->brk))
return -EFAULT;
if (put_user(cnow.overrun, &p_cuser->overrun))
return -EFAULT;
if (put_user(cnow.buf_overrun, &p_cuser->buf_overrun))
return -EFAULT;
if (put_user(cnow.parity, &p_cuser->parity))
return -EFAULT;
if (put_user(cnow.rx, &p_cuser->rx))
return -EFAULT;
if (put_user(cnow.tx, &p_cuser->tx))
return -EFAULT;
put_user(cnow.cts, &p_cuser->cts);
put_user(cnow.dsr, &p_cuser->dsr);
put_user(cnow.rng, &p_cuser->rng);
put_user(cnow.dcd, &p_cuser->dcd);
return 0;
case MOXA_HighSpeedOn:
return put_user(info->baud_base != 115200 ? 1 : 0, (int __user *)argp);
case MOXA_SDS_RSTICOUNTER:
info->mon_data.rxcnt = 0;
info->mon_data.txcnt = 0;
return 0;
case MOXA_ASPP_SETBAUD:{
long baud;
if (get_user(baud, (long __user *)argp))
return -EFAULT;
spin_lock_irqsave(&info->slock, flags);
mxser_set_baud(info, baud);
spin_unlock_irqrestore(&info->slock, flags);
return 0;
}
case MOXA_ASPP_GETBAUD:
if (copy_to_user(argp, &info->realbaud, sizeof(long)))
return -EFAULT;
return 0;
case MOXA_ASPP_OQUEUE:{
int len, lsr;
len = mxser_chars_in_buffer(tty);
lsr = inb(info->ioaddr + UART_LSR) & UART_LSR_TEMT;
len += (lsr ? 0 : 1);
if (copy_to_user(argp, &len, sizeof(int)))
return -EFAULT;
return 0;
}
case MOXA_ASPP_MON: {
int mcr, status;
status = mxser_get_msr(info->ioaddr, 1, tty->index);
mxser_check_modem_status(info, status);
mcr = inb(info->ioaddr + UART_MCR);
if (mcr & MOXA_MUST_MCR_XON_FLAG)
info->mon_data.hold_reason &= ~NPPI_NOTIFY_XOFFHOLD;
else
info->mon_data.hold_reason |= NPPI_NOTIFY_XOFFHOLD;
if (mcr & MOXA_MUST_MCR_TX_XON)
info->mon_data.hold_reason &= ~NPPI_NOTIFY_XOFFXENT;
else
info->mon_data.hold_reason |= NPPI_NOTIFY_XOFFXENT;
if (info->tty->hw_stopped)
info->mon_data.hold_reason |= NPPI_NOTIFY_CTSHOLD;
else
info->mon_data.hold_reason &= ~NPPI_NOTIFY_CTSHOLD;
if (copy_to_user(argp, &info->mon_data,
sizeof(struct mxser_mon)))
return -EFAULT;
return 0;
}
case MOXA_ASPP_LSTATUS: {
if (copy_to_user(argp, &info->err_shadow,
sizeof(unsigned char)))
return -EFAULT;
info->err_shadow = 0;
return 0;
}
case MOXA_SET_BAUD_METHOD: {
int method;
if (get_user(method, (int __user *)argp))
return -EFAULT;
mxser_set_baud_method[tty->index] = method;
if (copy_to_user(argp, &method, sizeof(int)))
return -EFAULT;
return 0;
}
default:
return -ENOIOCTLCMD;
}
return 0;
}
static void mxser_stoprx(struct tty_struct *tty)
{
struct mxser_port *info = tty->driver_data;
info->ldisc_stop_rx = 1;
if (I_IXOFF(tty)) {
if (info->board->chip_flag) {
info->IER &= ~MOXA_MUST_RECV_ISR;
outb(info->IER, info->ioaddr + UART_IER);
} else {
info->x_char = STOP_CHAR(tty);
outb(0, info->ioaddr + UART_IER);
info->IER |= UART_IER_THRI;
outb(info->IER, info->ioaddr + UART_IER);
}
}
if (info->tty->termios->c_cflag & CRTSCTS) {
info->MCR &= ~UART_MCR_RTS;
outb(info->MCR, info->ioaddr + UART_MCR);
}
}
/*
* This routine is called by the upper-layer tty layer to signal that
* incoming characters should be throttled.
*/
static void mxser_throttle(struct tty_struct *tty)
{
mxser_stoprx(tty);
}
static void mxser_unthrottle(struct tty_struct *tty)
{
struct mxser_port *info = tty->driver_data;
/* startrx */
info->ldisc_stop_rx = 0;
if (I_IXOFF(tty)) {
if (info->x_char)
info->x_char = 0;
else {
if (info->board->chip_flag) {
info->IER |= MOXA_MUST_RECV_ISR;
outb(info->IER, info->ioaddr + UART_IER);
} else {
info->x_char = START_CHAR(tty);
outb(0, info->ioaddr + UART_IER);
info->IER |= UART_IER_THRI;
outb(info->IER, info->ioaddr + UART_IER);
}
}
}
if (info->tty->termios->c_cflag & CRTSCTS) {
info->MCR |= UART_MCR_RTS;
outb(info->MCR, info->ioaddr + UART_MCR);
}
}
/*
* mxser_stop() and mxser_start()
*
* This routines are called before setting or resetting tty->stopped.
* They enable or disable transmitter interrupts, as necessary.
*/
static void mxser_stop(struct tty_struct *tty)
{
struct mxser_port *info = tty->driver_data;
unsigned long flags;
spin_lock_irqsave(&info->slock, flags);
if (info->IER & UART_IER_THRI) {
info->IER &= ~UART_IER_THRI;
outb(info->IER, info->ioaddr + UART_IER);
}
spin_unlock_irqrestore(&info->slock, flags);
}
static void mxser_start(struct tty_struct *tty)
{
struct mxser_port *info = tty->driver_data;
unsigned long flags;
spin_lock_irqsave(&info->slock, flags);
if (info->xmit_cnt && info->xmit_buf) {
outb(info->IER & ~UART_IER_THRI, info->ioaddr + UART_IER);
info->IER |= UART_IER_THRI;
outb(info->IER, info->ioaddr + UART_IER);
}
spin_unlock_irqrestore(&info->slock, flags);
}
static void mxser_set_termios(struct tty_struct *tty, struct ktermios *old_termios)
{
struct mxser_port *info = tty->driver_data;
unsigned long flags;
spin_lock_irqsave(&info->slock, flags);
mxser_change_speed(info, old_termios);
spin_unlock_irqrestore(&info->slock, flags);
if ((old_termios->c_cflag & CRTSCTS) &&
!(tty->termios->c_cflag & CRTSCTS)) {
tty->hw_stopped = 0;
mxser_start(tty);
}
/* Handle sw stopped */
if ((old_termios->c_iflag & IXON) &&
!(tty->termios->c_iflag & IXON)) {
tty->stopped = 0;
if (info->board->chip_flag) {
spin_lock_irqsave(&info->slock, flags);
DISABLE_MOXA_MUST_RX_SOFTWARE_FLOW_CONTROL(info->ioaddr);
spin_unlock_irqrestore(&info->slock, flags);
}
mxser_start(tty);
}
}
/*
* mxser_wait_until_sent() --- wait until the transmitter is empty
*/
static void mxser_wait_until_sent(struct tty_struct *tty, int timeout)
{
struct mxser_port *info = tty->driver_data;
unsigned long orig_jiffies, char_time;
int lsr;
if (info->type == PORT_UNKNOWN)
return;
if (info->xmit_fifo_size == 0)
return; /* Just in case.... */
orig_jiffies = jiffies;
/*
* Set the check interval to be 1/5 of the estimated time to
* send a single character, and make it at least 1. The check
* interval should also be less than the timeout.
*
* Note: we have to use pretty tight timings here to satisfy
* the NIST-PCTS.
*/
char_time = (info->timeout - HZ / 50) / info->xmit_fifo_size;
char_time = char_time / 5;
if (char_time == 0)
char_time = 1;
if (timeout && timeout < char_time)
char_time = timeout;
/*
* If the transmitter hasn't cleared in twice the approximate
* amount of time to send the entire FIFO, it probably won't
* ever clear. This assumes the UART isn't doing flow
* control, which is currently the case. Hence, if it ever
* takes longer than info->timeout, this is probably due to a
* UART bug of some kind. So, we clamp the timeout parameter at
* 2*info->timeout.
*/
if (!timeout || timeout > 2 * info->timeout)
timeout = 2 * info->timeout;
#ifdef SERIAL_DEBUG_RS_WAIT_UNTIL_SENT
printk(KERN_DEBUG "In rs_wait_until_sent(%d) check=%lu...",
timeout, char_time);
printk("jiff=%lu...", jiffies);
#endif
while (!((lsr = inb(info->ioaddr + UART_LSR)) & UART_LSR_TEMT)) {
#ifdef SERIAL_DEBUG_RS_WAIT_UNTIL_SENT
printk("lsr = %d (jiff=%lu)...", lsr, jiffies);
#endif
schedule_timeout_interruptible(char_time);
if (signal_pending(current))
break;
if (timeout && time_after(jiffies, orig_jiffies + timeout))
break;
}
set_current_state(TASK_RUNNING);
#ifdef SERIAL_DEBUG_RS_WAIT_UNTIL_SENT
printk("lsr = %d (jiff=%lu)...done\n", lsr, jiffies);
#endif
}
/*
* This routine is called by tty_hangup() when a hangup is signaled.
*/
static void mxser_hangup(struct tty_struct *tty)
{
struct mxser_port *info = tty->driver_data;
mxser_flush_buffer(tty);
mxser_shutdown(info);
info->event = 0;
info->count = 0;
info->flags &= ~ASYNC_NORMAL_ACTIVE;
info->tty = NULL;
wake_up_interruptible(&info->open_wait);
}
/*
* mxser_rs_break() --- routine which turns the break handling on or off
*/
static void mxser_rs_break(struct tty_struct *tty, int break_state)
{
struct mxser_port *info = tty->driver_data;
unsigned long flags;
spin_lock_irqsave(&info->slock, flags);
if (break_state == -1)
outb(inb(info->ioaddr + UART_LCR) | UART_LCR_SBC,
info->ioaddr + UART_LCR);
else
outb(inb(info->ioaddr + UART_LCR) & ~UART_LCR_SBC,
info->ioaddr + UART_LCR);
spin_unlock_irqrestore(&info->slock, flags);
}
static void mxser_receive_chars(struct mxser_port *port, int *status)
{
struct tty_struct *tty = port->tty;
unsigned char ch, gdl;
int ignored = 0;
int cnt = 0;
int recv_room;
int max = 256;
recv_room = tty->receive_room;
if ((recv_room == 0) && (!port->ldisc_stop_rx))
mxser_stoprx(tty);
if (port->board->chip_flag != MOXA_OTHER_UART) {
if (*status & UART_LSR_SPECIAL)
goto intr_old;
if (port->board->chip_flag == MOXA_MUST_MU860_HWID &&
(*status & MOXA_MUST_LSR_RERR))
goto intr_old;
if (*status & MOXA_MUST_LSR_RERR)
goto intr_old;
gdl = inb(port->ioaddr + MOXA_MUST_GDL_REGISTER);
if (port->board->chip_flag == MOXA_MUST_MU150_HWID)
gdl &= MOXA_MUST_GDL_MASK;
if (gdl >= recv_room) {
if (!port->ldisc_stop_rx)
mxser_stoprx(tty);
}
while (gdl--) {
ch = inb(port->ioaddr + UART_RX);
tty_insert_flip_char(tty, ch, 0);
cnt++;
}
goto end_intr;
}
intr_old:
do {
if (max-- < 0)
break;
ch = inb(port->ioaddr + UART_RX);
if (port->board->chip_flag && (*status & UART_LSR_OE))
outb(0x23, port->ioaddr + UART_FCR);
*status &= port->read_status_mask;
if (*status & port->ignore_status_mask) {
if (++ignored > 100)
break;
} else {
char flag = 0;
if (*status & UART_LSR_SPECIAL) {
if (*status & UART_LSR_BI) {
flag = TTY_BREAK;
port->icount.brk++;
if (port->flags & ASYNC_SAK)
do_SAK(tty);
} else if (*status & UART_LSR_PE) {
flag = TTY_PARITY;
port->icount.parity++;
} else if (*status & UART_LSR_FE) {
flag = TTY_FRAME;
port->icount.frame++;
} else if (*status & UART_LSR_OE) {
flag = TTY_OVERRUN;
port->icount.overrun++;
} else
flag = TTY_BREAK;
}
tty_insert_flip_char(tty, ch, flag);
cnt++;
if (cnt >= recv_room) {
if (!port->ldisc_stop_rx)
mxser_stoprx(tty);
break;
}
}
if (port->board->chip_flag)
break;
*status = inb(port->ioaddr + UART_LSR);
} while (*status & UART_LSR_DR);
end_intr:
mxvar_log.rxcnt[port->tty->index] += cnt;
port->mon_data.rxcnt += cnt;
port->mon_data.up_rxcnt += cnt;
/*
* We are called from an interrupt context with &port->slock
* being held. Drop it temporarily in order to prevent
* recursive locking.
*/
spin_unlock(&port->slock);
tty_flip_buffer_push(tty);
spin_lock(&port->slock);
}
static void mxser_transmit_chars(struct mxser_port *port)
{
int count, cnt;
if (port->x_char) {
outb(port->x_char, port->ioaddr + UART_TX);
port->x_char = 0;
mxvar_log.txcnt[port->tty->index]++;
port->mon_data.txcnt++;
port->mon_data.up_txcnt++;
port->icount.tx++;
return;
}
if (port->xmit_buf == 0)
return;
if ((port->xmit_cnt <= 0) || port->tty->stopped ||
(port->tty->hw_stopped &&
(port->type != PORT_16550A) &&
(!port->board->chip_flag))) {
port->IER &= ~UART_IER_THRI;
outb(port->IER, port->ioaddr + UART_IER);
return;
}
cnt = port->xmit_cnt;
count = port->xmit_fifo_size;
do {
outb(port->xmit_buf[port->xmit_tail++],
port->ioaddr + UART_TX);
port->xmit_tail = port->xmit_tail & (SERIAL_XMIT_SIZE - 1);
if (--port->xmit_cnt <= 0)
break;
} while (--count > 0);
mxvar_log.txcnt[port->tty->index] += (cnt - port->xmit_cnt);
port->mon_data.txcnt += (cnt - port->xmit_cnt);
port->mon_data.up_txcnt += (cnt - port->xmit_cnt);
port->icount.tx += (cnt - port->xmit_cnt);
if (port->xmit_cnt < WAKEUP_CHARS)
tty_wakeup(port->tty);
if (port->xmit_cnt <= 0) {
port->IER &= ~UART_IER_THRI;
outb(port->IER, port->ioaddr + UART_IER);
}
}
/*
* This is the serial driver's generic interrupt routine
*/
static irqreturn_t mxser_interrupt(int irq, void *dev_id)
{
int status, iir, i;
struct mxser_board *brd = NULL;
struct mxser_port *port;
int max, irqbits, bits, msr;
unsigned int int_cnt, pass_counter = 0;
int handled = IRQ_NONE;
for (i = 0; i < MXSER_BOARDS; i++)
if (dev_id == &mxser_boards[i]) {
brd = dev_id;
break;
}
if (i == MXSER_BOARDS)
goto irq_stop;
if (brd == NULL)
goto irq_stop;
max = brd->info->nports;
while (pass_counter++ < MXSER_ISR_PASS_LIMIT) {
irqbits = inb(brd->vector) & brd->vector_mask;
if (irqbits == brd->vector_mask)
break;
handled = IRQ_HANDLED;
for (i = 0, bits = 1; i < max; i++, irqbits |= bits, bits <<= 1) {
if (irqbits == brd->vector_mask)
break;
if (bits & irqbits)
continue;
port = &brd->ports[i];
int_cnt = 0;
spin_lock(&port->slock);
do {
iir = inb(port->ioaddr + UART_IIR);
if (iir & UART_IIR_NO_INT)
break;
iir &= MOXA_MUST_IIR_MASK;
if (!port->tty ||
(port->flags & ASYNC_CLOSING) ||
!(port->flags &
ASYNC_INITIALIZED)) {
status = inb(port->ioaddr + UART_LSR);
outb(0x27, port->ioaddr + UART_FCR);
inb(port->ioaddr + UART_MSR);
break;
}
status = inb(port->ioaddr + UART_LSR);
if (status & UART_LSR_PE)
port->err_shadow |= NPPI_NOTIFY_PARITY;
if (status & UART_LSR_FE)
port->err_shadow |= NPPI_NOTIFY_FRAMING;
if (status & UART_LSR_OE)
port->err_shadow |=
NPPI_NOTIFY_HW_OVERRUN;
if (status & UART_LSR_BI)
port->err_shadow |= NPPI_NOTIFY_BREAK;
if (port->board->chip_flag) {
if (iir == MOXA_MUST_IIR_GDA ||
iir == MOXA_MUST_IIR_RDA ||
iir == MOXA_MUST_IIR_RTO ||
iir == MOXA_MUST_IIR_LSR)
mxser_receive_chars(port,
&status);
} else {
status &= port->read_status_mask;
if (status & UART_LSR_DR)
mxser_receive_chars(port,
&status);
}
msr = inb(port->ioaddr + UART_MSR);
if (msr & UART_MSR_ANY_DELTA)
mxser_check_modem_status(port, msr);
if (port->board->chip_flag) {
if (iir == 0x02 && (status &
UART_LSR_THRE))
mxser_transmit_chars(port);
} else {
if (status & UART_LSR_THRE)
mxser_transmit_chars(port);
}
} while (int_cnt++ < MXSER_ISR_PASS_LIMIT);
spin_unlock(&port->slock);
}
}
irq_stop:
return handled;
}
static const struct tty_operations mxser_ops = {
.open = mxser_open,
.close = mxser_close,
.write = mxser_write,
.put_char = mxser_put_char,
.flush_chars = mxser_flush_chars,
.write_room = mxser_write_room,
.chars_in_buffer = mxser_chars_in_buffer,
.flush_buffer = mxser_flush_buffer,
.ioctl = mxser_ioctl,
.throttle = mxser_throttle,
.unthrottle = mxser_unthrottle,
.set_termios = mxser_set_termios,
.stop = mxser_stop,
.start = mxser_start,
.hangup = mxser_hangup,
.break_ctl = mxser_rs_break,
.wait_until_sent = mxser_wait_until_sent,
.tiocmget = mxser_tiocmget,
.tiocmset = mxser_tiocmset,
};
/*
* The MOXA Smartio/Industio serial driver boot-time initialization code!
*/
static void mxser_release_res(struct mxser_board *brd, struct pci_dev *pdev,
unsigned int irq)
{
if (irq)
free_irq(brd->irq, brd);
if (pdev != NULL) { /* PCI */
#ifdef CONFIG_PCI
pci_release_region(pdev, 2);
pci_release_region(pdev, 3);
#endif
} else {
release_region(brd->ports[0].ioaddr, 8 * brd->info->nports);
release_region(brd->vector, 1);
}
}
static int __devinit mxser_initbrd(struct mxser_board *brd,
struct pci_dev *pdev)
{
struct mxser_port *info;
unsigned int i;
int retval;
printk(KERN_INFO "max. baud rate = %d bps.\n", brd->ports[0].max_baud);
for (i = 0; i < brd->info->nports; i++) {
info = &brd->ports[i];
info->board = brd;
info->stop_rx = 0;
info->ldisc_stop_rx = 0;
/* Enhance mode enabled here */
if (brd->chip_flag != MOXA_OTHER_UART)
ENABLE_MOXA_MUST_ENCHANCE_MODE(info->ioaddr);
info->flags = ASYNC_SHARE_IRQ;
info->type = brd->uart_type;
process_txrx_fifo(info);
info->custom_divisor = info->baud_base * 16;
info->close_delay = 5 * HZ / 10;
info->closing_wait = 30 * HZ;
info->normal_termios = mxvar_sdriver->init_termios;
init_waitqueue_head(&info->open_wait);
init_waitqueue_head(&info->delta_msr_wait);
info->speed = 9600;
memset(&info->mon_data, 0, sizeof(struct mxser_mon));
info->err_shadow = 0;
spin_lock_init(&info->slock);
/* before set INT ISR, disable all int */
outb(inb(info->ioaddr + UART_IER) & 0xf0,
info->ioaddr + UART_IER);
}
retval = request_irq(brd->irq, mxser_interrupt, IRQF_SHARED, "mxser",
brd);
if (retval) {
printk(KERN_ERR "Board %s: Request irq failed, IRQ (%d) may "
"conflict with another device.\n",
brd->info->name, brd->irq);
/* We hold resources, we need to release them. */
mxser_release_res(brd, pdev, 0);
}
return retval;
}
static int __init mxser_get_ISA_conf(int cap, struct mxser_board *brd)
{
int id, i, bits;
unsigned short regs[16], irq;
unsigned char scratch, scratch2;
brd->chip_flag = MOXA_OTHER_UART;
id = mxser_read_register(cap, regs);
switch (id) {
case C168_ASIC_ID:
brd->info = &mxser_cards[0];
break;
case C104_ASIC_ID:
brd->info = &mxser_cards[1];
break;
case CI104J_ASIC_ID:
brd->info = &mxser_cards[2];
break;
case C102_ASIC_ID:
brd->info = &mxser_cards[5];
break;
case CI132_ASIC_ID:
brd->info = &mxser_cards[6];
break;
case CI134_ASIC_ID:
brd->info = &mxser_cards[7];
break;
default:
return 0;
}
irq = 0;
/* some ISA cards have 2 ports, but we want to see them as 4-port (why?)
Flag-hack checks if configuration should be read as 2-port here. */
if (brd->info->nports == 2 || (brd->info->flags & MXSER_HAS2)) {
irq = regs[9] & 0xF000;
irq = irq | (irq >> 4);
if (irq != (regs[9] & 0xFF00))
return MXSER_ERR_IRQ_CONFLIT;
} else if (brd->info->nports == 4) {
irq = regs[9] & 0xF000;
irq = irq | (irq >> 4);
irq = irq | (irq >> 8);
if (irq != regs[9])
return MXSER_ERR_IRQ_CONFLIT;
} else if (brd->info->nports == 8) {
irq = regs[9] & 0xF000;
irq = irq | (irq >> 4);
irq = irq | (irq >> 8);
if ((irq != regs[9]) || (irq != regs[10]))
return MXSER_ERR_IRQ_CONFLIT;
}
if (!irq)
return MXSER_ERR_IRQ;
brd->irq = ((int)(irq & 0xF000) >> 12);
for (i = 0; i < 8; i++)
brd->ports[i].ioaddr = (int) regs[i + 1] & 0xFFF8;
if ((regs[12] & 0x80) == 0)
return MXSER_ERR_VECTOR;
brd->vector = (int)regs[11]; /* interrupt vector */
if (id == 1)
brd->vector_mask = 0x00FF;
else
brd->vector_mask = 0x000F;
for (i = 7, bits = 0x0100; i >= 0; i--, bits <<= 1) {
if (regs[12] & bits) {
brd->ports[i].baud_base = 921600;
brd->ports[i].max_baud = 921600;
} else {
brd->ports[i].baud_base = 115200;
brd->ports[i].max_baud = 115200;
}
}
scratch2 = inb(cap + UART_LCR) & (~UART_LCR_DLAB);
outb(scratch2 | UART_LCR_DLAB, cap + UART_LCR);
outb(0, cap + UART_EFR); /* EFR is the same as FCR */
outb(scratch2, cap + UART_LCR);
outb(UART_FCR_ENABLE_FIFO, cap + UART_FCR);
scratch = inb(cap + UART_IIR);
if (scratch & 0xC0)
brd->uart_type = PORT_16550A;
else
brd->uart_type = PORT_16450;
if (!request_region(brd->ports[0].ioaddr, 8 * brd->info->nports,
"mxser(IO)"))
return MXSER_ERR_IOADDR;
if (!request_region(brd->vector, 1, "mxser(vector)")) {
release_region(brd->ports[0].ioaddr, 8 * brd->info->nports);
return MXSER_ERR_VECTOR;
}
return brd->info->nports;
}
static int __devinit mxser_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
#ifdef CONFIG_PCI
struct mxser_board *brd;
unsigned int i, j;
unsigned long ioaddress;
int retval = -EINVAL;
for (i = 0; i < MXSER_BOARDS; i++)
if (mxser_boards[i].info == NULL)
break;
if (i >= MXSER_BOARDS) {
printk(KERN_ERR "Too many Smartio/Industio family boards found "
"(maximum %d), board not configured\n", MXSER_BOARDS);
goto err;
}
brd = &mxser_boards[i];
brd->idx = i * MXSER_PORTS_PER_BOARD;
printk(KERN_INFO "Found MOXA %s board (BusNo=%d, DevNo=%d)\n",
mxser_cards[ent->driver_data].name,
pdev->bus->number, PCI_SLOT(pdev->devfn));
retval = pci_enable_device(pdev);
if (retval) {
printk(KERN_ERR "Moxa SmartI/O PCI enable fail !\n");
goto err;
}
/* io address */
ioaddress = pci_resource_start(pdev, 2);
retval = pci_request_region(pdev, 2, "mxser(IO)");
if (retval)
goto err;
brd->info = &mxser_cards[ent->driver_data];
for (i = 0; i < brd->info->nports; i++)
brd->ports[i].ioaddr = ioaddress + 8 * i;
/* vector */
ioaddress = pci_resource_start(pdev, 3);
retval = pci_request_region(pdev, 3, "mxser(vector)");
if (retval)
goto err_relio;
brd->vector = ioaddress;
/* irq */
brd->irq = pdev->irq;
brd->chip_flag = CheckIsMoxaMust(brd->ports[0].ioaddr);
brd->uart_type = PORT_16550A;
brd->vector_mask = 0;
for (i = 0; i < brd->info->nports; i++) {
for (j = 0; j < UART_INFO_NUM; j++) {
if (Gpci_uart_info[j].type == brd->chip_flag) {
brd->ports[i].max_baud =
Gpci_uart_info[j].max_baud;
/* exception....CP-102 */
if (brd->info->flags & MXSER_HIGHBAUD)
brd->ports[i].max_baud = 921600;
break;
}
}
}
if (brd->chip_flag == MOXA_MUST_MU860_HWID) {
for (i = 0; i < brd->info->nports; i++) {
if (i < 4)
brd->ports[i].opmode_ioaddr = ioaddress + 4;
else
brd->ports[i].opmode_ioaddr = ioaddress + 0x0c;
}
outb(0, ioaddress + 4); /* default set to RS232 mode */
outb(0, ioaddress + 0x0c); /* default set to RS232 mode */
}
for (i = 0; i < brd->info->nports; i++) {
brd->vector_mask |= (1 << i);
brd->ports[i].baud_base = 921600;
}
/* mxser_initbrd will hook ISR. */
retval = mxser_initbrd(brd, pdev);
if (retval)
goto err_null;
for (i = 0; i < brd->info->nports; i++)
tty_register_device(mxvar_sdriver, brd->idx + i, &pdev->dev);
pci_set_drvdata(pdev, brd);
return 0;
err_relio:
pci_release_region(pdev, 2);
err_null:
brd->info = NULL;
err:
return retval;
#else
return -ENODEV;
#endif
}
static void __devexit mxser_remove(struct pci_dev *pdev)
{
struct mxser_board *brd = pci_get_drvdata(pdev);
unsigned int i;
for (i = 0; i < brd->info->nports; i++)
tty_unregister_device(mxvar_sdriver, brd->idx + i);
mxser_release_res(brd, pdev, 1);
brd->info = NULL;
}
static struct pci_driver mxser_driver = {
.name = "mxser",
.id_table = mxser_pcibrds,
.probe = mxser_probe,
.remove = __devexit_p(mxser_remove)
};
static int __init mxser_module_init(void)
{
struct mxser_board *brd;
unsigned long cap;
unsigned int i, m, isaloop;
int retval, b;
pr_debug("Loading module mxser ...\n");
mxvar_sdriver = alloc_tty_driver(MXSER_PORTS + 1);
if (!mxvar_sdriver)
return -ENOMEM;
printk(KERN_INFO "MOXA Smartio/Industio family driver version %s\n",
MXSER_VERSION);
/* Initialize the tty_driver structure */
mxvar_sdriver->owner = THIS_MODULE;
mxvar_sdriver->magic = TTY_DRIVER_MAGIC;
mxvar_sdriver->name = "ttyMI";
mxvar_sdriver->major = ttymajor;
mxvar_sdriver->minor_start = 0;
mxvar_sdriver->num = MXSER_PORTS + 1;
mxvar_sdriver->type = TTY_DRIVER_TYPE_SERIAL;
mxvar_sdriver->subtype = SERIAL_TYPE_NORMAL;
mxvar_sdriver->init_termios = tty_std_termios;
mxvar_sdriver->init_termios.c_cflag = B9600|CS8|CREAD|HUPCL|CLOCAL;
mxvar_sdriver->flags = TTY_DRIVER_REAL_RAW|TTY_DRIVER_DYNAMIC_DEV;
tty_set_operations(mxvar_sdriver, &mxser_ops);
retval = tty_register_driver(mxvar_sdriver);
if (retval) {
printk(KERN_ERR "Couldn't install MOXA Smartio/Industio family "
"tty driver !\n");
goto err_put;
}
mxvar_diagflag = 0;
m = 0;
/* Start finding ISA boards here */
for (isaloop = 0; isaloop < 2; isaloop++)
for (b = 0; b < MXSER_BOARDS && m < MXSER_BOARDS; b++) {
if (!isaloop)
cap = mxserBoardCAP[b]; /* predefined */
else
cap = ioaddr[b]; /* module param */
if (!cap)
continue;
brd = &mxser_boards[m];
retval = mxser_get_ISA_conf(cap, brd);
if (retval != 0)
printk(KERN_INFO "Found MOXA %s board "
"(CAP=0x%x)\n",
brd->info->name, ioaddr[b]);
if (retval <= 0) {
if (retval == MXSER_ERR_IRQ)
printk(KERN_ERR "Invalid interrupt "
"number, board not "
"configured\n");
else if (retval == MXSER_ERR_IRQ_CONFLIT)
printk(KERN_ERR "Invalid interrupt "
"number, board not "
"configured\n");
else if (retval == MXSER_ERR_VECTOR)
printk(KERN_ERR "Invalid interrupt "
"vector, board not "
"configured\n");
else if (retval == MXSER_ERR_IOADDR)
printk(KERN_ERR "Invalid I/O address, "
"board not configured\n");
brd->info = NULL;
continue;
}
/* mxser_initbrd will hook ISR. */
if (mxser_initbrd(brd, NULL) < 0) {
brd->info = NULL;
continue;
}
brd->idx = m * MXSER_PORTS_PER_BOARD;
for (i = 0; i < brd->info->nports; i++)
tty_register_device(mxvar_sdriver, brd->idx + i,
NULL);
m++;
}
retval = pci_register_driver(&mxser_driver);
if (retval) {
printk(KERN_ERR "Can't register pci driver\n");
if (!m) {
retval = -ENODEV;
goto err_unr;
} /* else: we have some ISA cards under control */
}
pr_debug("Done.\n");
return 0;
err_unr:
tty_unregister_driver(mxvar_sdriver);
err_put:
put_tty_driver(mxvar_sdriver);
return retval;
}
static void __exit mxser_module_exit(void)
{
unsigned int i, j;
pr_debug("Unloading module mxser ...\n");
pci_unregister_driver(&mxser_driver);
for (i = 0; i < MXSER_BOARDS; i++) /* ISA remains */
if (mxser_boards[i].info != NULL)
for (j = 0; j < mxser_boards[i].info->nports; j++)
tty_unregister_device(mxvar_sdriver,
mxser_boards[i].idx + j);
tty_unregister_driver(mxvar_sdriver);
put_tty_driver(mxvar_sdriver);
for (i = 0; i < MXSER_BOARDS; i++)
if (mxser_boards[i].info != NULL)
mxser_release_res(&mxser_boards[i], NULL, 1);
pr_debug("Done.\n");
}
module_init(mxser_module_init);
module_exit(mxser_module_exit);
| darth-llamah/kernel-caanoo | drivers/char/mxser_new.c | C | gpl-2.0 | 72,367 | [
30522,
1013,
1008,
1008,
25630,
8043,
1012,
1039,
1011,
1011,
9587,
18684,
6047,
3695,
1013,
27746,
3775,
2080,
2155,
4800,
6442,
7642,
4062,
1012,
1008,
1008,
9385,
1006,
1039,
1007,
2639,
1011,
2294,
9587,
18684,
6786,
1006,
2490,
1030,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#include "ThinObject.h"
#include "Object.h"
#include "SnowString.h"
#include "Exception.h"
namespace snow {
static volatile uintx global_object_id_counter = 1;
void ThinObject::init() {
m_Info.frozen = false;
m_Info.gc_lock = false;
// XXX: With multithreading, this will most certainly go wrong.
#ifdef ARCH_IS_64_BIT
ASSERT(global_object_id_counter < (1LU<<61));
#else
ASSERT(global_object_id_counter < (1<<29));
#endif
m_Info.id = global_object_id_counter++;
}
Value ThinObject::get_raw(Symbol name) const {
return prototype()->get_raw(name);
}
Value ThinObject::set_raw(Symbol name, const Value&) {
throw_exception(new String("Thin objects cannot have members assigned. Modify the prototype, or create a wrapper."));
return nil();
}
Value ThinObject::set(const Value& self, Symbol member, const Value& val) {
return prototype()->set(self, member, val);
}
Value ThinObject::get(const Value& self, Symbol member) const {
return prototype()->get(self, member);
}
}
| simonask/snow-deprecated | src/runtime/ThinObject.cpp | C++ | isc | 1,014 | [
30522,
1001,
2421,
1000,
4857,
16429,
20614,
1012,
1044,
1000,
1001,
2421,
1000,
4874,
1012,
1044,
1000,
1001,
2421,
1000,
4586,
3367,
4892,
1012,
1044,
1000,
1001,
2421,
1000,
6453,
1012,
1044,
1000,
3415,
15327,
4586,
1063,
10763,
20606,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Copyright 2016 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs
*/
#include "gk104.h"
#include "changk104.h"
static const struct nvkm_fifo_func
gk110_fifo = {
.dtor = gk104_fifo_dtor,
.oneinit = gk104_fifo_oneinit,
.init = gk104_fifo_init,
.fini = gk104_fifo_fini,
.intr = gk104_fifo_intr,
.uevent_init = gk104_fifo_uevent_init,
.uevent_fini = gk104_fifo_uevent_fini,
.chan = {
&gk110_fifo_gpfifo_oclass,
NULL
},
};
int
gk110_fifo_new(struct nvkm_device *device, int index, struct nvkm_fifo **pfifo)
{
return gk104_fifo_new_(&gk110_fifo, device, index, 4096, pfifo);
}
| cneira/ebpf-backports | linux-3.10.0-514.21.1.el7.x86_64/drivers/gpu/drm/nouveau/nvkm/engine/fifo/gk110.c | C | gpl-2.0 | 1,662 | [
30522,
1013,
1008,
1008,
9385,
2355,
2417,
6045,
4297,
1012,
1008,
1008,
6656,
2003,
2182,
3762,
4379,
1010,
2489,
1997,
3715,
1010,
2000,
2151,
2711,
11381,
1037,
1008,
6100,
1997,
2023,
4007,
1998,
3378,
12653,
6764,
1006,
1996,
1000,
4... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Doctrine\PropertyInfo;
use Doctrine\Common\Persistence\Mapping\ClassMetadataFactory;
use Doctrine\Common\Persistence\Mapping\MappingException;
use Doctrine\DBAL\Types\Type as DBALType;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Doctrine\ORM\Mapping\MappingException as OrmMappingException;
use Symfony\Component\PropertyInfo\PropertyListExtractorInterface;
use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface;
use Symfony\Component\PropertyInfo\Type;
/**
* Extracts data using Doctrine ORM and ODM metadata.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class DoctrineExtractor implements PropertyListExtractorInterface, PropertyTypeExtractorInterface
{
/**
* @var ClassMetadataFactory
*/
private $classMetadataFactory;
public function __construct(ClassMetadataFactory $classMetadataFactory)
{
$this->classMetadataFactory = $classMetadataFactory;
}
/**
* {@inheritdoc}
*/
public function getProperties($class, array $context = array())
{
try {
$metadata = $this->classMetadataFactory->getMetadataFor($class);
} catch (MappingException $exception) {
return;
} catch (OrmMappingException $exception) {
return;
}
return array_merge($metadata->getFieldNames(), $metadata->getAssociationNames());
}
/**
* {@inheritdoc}
*/
public function getTypes($class, $property, array $context = array())
{
try {
$metadata = $this->classMetadataFactory->getMetadataFor($class);
} catch (MappingException $exception) {
return;
} catch (OrmMappingException $exception) {
return;
}
if ($metadata->hasAssociation($property)) {
$class = $metadata->getAssociationTargetClass($property);
if ($metadata->isSingleValuedAssociation($property)) {
if ($metadata instanceof ClassMetadataInfo) {
$associationMapping = $metadata->getAssociationMapping($property);
$nullable = $this->isAssociationNullable($associationMapping);
} else {
$nullable = false;
}
return array(new Type(Type::BUILTIN_TYPE_OBJECT, $nullable, $class));
}
$collectionKeyType = Type::BUILTIN_TYPE_INT;
if ($metadata instanceof ClassMetadataInfo) {
$associationMapping = $metadata->getAssociationMapping($property);
if (isset($associationMapping['indexBy'])) {
$indexProperty = $associationMapping['indexBy'];
$subMetadata = $this->classMetadataFactory->getMetadataFor($associationMapping['targetEntity']);
$typeOfField = $subMetadata->getTypeOfField($indexProperty);
$collectionKeyType = $this->getPhpType($typeOfField);
}
}
return array(new Type(
Type::BUILTIN_TYPE_OBJECT,
false,
'Doctrine\Common\Collections\Collection',
true,
new Type($collectionKeyType),
new Type(Type::BUILTIN_TYPE_OBJECT, false, $class)
));
}
if ($metadata->hasField($property)) {
$typeOfField = $metadata->getTypeOfField($property);
$nullable = $metadata instanceof ClassMetadataInfo && $metadata->isNullable($property);
switch ($typeOfField) {
case DBALType::DATE:
case DBALType::DATETIME:
case DBALType::DATETIMETZ:
case 'vardatetime':
case DBALType::TIME:
return array(new Type(Type::BUILTIN_TYPE_OBJECT, $nullable, 'DateTime'));
case DBALType::TARRAY:
return array(new Type(Type::BUILTIN_TYPE_ARRAY, $nullable, null, true));
case DBALType::SIMPLE_ARRAY:
return array(new Type(Type::BUILTIN_TYPE_ARRAY, $nullable, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_STRING)));
case DBALType::JSON_ARRAY:
return array(new Type(Type::BUILTIN_TYPE_ARRAY, $nullable, null, true));
default:
$builtinType = $this->getPhpType($typeOfField);
return $builtinType ? array(new Type($builtinType, $nullable)) : null;
}
}
}
/**
* Determines whether an association is nullable.
*
* @param array $associationMapping
*
* @return bool
*
* @see https://github.com/doctrine/doctrine2/blob/v2.5.4/lib/Doctrine/ORM/Tools/EntityGenerator.php#L1221-L1246
*/
private function isAssociationNullable(array $associationMapping)
{
if (isset($associationMapping['id']) && $associationMapping['id']) {
return false;
}
if (!isset($associationMapping['joinColumns'])) {
return true;
}
$joinColumns = $associationMapping['joinColumns'];
foreach ($joinColumns as $joinColumn) {
if (isset($joinColumn['nullable']) && !$joinColumn['nullable']) {
return false;
}
}
return true;
}
/**
* Gets the corresponding built-in PHP type.
*
* @param string $doctrineType
*
* @return string|null
*/
private function getPhpType($doctrineType)
{
switch ($doctrineType) {
case DBALType::SMALLINT:
case DBALType::INTEGER:
return Type::BUILTIN_TYPE_INT;
case DBALType::FLOAT:
return Type::BUILTIN_TYPE_FLOAT;
case DBALType::BIGINT:
case DBALType::STRING:
case DBALType::TEXT:
case DBALType::GUID:
case DBALType::DECIMAL:
return Type::BUILTIN_TYPE_STRING;
case DBALType::BOOLEAN:
return Type::BUILTIN_TYPE_BOOL;
case DBALType::BLOB:
case 'binary':
return Type::BUILTIN_TYPE_RESOURCE;
case DBALType::OBJECT:
return Type::BUILTIN_TYPE_OBJECT;
}
}
}
| dkyinsaat/DKY | vendor/symfony/symfony/src/Symfony/Bridge/Doctrine/PropertyInfo/DoctrineExtractor.php | PHP | mit | 6,561 | [
30522,
1026,
1029,
25718,
1013,
1008,
1008,
2023,
5371,
2003,
2112,
1997,
1996,
25353,
2213,
14876,
4890,
7427,
1012,
1008,
1008,
1006,
1039,
1007,
6904,
11283,
2078,
8962,
2368,
19562,
1026,
6904,
11283,
2078,
1030,
25353,
2213,
14876,
489... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// Generated by CoffeeScript 1.4.0
(function() {
"use strict";
var UserCommand, exports, _ref,
__slice = [].slice;
var exports = (_ref = window.chat) != null ? _ref : window.chat = {};
/*
* Represents a user command, like /kick or /say.
*/
UserCommand = (function() {
function UserCommand(name, description) {
this.description = description;
this.name = name;
this.describe(this.description);
this._hasValidArgs = false;
}
/*
* Describe the command using the following format:
* * description - a description of what the command does; used with /help
* <command>
* * category - what category the command falls under. This is used with /help
* * params - what parameters the command takes, 'opt_<name>' for optional,
* '<name>...' for variable
*##
* * validateArgs - returns a truthy variable if the given arguments are valid.
* * requires - what the command requires to run (e.g. a connections to an IRC
* server)
* * usage - manually set a usage message, one will be generated if not specified
* * run - the function to call when the command is run
*/
UserCommand.prototype.describe = function(description) {
var _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7;
if ((_ref1 = this._description) == null) {
this._description = description.description;
}
if ((_ref2 = this._params) == null) {
this._params = description.params;
}
if ((_ref3 = this._requires) == null) {
this._requires = description.requires;
}
if ((_ref4 = this._validateArgs) == null) {
this._validateArgs = description.validateArgs;
}
if ((_ref5 = this._usage) == null) {
this._usage = description.usage;
}
if ((_ref6 = this.run) == null) {
this.run = description.run;
}
return (_ref7 = this.category) != null ? _ref7 : this.category = description.category;
};
/*
* Try running the command. A command can fail to run if its requirements
* aren't met (e.g. needs a connection to the internet) or the specified
* arguments are invalid. In these cases a help message is displayed.
* @param {Context} context Which server/channel the command came from.
* @param {Object...} args Arguments for the command.
*/
UserCommand.prototype.tryToRun = function() {
var args, context;
context = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
this.setContext(context);
if (!this.canRun()) {
if (this.shouldDisplayFailedToRunMessage()) {
this.displayHelp();
}
return;
}
this.setArgs.apply(this, args);
if (this._hasValidArgs) {
return this.run();
} else {
return this.displayHelp();
}
};
UserCommand.prototype.setChat = function(chat) {
this.chat = chat;
};
UserCommand.prototype.setContext = function(context) {
this.win = this.chat.determineWindow(context);
if (this.win !== window.chat.NO_WINDOW) {
this.conn = this.win.conn;
return this.chan = this.win.target;
}
};
UserCommand.prototype.setArgs = function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return this._hasValidArgs = this._tryToAssignArgs(args) && (!this._validateArgs || !!this._validateArgs());
};
UserCommand.prototype._tryToAssignArgs = function(args) {
var i, param, params, _i, _len;
this.args = [];
this._removeTrailingWhiteSpace(args);
if (!this._params) {
return args.length === 0;
}
this._resetParams();
this._truncateVariableArgs(args);
params = this._truncateExtraOptionalParams(args.length);
if (args.length !== params.length) {
return false;
}
for (i = _i = 0, _len = params.length; _i < _len; i = ++_i) {
param = params[i];
this[this._getParamName(param)] = args[i];
}
this.args = args;
return true;
};
UserCommand.prototype._resetParams = function() {
var param, _i, _len, _ref1, _results;
_ref1 = this._params;
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
param = _ref1[_i];
_results.push(this[this._getParamName(param)] = void 0);
}
return _results;
};
UserCommand.prototype._removeTrailingWhiteSpace = function(args) {
var i, _i, _ref1, _results;
_results = [];
for (i = _i = _ref1 = args.length - 1; _ref1 <= 0 ? _i <= 0 : _i >= 0; i = _ref1 <= 0 ? ++_i : --_i) {
if (args[i] === '') {
_results.push(args.splice(i, 1));
} else {
break;
}
}
return _results;
};
/*
* Join all arguments that fit under the variable argument param.
* Note: only the last argument is allowd to be variable.
*/
UserCommand.prototype._truncateVariableArgs = function(args) {
var _ref1;
if (args.length < this._params.length) {
return args;
}
if (this._isVariable(this._params[this._params.length - 1])) {
args[this._params.length - 1] = (_ref1 = args.slice(this._params.length - 1)) != null ? _ref1.join(' ') : void 0;
return args.length = this._params.length;
}
};
UserCommand.prototype._truncateExtraOptionalParams = function(numArgs) {
var extraParams, i, param, params, _i, _ref1;
extraParams = this._params.length - numArgs;
if (extraParams <= 0) {
return this._params;
}
params = [];
for (i = _i = _ref1 = this._params.length - 1; _ref1 <= 0 ? _i <= 0 : _i >= 0; i = _ref1 <= 0 ? ++_i : --_i) {
param = this._params[i];
if (extraParams > 0 && this._isOptional(param)) {
extraParams--;
} else {
params.splice(0, 0, param);
}
}
return params;
};
/*
* When a command can't run, determine if a helpful message should be
* displayed to the user.
*/
UserCommand.prototype.shouldDisplayFailedToRunMessage = function() {
if (this.win === window.chat.NO_WINDOW) {
return false;
}
return this.name !== 'say';
};
/*
* Commands can only run if their requirements are met (e.g. connected to the
* internet, in a channel, etc) and a run method is defined.
*/
UserCommand.prototype.canRun = function(opt_context) {
var requirement, _i, _len, _ref1;
if (opt_context) {
this.setContext(opt_context);
}
if (!this.run) {
return false;
}
if (!this._requires) {
return true;
}
_ref1 = this._requires;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
requirement = _ref1[_i];
if (!this._meetsRequirement(requirement)) {
return false;
}
}
return true;
};
UserCommand.prototype._meetsRequirement = function(requirement) {
var _ref1;
switch (requirement) {
case 'online':
return isOnline();
case 'connection':
return !!this.conn && isOnline();
case 'channel':
return !!this.chan;
default:
return ((_ref1 = this.conn) != null ? _ref1.irc.state : void 0) === requirement;
}
};
UserCommand.prototype.displayHelp = function(win) {
if (win == null) {
win = this.win;
}
return win.message('', html.escape(this.getHelp()), 'notice help');
};
UserCommand.prototype.getHelp = function() {
var descriptionText, usageText, _ref1;
descriptionText = this._description ? ", " + this._description : '';
if (this._usage) {
usageText = ' ' + this._usage;
}
if (usageText == null) {
usageText = ((_ref1 = this._params) != null ? _ref1.length : void 0) > 0 ? " " + (this._getUsage()) : '';
}
return this.name.toUpperCase() + usageText + descriptionText + '.';
};
UserCommand.prototype._getUsage = function() {
var param, paramDescription, paramName, _i, _len, _ref1;
paramDescription = [];
_ref1 = this._params;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
param = _ref1[_i];
paramName = this._getParamName(param);
if (this._isOptional(param)) {
paramName = "[" + paramName + "]";
} else {
paramName = "<" + paramName + ">";
}
paramDescription.push(paramName);
}
return paramDescription.join(' ');
};
UserCommand.prototype._getParamName = function(param) {
if (this._isOptional(param)) {
param = param.slice(4);
}
if (this._isVariable(param)) {
param = param.slice(0, +(param.length - 4) + 1 || 9e9);
}
return param;
};
UserCommand.prototype._isOptional = function(param) {
return param.indexOf('opt_') === 0;
};
UserCommand.prototype._isVariable = function(param) {
return (param != null ? param.slice(param.length - 3) : void 0) === '...';
};
UserCommand.prototype.isOwnNick = function(nick) {
var _ref1;
if (nick == null) {
nick = this.nick;
}
return irc.util.nicksEqual((_ref1 = this.conn) != null ? _ref1.irc.nick : void 0, nick);
};
UserCommand.prototype.displayDirectMessage = function(nick, message) {
var _ref1;
if (nick == null) {
nick = this.nick;
}
if (message == null) {
message = this.message;
}
if (((_ref1 = this.conn) != null ? _ref1.windows[nick] : void 0) != null) {
return this._displayDirectMessageInPrivateChannel(nick, message);
} else {
return this._displayDirectMessageInline(nick, message);
}
};
/*
* Used with /msg. Displays the message in a private channel.
*/
UserCommand.prototype._displayDirectMessageInPrivateChannel = function(nick, message) {
var context;
context = {
server: this.conn.name,
channel: nick
};
return this.chat.displayMessage('privmsg', context, this.conn.irc.nick, message);
};
/*
* Used with /msg. Displays the private message in the current window.
* Direct messages always display inline until the user receives a response.
*/
UserCommand.prototype._displayDirectMessageInline = function(nick, message) {
return this.displayMessageWithStyle('privmsg', nick, message, 'direct');
};
UserCommand.prototype.displayMessage = function() {
var args, context, type, _ref1, _ref2;
type = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
context = {
server: (_ref1 = this.conn) != null ? _ref1.name : void 0,
channel: this.chan
};
return (_ref2 = this.chat).displayMessage.apply(_ref2, [type, context].concat(__slice.call(args)));
};
/*
* Displays a message with a custom style. This is useful for indicating that
* a message be rendered in a special way (e.g. no pretty formatting).
*/
UserCommand.prototype.displayMessageWithStyle = function() {
var args, e, style, type, _i, _ref1;
type = arguments[0], args = 3 <= arguments.length ? __slice.call(arguments, 1, _i = arguments.length - 1) : (_i = 1, []), style = arguments[_i++];
e = (function(func, args, ctor) {
ctor.prototype = func.prototype;
var child = new ctor, result = func.apply(child, args);
return Object(result) === result ? result : child;
})(Event, ['message', type].concat(__slice.call(args)), function(){});
e.setContext((_ref1 = this.conn) != null ? _ref1.name : void 0, this.chan);
e.addStyle(style);
return this.chat.emit(e.type, e);
};
UserCommand.prototype.handleCTCPRequest = function(nick, type) {
var delimiter, message;
this.displayDirectMessage(nick, "CTCP " + type);
delimiter = irc.CTCPHandler.DELIMITER;
message = delimiter + type + delimiter;
return this.conn.irc.doCommand('PRIVMSG', nick, message);
};
/*
* Used to set the arguments for MODE shortcut commands.
* @param {string} type E.g. /op, /voice, etc.
*/
UserCommand.prototype.setModeArgs = function(type) {
this.nicks = [this.nick];
this.target = this.chan;
return this.mode = type;
};
/*
* Determine if the given string is a valid mode expression.
* TODO: This can be improved. (e.g. ++ and +a++ shouldn't be valid)
* @param {string} mode E.g. +o, -o, +v, etc.
*/
UserCommand.prototype.isValidMode = function(mode) {
var _ref1;
return (_ref1 = mode != null ? mode[0] : void 0) === '+' || _ref1 === '-';
};
UserCommand.prototype.listInstalledScripts = function() {
var names;
names = this.chat.scriptHandler.getScriptNames();
if (names.length === 0) {
return "No scripts are currently installed";
} else {
return "Installed scripts: " + (getReadableList(names));
}
};
return UserCommand;
})();
exports.UserCommand = UserCommand;
}).call(this);
| wikijoss/circ | package/bin/chat/user_command.js | JavaScript | bsd-3-clause | 13,369 | [
30522,
1013,
1013,
7013,
2011,
4157,
22483,
1015,
1012,
1018,
1012,
1014,
1006,
3853,
1006,
1007,
1063,
1000,
2224,
9384,
1000,
1025,
13075,
5310,
9006,
2386,
2094,
1010,
14338,
1010,
1035,
25416,
1010,
1035,
1035,
14704,
1027,
1031,
1033,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Detail view of _utf_normal_util.inc.php</title>
<link rel="stylesheet" href="../../sample.css" type="text/css">
<link rel="stylesheet" href="../../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Sat Nov 21 22:13:19 2015 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../../';
subdir='plugins/wikitables_plugin';
filename='_utf_normal_util.inc.php.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h2 class="details-heading"><a href="./index.html">/plugins/wikitables_plugin/</a> -> <a href="_utf_normal_util.inc.php.source.html">_utf_normal_util.inc.php</a> (summary)</h2>
<div class="details-summary">
<p class="viewlinks">[<a href="_utf_normal_util.inc.php.source.html">Source view</a>]
[<a href="javascript:window.print();">Print</a>]
[<a href="../../_stats.html">Project Stats</a>]</p>
<p><b>Some of these functions are adapted from places in MediaWiki. Should probably merge them for consistency. Copyright © 2004 Brion Vibber <brion@pobox.com> http://www.mediawiki.org/</b></p>
<table>
<tr><td align="right">File Size: </td><td>140 lines (4 kb)</td></tr>
<tr><td align="right">Included or required:</td><td>0 times</td></tr>
<tr><td align="right" valign="top">Referenced: </td><td>0 times</td></tr>
<tr><td align="right" valign="top">Includes or requires: </td><td>0 files</td></tr>
</table>
<h3>Defines 5 functions</h3>
<div class="inset">
<a href="#codepointtoutf8">codepointToUtf8</a>()<br>
<a href="#hexsequencetoutf8">hexSequenceToUtf8</a>()<br>
<a href="#utf8tohexsequence">utf8ToHexSequence</a>()<br>
<a href="#utf8tocodepoint">utf8ToCodepoint</a>()<br>
<a href="#escapesinglestring">escapeSingleString</a>()<br>
</div>
</div>
<br><div class="details-funclist">
<div class="details-classtitle"><a name="functions"><b>Functions</b></a></div>
<div class="details-classinfo">
Functions that are not part of a class:<br><br>
<div class="inset"><table border="0" width="80%" class="funcinfo"><tr class="funcinfo-title"><td>
<a name="codepointtoutf8" onClick="logFunction('codepointtoutf8', '_utf_normal_util.inc.php.source.html#l28')" href="_utf_normal_util.inc.php.source.html#l28">codepointToUtf8</a>( <a href="../../_variables/codepoint.html">$codepoint</a> )
<a href="../../_functions/codepointtoutf8.html"><small>X-Ref</small></a>
</td></tr><tr class="funcinfo-body"><td><b>Return UTF-8 sequence for a given Unicode code point.<BR>
May die if fed out of range data.<BR>
</b><BR><b>param:</b> $codepoint Integer:<br>
<b>return:</b> String<br>
</td></tr></table>
<br>
<table border="0" width="80%" class="funcinfo"><tr class="funcinfo-title"><td>
<a name="hexsequencetoutf8" onClick="logFunction('hexsequencetoutf8', '_utf_normal_util.inc.php.source.html#l52')" href="_utf_normal_util.inc.php.source.html#l52">hexSequenceToUtf8</a>( <a href="../../_variables/sequence.html">$sequence</a> )
<a href="../../_functions/hexsequencetoutf8.html"><small>X-Ref</small></a>
</td></tr><tr class="funcinfo-body"><td><b>Take a series of space-separated hexadecimal numbers representing<BR>
Unicode code points and return a UTF-8 string composed of those<BR>
characters. Used by UTF-8 data generation and testing routines.<BR>
</b><BR><b>param:</b> $sequence String<br>
<b>return:</b> String<br>
</td></tr></table>
<br>
<table border="0" width="80%" class="funcinfo"><tr class="funcinfo-title"><td>
<a name="utf8tohexsequence" onClick="logFunction('utf8tohexsequence', '_utf_normal_util.inc.php.source.html#l70')" href="_utf_normal_util.inc.php.source.html#l70">utf8ToHexSequence</a>( <a href="../../_variables/str.html">$str</a> )
<a href="../../_functions/utf8tohexsequence.html"><small>X-Ref</small></a>
</td></tr><tr class="funcinfo-body"><td><b>Take a UTF-8 string and return a space-separated series of hex<BR>
numbers representing Unicode code points. For debugging.<BR>
</b><BR><b>param:</b> string $str UTF-8 string.<br>
<b>return:</b> string<br>
</td></tr></table>
<br>
<table border="0" width="80%" class="funcinfo"><tr class="funcinfo-title"><td>
<a name="utf8tocodepoint" onClick="logFunction('utf8tocodepoint', '_utf_normal_util.inc.php.source.html#l86')" href="_utf_normal_util.inc.php.source.html#l86">utf8ToCodepoint</a>( <a href="../../_variables/char.html">$char</a> )
<a href="../../_functions/utf8tocodepoint.html"><small>X-Ref</small></a>
</td></tr><tr class="funcinfo-body"><td><b>Determine the Unicode codepoint of a single-character UTF-8 sequence.<BR>
Does not check for invalid input data.<BR>
</b><BR><b>param:</b> $char String<br>
<b>return:</b> Integer<br>
</td></tr></table>
<br>
<table border="0" width="80%" class="funcinfo"><tr class="funcinfo-title"><td>
<a name="escapesinglestring" onClick="logFunction('escapesinglestring', '_utf_normal_util.inc.php.source.html#l127')" href="_utf_normal_util.inc.php.source.html#l127">escapeSingleString</a>( <a href="../../_variables/string.html">$string</a> )
<a href="../../_functions/escapesinglestring.html"><small>X-Ref</small></a>
</td></tr><tr class="funcinfo-body"><td><b>Escape a string for inclusion in a PHP single-quoted string literal.<BR>
</b><BR><b>param:</b> string $string string to be escaped.<br>
<b>return:</b> String: escaped string.<br>
</td></tr></table>
<br>
</div></div>
</div>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Sat Nov 21 22:13:19 2015</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
| mgsolipa/b2evolution_phpxref | plugins/wikitables_plugin/_utf_normal_util.inc.php.html | HTML | gpl-2.0 | 9,141 | [
30522,
1026,
999,
9986,
13874,
16129,
2270,
1000,
1011,
1013,
1013,
1059,
2509,
2278,
1013,
1013,
26718,
2094,
16129,
1018,
1012,
1014,
17459,
1013,
1013,
4372,
1000,
1000,
8299,
1024,
1013,
1013,
7479,
1012,
1059,
2509,
1012,
8917,
1013,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#
# Makefile for the Linux Bluetooth RFCOMM layer.
#
obj-$(CONFIG_BT_RFCOMM) += rfcomm.o
rfcomm-y := core.o sock.o crc.o
rfcomm-$(CONFIG_BT_RFCOMM_TTY) += tty.o
| foxsat-hdr/linux-kernel | net/bluetooth/rfcomm/Makefile | Makefile | gpl-2.0 | 165 | [
30522,
1001,
1001,
2191,
8873,
2571,
2005,
1996,
11603,
2630,
19392,
14645,
5358,
2213,
6741,
1012,
1001,
27885,
3501,
1011,
1002,
1006,
9530,
8873,
2290,
1035,
18411,
1035,
14645,
5358,
2213,
1007,
1009,
1027,
14645,
5358,
2213,
1012,
1051... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
Facepuncher
================================
[](http://travis-ci.org/bigfuel/facepuncher)
Welcome to a Punch in the Face! Facepuncher is a platform for quickly bootstrapping deploying Facebook tabs.
Requirements
------------
- Rails 3.2
- MongoDB 1.8+
- Redis 2.4+
- git
- ssh
Setup
-----
To setup Facepuncher:
git clone git@github.com:bigfuel/facepuncher.git
cd facepuncher
bundle
Configure app and databases:
Rename config files:
mv config/config.yml.example config/config.yml
mv config/mongoid.yml.example config/mongoid.yml
and optionally:
mv config/newrelic.yml.example config/newrelic.yml
Modify the configuration files to match your environment.
Setup the database:
rake db:setup
Start the applicaiton:
foreman start
Project repositories
--------------------
Facepuncher supports both `https` and `git` protocols for project repositories. The `https` protocol may require a username and password if it's a private repository, or if there's http authentication on top of the repo:
https://username:password@github.com/bigfuel/example_private_repo.git
At Big Fuel we have private repositories on Github and Bit Bucket. What we do is create a deploy specific read-only account and we reference that in repository urls.
If you must use the `git` protocol, then you must install an SSH key and a known_hosts file with the host fingerprint of the repository's host. Add these to `vendor/support/.ssh` and they will be copied to your production environment upon deployment.
Resque workers
--------------
This application also requires resque and resque-scheduler workers to be started. These workers process background jobs, such as deployng project releases.
You should run this in a separate terminal window. The VERBOSE=1 option tells it to provide more debugging information so you know what's going on.
VERBOSE=1 QUEUE=* rake resque:work
The scheduler worker schedules jobs that take place at later or at regular intervals.
VERBOSE=1 rake resque:scheduler
| bigfuel/facepuncher | README.md | Markdown | mpl-2.0 | 2,116 | [
30522,
2227,
14289,
26091,
2099,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1031,
999,
10... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package com.kkk.retrofitdemo;
import com.kkk.retrofitdemo.bean.Repo;
import com.kkk.retrofitdemo.bean.SearchRepoResult;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
import rx.Observable;
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
@GET("search/repositories")
Observable<SearchRepoResult> searchRepos(@Query("q") String keyword,
@Query("sort") String sort,
@Query("order") String order);
} | kylm53/learn-android | RetrofitDemo/src/main/java/com/kkk/retrofitdemo/GitHubService.java | Java | mit | 655 | [
30522,
7427,
4012,
1012,
1047,
19658,
1012,
22307,
8873,
2102,
3207,
5302,
1025,
12324,
4012,
1012,
1047,
19658,
1012,
22307,
8873,
2102,
3207,
5302,
1012,
14068,
1012,
16360,
2080,
1025,
12324,
4012,
1012,
1047,
19658,
1012,
22307,
8873,
2... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/***************************************************************************
* Copyright (C) 2011-2015 by Fabrizio Montesi <famontesi@gmail.com> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
***************************************************************************/
package jolie.runtime.typing;
import jolie.lang.Constants;
/**
*
* @author Fabrizio Montesi
*/
public class TypeCastingException extends Exception {
public final static long serialVersionUID = Constants.serialVersionUID();
public TypeCastingException() {
super();
}
public TypeCastingException( String message ) {
super( message );
}
/*
* @Override public Throwable fillInStackTrace() { return this; }
*/
}
| jolie/jolie | jolie/src/main/java/jolie/runtime/typing/TypeCastingException.java | Java | lgpl-2.1 | 1,972 | [
30522,
1013,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
100... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>RADIUS Options</title>
</head>
<body><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="radius.constants.html">Predefined Constants</a></div>
<div class="next" style="text-align: right; float: right;"><a href="radius.constants.packets.html">RADIUS Packet Types</a></div>
<div class="up"><a href="radius.constants.html">Predefined Constants</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div><hr /><div id="radius.constants.options" class="section">
<h2 class="title">RADIUS Options</h2>
<p class="para">
Several RADIUS functions accept option flags as bitmasks. The constants
representing those flags are listed below.
</p>
<dl>
<dt id="constant.radius-option-salt">
<strong><code>RADIUS_OPTION_SALT</code></strong>
(<span class="type"><a href="language.types.integer.html" class="type integer">integer</a></span>)
</dt>
<dd>
<p class="para">
When set, this option will result in the attribute value being
salt-encrypted.
</p>
</dd>
<dt id="constant.radius-option-tagged">
<strong><code>RADIUS_OPTION_TAGGED</code></strong>
(<span class="type"><a href="language.types.integer.html" class="type integer">integer</a></span>)
</dt>
<dd>
<p class="para">
When set, this option will result in the attribute value being tagged
with the value of the tag parameter.
</p>
</dd>
</dl>
</div><hr /><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="radius.constants.html">Predefined Constants</a></div>
<div class="next" style="text-align: right; float: right;"><a href="radius.constants.packets.html">RADIUS Packet Types</a></div>
<div class="up"><a href="radius.constants.html">Predefined Constants</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div></body></html>
| rafaelgou/the-phpjs-local-docs-collection | php/5.5/radius.constants.options.html | HTML | gpl-3.0 | 2,195 | [
30522,
1026,
999,
9986,
13874,
16129,
2270,
1000,
1011,
1013,
1013,
1059,
2509,
2278,
1013,
1013,
26718,
2094,
16129,
1018,
1012,
5890,
17459,
1013,
1013,
4372,
1000,
1000,
8299,
1024,
1013,
1013,
7479,
1012,
1059,
2509,
1012,
8917,
1013,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
local m = splay_map()
for i = 1, 100 do
m:insert(i, i * 3)
end
local prev_k = nil
-- It is safe to add/erase elements from m while we are traversing.
-- The for_each method will traverse the elements that are in m
-- when the for_each is invoked
m:for_each(
function(k, v)
if prev_k then
assert(prev_k < k)
end
print(k .. " -> " .. v)
prev_k = k
m:insert(-k, v)
end
)
assert(m:size() == 200)
m2 = m:copy()
m:for_each(
function(k, v)
assert(m2:contains(-k))
assert(m2:find(-k) == v)
if k > 0 then
m:erase(k)
end
end
)
assert(m:size() == 100)
m:for_each(function(k, v) assert(k < 0) end)
| codyroux/lean0.1 | tests/lua/map2.lua | Lua | apache-2.0 | 675 | [
30522,
2334,
1049,
1027,
11867,
8485,
1035,
4949,
1006,
1007,
2005,
1045,
1027,
1015,
1010,
2531,
2079,
1049,
1024,
19274,
1006,
1045,
1010,
1045,
1008,
1017,
1007,
2203,
2334,
3653,
2615,
1035,
1047,
1027,
9152,
2140,
1011,
1011,
2009,
2... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
/**
* Link Helper class: com_form2content.form
*
* @package Better Preview
* @version 4.1.2PRO
*
* @author Peter van Westen <peter@nonumber.nl>
* @link http://www.nonumber.nl
* @copyright Copyright © 2015 NoNumber All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
defined('_JEXEC') or die;
include_once __DIR__ . '/helper.php';
class HelperBetterPreviewLinkForm2ContentForm extends HelperBetterPreviewLink
{
function getLinks()
{
$helper = new HelperBetterPreviewHelperForm2ContentForm($this->params);
if (!$item = $helper->getArticle())
{
return;
}
$parents = $helper->getArticleParents($item);
return array_merge(array($item), $parents);
}
}
| quanghung0404/it2tech | plugins/system/betterpreview/helpers/com_form2content/form/link.php | PHP | gpl-2.0 | 768 | [
30522,
1026,
1029,
25718,
1013,
1008,
1008,
1008,
4957,
2393,
2121,
2465,
1024,
4012,
1035,
2433,
2475,
8663,
6528,
2102,
1012,
2433,
1008,
1008,
1030,
7427,
2488,
19236,
1008,
1030,
2544,
1018,
1012,
1015,
1012,
1016,
21572,
1008,
1008,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// Accord Audio Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2014
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Audio
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Timers;
/// <summary>
/// Virtual Metronome.
/// </summary>
///
/// <remarks>
/// Objects from this class acts as virtual metronomes. If connected
/// to a beat detector, it can be used to determine the tempo (in
/// beats per minute) of a signal. It can also be used in manual mode
/// by calling <see cref="Tap"/> method. For more details, see the
/// Beat detection sample application which comes together with the
/// framework.
/// </remarks>
///
public class Metronome : IDisposable
{
private int taps;
private List<TimeSpan> timeSpan;
private DateTime lastTick;
private Timer timeUp;
private Timer metronome;
/// <summary>
/// Gets or sets the Beats per Minute for this metronome.
/// </summary>
///
public int BeatsPerMinute
{
get { return (int)((1000.0 * 60.0) / metronome.Interval); }
set { metronome.Interval = (60.0 * 1000.0) / value; }
}
/// <summary>
/// Gets whether the metronome is currently detecting the tempo being tapped.
/// </summary>
///
public bool Detecting
{
get { return timeUp.Enabled; }
}
/// <summary>
/// Fired when the metronome has figured the tapped tempo.
/// </summary>
///
public event EventHandler TempoDetected;
/// <summary>
/// Metronome tick.
/// </summary>
///
public event ElapsedEventHandler Tick
{
add { metronome.Elapsed += value; }
remove { metronome.Elapsed -= value; }
}
/// <summary>
/// Synchronizing object for thread safety.
/// </summary>
///
public ISynchronizeInvoke SynchronizingObject
{
get { return timeUp.SynchronizingObject; }
set
{
timeUp.SynchronizingObject = value;
metronome.SynchronizingObject = value;
}
}
/// <summary>
/// Constructs a new Metronome.
/// </summary>
///
public Metronome()
{
timeUp = new Timer();
metronome = new Timer();
timeSpan = new List<TimeSpan>();
// set interval as 2 seconds
timeUp.Interval = 2000;
timeUp.Elapsed += timeUp_Elapsed;
}
/// <summary>
/// Taps the metronome (for tempo detection)
/// </summary>
///
public void Tap()
{
metronome.Stop();
DateTime now = DateTime.Now;
if (Detecting)
{
timeUp.Stop();
TimeSpan span = now - lastTick;
timeSpan.Add(span);
}
lastTick = now;
timeUp.Start();
}
/// <summary>
/// Starts the metronome.
/// </summary>
///
public void Start()
{
metronome.Start();
}
/// <summary>
/// Stops the metronome.
/// </summary>
///
public void Stop()
{
metronome.Stop();
}
/// <summary>
/// Performs application-defined tasks associated with
/// freeing, releasing, or resetting unmanaged resources.
/// </summary>
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
///
/// <param name="disposing"><c>true</c> to release both managed
/// and unmanaged resources; <c>false</c> to release only unmanaged
/// resources.</param>
///
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources
if (timeUp != null)
{
timeUp.Dispose();
timeUp = null;
}
if (metronome != null)
{
metronome.Dispose();
metronome = null;
}
}
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the
/// <see cref="Metronome"/> is reclaimed by garbage collection.
/// </summary>
///
~Metronome()
{
Dispose(false);
}
private void timeUp_Elapsed(object sender, ElapsedEventArgs e)
{
timeUp.Stop();
this.taps = timeSpan.Count;
if (taps <= 1)
{
timeSpan.Clear();
return;
}
double mean = 0;
for (int i = 0; i < taps; i++)
mean += timeSpan[0].Milliseconds;
mean = mean / taps;
timeSpan.Clear();
this.metronome.Interval = mean;
if (TempoDetected != null)
TempoDetected(this, EventArgs.Empty);
}
}
}
| DiegoCatalano/framework | Sources/Accord.Audio/Metronome.cs | C# | lgpl-2.1 | 6,374 | [
30522,
1013,
1013,
15802,
5746,
3075,
1013,
1013,
1996,
15802,
1012,
5658,
7705,
1013,
1013,
8299,
1024,
1013,
1013,
15802,
1011,
7705,
1012,
5658,
1013,
1013,
1013,
1013,
9385,
1075,
14923,
26598,
1010,
2268,
1011,
2297,
1013,
1013,
14923,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
//http://www.nayuki.io/page/fast-fibonacci-algorithms
//cc -o fibonacci2 fibonacci2.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define TAM 40
int main(){
int fib[TAM];
fib[0]=0;
fib[1]=1;
int i;
clock_t t;
t = clock();
for(i = 2; i < TAM; i++)
fib[i] = fib[i-1] + fib[i-2];
printf ("%f time \n",t,((float)t)/CLOCKS_PER_SEC);
printf("%d\n",fib[TAM-1]);
return 0;
}
| h31nr1ch/CAL | fibonacci/fibonacci2.c | C | gpl-2.0 | 428 | [
30522,
1013,
1013,
8299,
1024,
1013,
1013,
7479,
1012,
29349,
14228,
1012,
22834,
1013,
3931,
1013,
3435,
1011,
10882,
11735,
6305,
6895,
1011,
13792,
1013,
1013,
10507,
1011,
1051,
10882,
11735,
6305,
6895,
2475,
10882,
11735,
6305,
6895,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE html>
<html lang="en-us">
<head>
<link href="http://gmpg.org/xfn/11" rel="profile">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<!-- Enable responsiveness on mobile devices-->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
<title>
404: Page not found · Web Grower
</title>
<!-- CSS -->
<link rel="stylesheet" href="/public/css/poole.css">
<link rel="stylesheet" href="/public/css/syntax.css">
<link rel="stylesheet" href="/public/css/lanyon.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Serif:400,400italic,700%7CPT+Sans:400">
<!-- Icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-precomposed.png">
<link rel="shortcut icon" href="/public/favicon.ico">
<!-- RSS -->
<link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">
</head>
<body>
<!-- Target for toggling the sidebar `.sidebar-checkbox` is for regular
styles, `#sidebar-checkbox` for behavior. -->
<input type="checkbox" class="sidebar-checkbox" id="sidebar-checkbox">
<!-- Toggleable sidebar -->
<div class="sidebar" id="sidebar">
<div class="sidebar-item">
<p>Очередной коллективный блог про веб-разработку, созданный, когда это еще не было мэйнстримом.</p>
</div>
<nav class="sidebar-nav">
<a class="sidebar-nav-item" href="/">Home</a>
<a class="sidebar-nav-item" href="/about/">About</a>
<span class="sidebar-nav-item">Currently v1.0.0</span>
</nav>
<div class="sidebar-item">
<p>
© 2016. All rights reserved.
</p>
</div>
</div>
<!-- Wrap is the content to shift when toggling the sidebar. We wrap the
content to avoid any CSS collisions with our real content. -->
<div class="wrap">
<div class="masthead">
<div class="container">
<h3 class="masthead-title">
<a href="/" title="Home">Web Grower</a>
<small>Очередной коллективный блог про веб-разработку</small>
</h3>
</div>
</div>
<div class="container content">
<div class="page">
<h1 class="page-title">404: Page not found</h1>
<p class="lead">Sorry, we've misplaced that URL or it's pointing to something that doesn't exist. <a href="/">Head back home</a> to try finding it again.</p>
</div>
</div>
</div>
<label for="sidebar-checkbox" class="sidebar-toggle"></label>
<script>
(function(document) {
var toggle = document.querySelector('.sidebar-toggle');
var sidebar = document.querySelector('#sidebar');
var checkbox = document.querySelector('#sidebar-checkbox');
document.addEventListener('click', function(e) {
var target = e.target;
if(!checkbox.checked ||
sidebar.contains(target) ||
(target === checkbox || target === toggle)) return;
checkbox.checked = false;
}, false);
})(document);
</script>
</body>
</html>
| webgrower/webgrower.github.io | _site/404.html | HTML | mit | 3,390 | [
30522,
1026,
999,
9986,
13874,
16129,
1028,
1026,
16129,
11374,
1027,
1000,
4372,
1011,
2149,
1000,
1028,
1026,
2132,
1028,
1026,
4957,
17850,
12879,
1027,
1000,
8299,
1024,
1013,
1013,
13938,
26952,
1012,
8917,
1013,
1060,
2546,
2078,
1013... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
'use strict';
export default function routes($routeProvider) {
'ngInject';
$routeProvider.when('/new_component', {
template: '<about></about>'
});
$routeProvider.when('/new_component/:somethingToPrint', {
template: '<about></about>'
});
}
| whoppa/COMP-3705 | client/app/Component/new_component.routes.js | JavaScript | mit | 259 | [
30522,
1005,
2224,
9384,
1005,
1025,
9167,
12398,
3853,
5847,
1006,
1002,
2799,
21572,
17258,
2121,
1007,
1063,
1005,
12835,
2378,
20614,
1005,
1025,
1002,
2799,
21572,
17258,
2121,
1012,
2043,
1006,
1005,
1013,
2047,
1035,
6922,
1005,
1010... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# Discourse Migration Guide
## Install new server
Complete a fresh install of Discourse on the new server, following the official guide, except for the initial database population (rake db:migrate).
## Review old server
On old server, run `git status` and review changes to the tree. For example:
# On branch master
# Changes not staged for commit:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: app/assets/javascripts/external/Markdown.Editor.js
# modified: app/views/layouts/application.html.erb
# modified: config/application.rb
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# app/views/layouts/application.html.erb.bitnami
# config/environments/production.rb
# log/sidekiq.pid
# vendor/gems/active_model_serializers/
# vendor/gems/fast_blank/
# vendor/gems/message_bus/
# vendor/gems/redis-rack-cache/
# vendor/gems/sprockets/
# vendor/gems/vestal_versions/
### Review for changes
Review each of the changed files for changes that need to be manually moved over
* Ignore all files under vendor/gems
* Ignore files under log/
Check your config/environments/production.rb, config/discourse.pill,
config/database.yml (as per the upgrade instructions)
## Move DB
Take DB dump with:
pg_dump --no-owner -U user_name -W database_name > backup_file_name.sql
Copy it over to the new server
Run as discourse user:
```
createdb discourse_prod
psql discourse_prod
\i backup_file_name.sql
```
On oldserver:
`rsync -avz -e ssh public newserver:public`
On the new server:
```
bundle install --without test --deployment
RUBY_GC_MALLOC_LIMIT=90000000 RAILS_ENV=production rake db:migrate
RUBY_GC_MALLOC_LIMIT=90000000 RAILS_ENV=production rake assets:precompile
RUBY_GC_MALLOC_LIMIT=90000000 RAILS_ENV=production rake posts:rebake
```
If the `rake db:migrate` step fails, you might have to run it twice.
Are you just testing your migration? Disable outgoing email by changing
`config/environments/production.rb` and adding the following below the mail
configuration:
config.action_mailer.perform_deliveries = false
| chrishunt/discourse | docs/MIGRATION.md | Markdown | gpl-2.0 | 2,290 | [
30522,
1001,
15152,
9230,
5009,
1001,
1001,
16500,
2047,
8241,
3143,
1037,
4840,
16500,
1997,
15152,
2006,
1996,
2047,
8241,
1010,
2206,
1996,
2880,
5009,
1010,
3272,
2005,
1996,
3988,
7809,
2313,
1006,
26008,
16962,
1024,
22806,
1007,
1012... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
---
layout: page
title: Barr Bear Media Conference
date: 2016-05-24
author: Jeffrey Hicks
tags: weekly links, java
status: published
summary: Praesent ultrices orci eu quam suscipit dignissim. Phasellus tempus malesuada.
banner: images/banner/office-01.jpg
booking:
startDate: 07/26/2018
endDate: 07/28/2018
ctyhocn: MOBJCHX
groupCode: BBMC
published: true
---
Curabitur volutpat consectetur enim a semper. Sed quis neque consectetur, maximus ex at, tincidunt augue. Maecenas ut tortor nec diam feugiat varius. Maecenas vel pretium elit. Vestibulum molestie elit ut ante porttitor, eget accumsan purus dictum. Quisque dapibus porttitor arcu, sed blandit lectus consequat id. Nullam commodo ante vel sollicitudin lacinia. Sed hendrerit sem ut nisl fringilla maximus. Integer fermentum facilisis lacinia. Vivamus tincidunt ligula ut euismod gravida. Morbi aliquet, nisl eu vestibulum ultrices, est diam accumsan ex, ut interdum libero lectus eu orci. Pellentesque id blandit sem, ac laoreet justo. Curabitur at ornare metus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer sed velit sit amet odio venenatis mollis.
Nulla nec vehicula lacus, sit amet vehicula odio. Aenean blandit bibendum arcu, et tincidunt turpis suscipit sit amet. Vivamus odio dolor, suscipit sed cursus vel, porta et quam. Nam massa mi, tincidunt quis pulvinar sit amet, interdum nec nisl. Donec semper ut ipsum maximus egestas. Aliquam viverra justo nisi, in consequat nulla varius vel. Proin at quam vel felis aliquet placerat quis vel lacus. Pellentesque elementum dui purus, vel accumsan quam lacinia tristique. Vestibulum elementum scelerisque dui in scelerisque. Mauris non odio non velit suscipit euismod. Donec molestie mauris eu ornare pretium.
* Sed nec velit rhoncus, euismod diam sit amet, aliquam elit
* Ut sit amet lacus ac justo tristique fermentum sit amet vel ligula.
Morbi consectetur nunc sed semper vulputate. Nulla id laoreet lacus, sed sagittis libero. Maecenas pellentesque pellentesque urna vel mollis. Ut venenatis massa eu tincidunt placerat. Vivamus fermentum blandit mi, eu posuere nunc dictum at. Mauris ut neque ut felis bibendum vehicula dapibus in quam. Duis turpis sapien, semper et est id, convallis gravida arcu.
| KlishGroup/prose-pogs | pogs/M/MOBJCHX/BBMC/index.md | Markdown | mit | 2,336 | [
30522,
1011,
1011,
1011,
9621,
1024,
3931,
2516,
1024,
19820,
4562,
2865,
3034,
3058,
1024,
2355,
1011,
5709,
1011,
2484,
3166,
1024,
10799,
17221,
22073,
1024,
4882,
6971,
1010,
9262,
3570,
1024,
2405,
12654,
1024,
10975,
6679,
5054,
2102,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
.ant-modal {
position: relative;
width: auto;
margin: 0 auto;
top: 100px;
padding-bottom: 24px;
}
.ant-modal-wrap {
position: fixed;
overflow: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1000;
-webkit-overflow-scrolling: touch;
outline: 0;
}
.ant-modal-title {
margin: 0;
font-size: 14px;
line-height: 21px;
font-weight: 500;
color: rgba(0, 0, 0, 0.85);
}
.ant-modal-content {
position: relative;
background-color: #fff;
border: 0;
border-radius: 4px;
background-clip: padding-box;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
.ant-modal-close {
cursor: pointer;
border: 0;
background: transparent;
position: absolute;
right: 0;
top: 0;
z-index: 10;
font-weight: 700;
line-height: 1;
text-decoration: none;
transition: color .3s ease;
color: rgba(0, 0, 0, 0.43);
outline: 0;
}
.ant-modal-close-x {
display: block;
font-style: normal;
vertical-align: baseline;
text-align: center;
text-transform: none;
text-rendering: auto;
width: 48px;
height: 48px;
line-height: 48px;
font-size: 14px;
}
.ant-modal-close-x:before {
content: "\e633";
display: block;
font-family: "anticon" !important;
}
.ant-modal-close:focus,
.ant-modal-close:hover {
color: #444;
text-decoration: none;
}
.ant-modal-header {
padding: 13px 16px;
border-radius: 4px 4px 0 0;
background: #fff;
color: rgba(0, 0, 0, 0.65);
border-bottom: 1px solid #e9e9e9;
}
.ant-modal-body {
padding: 16px;
font-size: 12px;
line-height: 1.5;
}
.ant-modal-footer {
border-top: 1px solid #e9e9e9;
padding: 10px 16px 10px 10px;
text-align: right;
border-radius: 0 0 4px 4px;
}
.ant-modal-footer button + button {
margin-left: 8px;
margin-bottom: 0;
}
.ant-modal.zoom-enter,
.ant-modal.zoom-appear {
-webkit-animation-duration: 0.3s;
animation-duration: 0.3s;
-webkit-transform: none;
-ms-transform: none;
transform: none;
opacity: 0;
}
.ant-modal-mask {
position: fixed;
top: 0;
right: 0;
left: 0;
bottom: 0;
background-color: #373737;
background-color: rgba(55, 55, 55, 0.6);
height: 100%;
z-index: 1000;
filter: alpha(opacity=50);
}
.ant-modal-mask-hidden {
display: none;
}
.ant-modal-open {
overflow: hidden;
}
@media (max-width: 768px) {
.ant-modal {
width: auto !important;
margin: 10px;
}
.vertical-center-modal .ant-modal {
-webkit-box-flex: 1;
-ms-flex: 1;
flex: 1;
}
}
.ant-confirm .ant-modal-header {
display: none;
}
.ant-confirm .ant-modal-close {
display: none;
}
.ant-confirm .ant-modal-body {
padding: 30px 40px;
}
.ant-confirm-body-wrapper {
zoom: 1;
}
.ant-confirm-body-wrapper:before,
.ant-confirm-body-wrapper:after {
content: " ";
display: table;
}
.ant-confirm-body-wrapper:after {
clear: both;
visibility: hidden;
font-size: 0;
height: 0;
}
.ant-confirm-body .ant-confirm-title {
color: rgba(0, 0, 0, 0.65);
font-weight: bold;
font-size: 14px;
}
.ant-confirm-body .ant-confirm-content {
margin-left: 42px;
font-size: 12px;
color: rgba(0, 0, 0, 0.65);
margin-top: 8px;
}
.ant-confirm-body > .anticon {
font-size: 24px;
margin-right: 16px;
padding: 0 1px;
float: left;
}
.ant-confirm .ant-confirm-btns {
margin-top: 30px;
float: right;
}
.ant-confirm .ant-confirm-btns button + button {
margin-left: 10px;
margin-bottom: 0;
}
.ant-confirm-error .ant-confirm-body > .anticon {
color: #f04134;
}
.ant-confirm-warning .ant-confirm-body > .anticon,
.ant-confirm-confirm .ant-confirm-body > .anticon {
color: #ffbf00;
}
.ant-confirm-info .ant-confirm-body > .anticon {
color: #108ee9;
}
.ant-confirm-success .ant-confirm-body > .anticon {
color: #00a854;
}
| prodigalyijun/demo-by-antd | node_modules/antd/lib/modal/style/index.css | CSS | mit | 3,717 | [
30522,
1012,
14405,
1011,
16913,
2389,
1063,
2597,
1024,
5816,
1025,
9381,
1024,
8285,
1025,
7785,
1024,
1014,
8285,
1025,
2327,
1024,
2531,
2361,
2595,
1025,
11687,
4667,
1011,
3953,
1024,
2484,
2361,
2595,
1025,
1065,
1012,
14405,
1011,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.deeplearning4j.text.documentiterator;
import lombok.NonNull;
import org.deeplearning4j.text.documentiterator.interoperability.DocumentIteratorConverter;
import org.deeplearning4j.text.sentenceiterator.SentenceIterator;
import org.deeplearning4j.text.sentenceiterator.interoperability.SentenceIteratorConverter;
import org.deeplearning4j.text.sentenceiterator.labelaware.LabelAwareSentenceIterator;
import java.util.concurrent.atomic.AtomicLong;
/**
* This is simple class, for building Sentence-Label pairs for ParagraphVectors/Doc2Vec.
* Idea is simple - you provide SentenceIterator or DocumentIterator, and it builds nice structure for future model reuse
*
* @author raver119@gmail.com
*/
public class BasicLabelAwareIterator implements LabelAwareIterator {
// this counter is used for dumb labels generation
protected AtomicLong documentPosition = new AtomicLong(0);
protected LabelsSource generator;
protected transient LabelAwareIterator backendIterator;
private BasicLabelAwareIterator() {
}
/**
* This method checks, if there's more LabelledDocuments
* @return
*/
public boolean hasNextDocument() {
return backendIterator.hasNextDocument();
}
/**
* This method returns next LabelledDocument
* @return
*/
public LabelledDocument nextDocument() {
return backendIterator.nextDocument();
}
/**
* This methods resets LabelAwareIterator
*/
public void reset() {
backendIterator.reset();
}
/**
* This method returns LabelsSource instance, containing all labels derived from this iterator
* @return
*/
@Override
public LabelsSource getLabelsSource() {
return generator;
}
@Override
public boolean hasNext() {
return hasNextDocument();
}
@Override
public LabelledDocument next() {
return nextDocument();
}
@Override
public void shutdown() {
// no-op
}
@Override
public void remove() {
// no-op
}
public static class Builder {
private String labelTemplate = "DOC_";
private LabelAwareIterator labelAwareIterator;
private LabelsSource generator = new LabelsSource(labelTemplate);
/**
* This method should stay protected, since it's only viable for testing purposes
*/
protected Builder() {
}
/**
* We assume that each sentence in this iterator is separate document/paragraph
*
* @param iterator
*/
public Builder(@NonNull SentenceIterator iterator) {
this.labelAwareIterator = new SentenceIteratorConverter(iterator, generator);
}
/**
* We assume that each inputStream in this iterator is separate document/paragraph
* @param iterator
*/
public Builder(@NonNull DocumentIterator iterator) {
this.labelAwareIterator = new DocumentIteratorConverter(iterator, generator);
}
/**
* We assume that each sentence in this iterator is separate document/paragraph.
* Labels will be converted into LabelledDocument format
*
* @param iterator
*/
public Builder(@NonNull LabelAwareSentenceIterator iterator) {
this.labelAwareIterator = new SentenceIteratorConverter(iterator, generator);
}
/**
* We assume that each inputStream in this iterator is separate document/paragraph
* Labels will be converted into LabelledDocument format
*
* @param iterator
*/
public Builder(@NonNull LabelAwareDocumentIterator iterator) {
this.labelAwareIterator = new DocumentIteratorConverter(iterator, generator);
}
public Builder(@NonNull LabelAwareIterator iterator) {
this.labelAwareIterator = iterator;
this.generator = iterator.getLabelsSource();
}
/**
* Label template will be used for sentence labels generation. I.e. if provided template is "DOCUMENT_", all documents/paragraphs will have their labels starting from "DOCUMENT_0" to "DOCUMENT_X", where X is the total number of documents - 1
*
* @param template
* @return
*/
public Builder setLabelTemplate(@NonNull String template) {
this.labelTemplate = template;
this.generator.setTemplate(template);
return this;
}
/**
* TODO: To be implemented
*
* @param source
* @return
*/
public Builder setLabelsSource(@NonNull LabelsSource source) {
this.generator = source;
return this;
}
public BasicLabelAwareIterator build() {
BasicLabelAwareIterator iterator = new BasicLabelAwareIterator();
iterator.generator = this.generator;
iterator.backendIterator = this.labelAwareIterator;
return iterator;
}
}
}
| deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/text/documentiterator/BasicLabelAwareIterator.java | Java | apache-2.0 | 5,848 | [
30522,
1013,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
100... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_26) on Sun Dec 30 01:26:12 PST 2012 -->
<TITLE>
Uses of Class org.apache.hadoop.io.InputBuffer (Hadoop 1.0.4-SNAPSHOT API)
</TITLE>
<META NAME="date" CONTENT="2012-12-30">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.io.InputBuffer (Hadoop 1.0.4-SNAPSHOT API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/io/InputBuffer.html" title="class in org.apache.hadoop.io"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/io//class-useInputBuffer.html" target="_top"><B>FRAMES</B></A>
<A HREF="InputBuffer.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.hadoop.io.InputBuffer</B></H2>
</CENTER>
No usage of org.apache.hadoop.io.InputBuffer
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/io/InputBuffer.html" title="class in org.apache.hadoop.io"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/io//class-useInputBuffer.html" target="_top"><B>FRAMES</B></A>
<A HREF="InputBuffer.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2009 The Apache Software Foundation
</BODY>
</HTML>
| davidl1/hortonworks-extension | build/docs/api/org/apache/hadoop/io/class-use/InputBuffer.html | HTML | apache-2.0 | 5,952 | [
30522,
1026,
999,
9986,
13874,
16129,
2270,
1000,
1011,
1013,
1013,
1059,
2509,
2278,
1013,
1013,
26718,
2094,
16129,
1018,
1012,
5890,
17459,
1013,
1013,
4372,
1000,
1000,
8299,
1024,
1013,
1013,
7479,
1012,
1059,
2509,
1012,
8917,
1013,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Modified for use with MPlayer, detailed changelog at
* http://svn.mplayerhq.hu/mplayer/trunk/
*/
#ifndef MPLAYER_EXT_H
#define MPLAYER_EXT_H
#include "wine/windef.h"
LPVOID FILE_dommap( int unix_handle, LPVOID start,
DWORD size_high, DWORD size_low,
DWORD offset_high, DWORD offset_low,
int prot, int flags );
int FILE_munmap( LPVOID start, DWORD size_high, DWORD size_low );
int wcsnicmp( const unsigned short* s1, const unsigned short* s2, int n );
int __vprintf( const char *format, ... );
#endif /* MPLAYER_EXT_H */
| DMCsys/smartalkaudio | oss-survey/mplayer-checkout-2011-04-26/loader/ext.h | C | gpl-3.0 | 592 | [
30522,
1013,
1008,
1008,
6310,
2005,
2224,
2007,
6131,
24314,
1010,
6851,
2689,
21197,
2012,
1008,
8299,
1024,
1013,
1013,
17917,
2078,
1012,
6131,
24314,
2232,
4160,
1012,
15876,
1013,
6131,
24314,
1013,
8260,
1013,
1008,
1013,
1001,
2065,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import {Http, Headers} from '@angular/http';
import {Router } from '@angular/router';
import 'rxjs/add/operator/map';
@Injectable()
export class AuthService {
submission: FirebaseListObservable<any>;
constructor(public afAuth: AngularFireAuth, private db: AngularFireDatabase, private router: Router){
console.log("Authentication service started");
console.log(firebase.auth());
}
login(email, pass){
this.afAuth.auth.signInWithEmailAndPassword(email, pass)
.then(res => {
console.log('Nice, logging you in!!!');
this.router.navigate(['/admin']);
});
}
checkAuth(){
this.afAuth.authState.subscribe(res => {
if (res && res.uid) {
console.log('user is logged in');
return true;
} else {
console.log('user not logged in...redirecting to welcome..');
this.router.navigate(['/login']);
return false;
}
});
}
logout() {
this.afAuth.auth.signOut();
this.router.navigate(['/']);
}
}
| alimcharaniya/uniformlab-v3 | src/services/auth.service.ts | TypeScript | mit | 1,321 | [
30522,
12324,
1063,
1999,
20614,
3085,
1065,
2013,
1005,
1030,
16108,
1013,
4563,
1005,
1025,
12324,
1063,
3395,
1065,
2013,
1005,
1054,
2595,
22578,
1013,
3395,
1005,
1025,
12324,
1063,
27885,
8043,
12423,
1065,
2013,
1005,
1054,
2595,
225... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
import { moduleFor, test } from 'ember-qunit';
moduleFor('adapter:contacts', 'Unit | Adapter | contacts', {
// Specify the other units that are required for this test.
// needs: ['serializer:foo']
});
// Replace this with your real tests.
test('it exists', function(assert) {
let adapter = this.subject();
assert.ok(adapter);
});
| jtolbert1975/imanjesolutions | tests/unit/adapters/contacts-test.js | JavaScript | gpl-3.0 | 340 | [
30522,
12324,
1063,
11336,
29278,
1010,
3231,
1065,
2013,
1005,
7861,
5677,
1011,
24209,
3490,
2102,
1005,
1025,
11336,
29278,
1006,
1005,
15581,
2121,
1024,
10402,
1005,
1010,
1005,
3131,
1064,
15581,
2121,
1064,
10402,
1005,
1010,
1063,
1... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
var YDom = YAHOO.util.Dom;
var YEvent = YAHOO.util.Event;
var subChildren = null;
var configTimeZone = null;
if (typeof WcmDashboardWidgetCommon == "undefined" || !WcmDashboardWidgetCommon) {
var WcmDashboardWidgetCommon = {};
}
WcmDashboardWidgetCommon.dashboards = new Array();
WcmDashboardWidgetCommon.sortClick = function (event, matchedEl, el, params) {
//var eventId='sorteventDate-component-1-1';
var eventId = matchedEl.id;
var sortBy = eventId.substring(4, eventId.indexOf('-'));
var Widget = WcmDashboardWidgetCommon.dashboards[params.widgetId];
WcmDashboardWidgetCommon.loadTableData(sortBy, YDom.get(params.widgetId), params.widgetId, null, true);
};
WcmDashboardWidgetCommon.encodePathToNumbers = function (path) {
var re1 = new RegExp('/', 'g');
var res = path.replace(re1, '00'); // substitute all forward slash with '00'
res = res.replace(/\./g, '010'); // substitute all periods with '010'
return res;
};
WcmDashboardWidgetCommon.insertEditLink = function (item, editLinkId) {
if (item.uri.indexOf(".ftl") == -1
&& item.uri.indexOf(".css") == -1
&& item.uri.indexOf(".js") == -1
&& item.uri.indexOf(".groovy") == -1
&& item.uri.indexOf(".txt") == -1
&& item.uri.indexOf(".html") == -1
&& item.uri.indexOf(".hbs") == -1
&& item.uri.indexOf(".xml") == -1) {
return 0; // dont render if not these types
}
CStudioAuthoring.Service.getUserPermissions(CStudioAuthoringContext.site, item.uri, {
success: function (results) {
function addEditLink() {
var editLink = document.getElementById(editLinkId);
if (editLink) {
editLink.innerHTML = ''.concat('<a href="javascript:" class="editLink', ((item.deleted || item.inFlight ) ? ' non-previewable-edit' : ''), '">' + CMgs.format(langBundle, "dashboardEdit") + '</a>');
} else {
// We cannot assume the DOM will be ready to insert the edit link
// that's why we'll poll until the element is available in the DOM
setTimeout(addEditLink, 200);
}
}
var isUserAllowed = CStudioAuthoring.Service.isUserAllowed(results.permissions);
if (isUserAllowed) {
// If the user's role is allowed to edit the content then add an edit link
addEditLink();
}
},
failure: function () {
throw new Error('Unable to retrieve user permissions');
}
});
};
WcmDashboardWidgetCommon.insertViewLink = function (item, viewLinkId) {
if (item.uri.indexOf(".ftl") == -1
&& item.uri.indexOf(".css") == -1
&& item.uri.indexOf(".js") == -1
&& item.uri.indexOf(".groovy") == -1
&& item.uri.indexOf(".txt") == -1
&& item.uri.indexOf(".html") == -1
&& item.uri.indexOf(".hbs") == -1
&& item.uri.indexOf(".xml") == -1) {
return 0; // dont render if not these types
}
CStudioAuthoring.Service.getUserPermissions(CStudioAuthoringContext.site, item.uri, {
success: function (results) {
function addViewLink() {
var viewLink = document.getElementById(viewLinkId);
if (viewLink) {
viewLink.innerHTML = ''.concat('<a href="javascript:" class="viewLink', ((item.deleted || item.inFlight ) ? ' non-previewable-edit' : ''), '">View</a>');
} else {
// We cannot assume the DOM will be ready to insert the edit link
// that's why we'll poll until the element is available in the DOM
setTimeout(addViewLink, 200);
}
}
var isUserAllowed = CStudioAuthoring.Service.isUserAllowed(results.permissions);
if (isUserAllowed) {
// If the user's role is allowed to edit the content then add an edit link
addViewLink();
}
},
failure: function () {
throw new Error('Unable to retrieve user permissions');
}
});
};
WcmDashboardWidgetCommon.convertDate = function (dateString) {
if (!dateString) return 0;
//our eventDate are passing in the format "YYYY-MM-DDTHH:MM:SS;"
var dateObj = null;
var dateArray = dateString.split("T");
if (dateArray && dateArray.length == 2) {
var dtArray = dateArray[0].split("-");
var tmArray = dateArray[1].split(":");
if (dtArray && dtArray.length == 3 &&
tmArray && tmArray.length >= 3) {
dateObj = new Date(parseInt(dtArray[0], 10),
parseInt(dtArray[1], 10),
parseInt(dtArray[2], 10),
parseInt(tmArray[0], 10),
parseInt(tmArray[1], 10),
parseInt(tmArray[2], 10));
}
}
if (dateObj) return dateObj;
return 0;
};
WcmDashboardWidgetCommon.sortItems = function (items, currentSortBy, currentSortType) {
try {
items.sort(function (firstItem, secondItem) {
if (currentSortBy == "userLastName") {
var firstItemVal = firstItem[currentSortBy];
var secondItemVal = secondItem[currentSortBy];
if (!firstItemVal) {
firstItemVal = firstItem["userFirstName"];
}
if (!secondItemVal) {
secondItemVal = secondItem["userFirstName"];
}
if (firstItemVal && secondItemVal) {
firstItemVal = firstItemVal.toLowerCase()
secondItemVal = secondItemVal.toLowerCase()
if (firstItemVal && secondItemVal) {
if (currentSortType == "true") {
return (firstItemVal == secondItemVal) ? 0 : (firstItemVal < secondItemVal) ? -1 : 1;
} else {
return (firstItemVal == secondItemVal) ? 0 : (secondItemVal < firstItemVal) ? -1 : 1;
}
}
}
} else if (firstItem[currentSortBy]) {
if (currentSortBy == "eventDate") {
var firstDate = WcmDashboardWidgetCommon.convertDate(firstItem[currentSortBy]);
var secondDate = WcmDashboardWidgetCommon.convertDate(secondItem[currentSortBy]);
if (currentSortType == "true") {
return (firstDate == secondDate) ? 0 : (firstDate < secondDate) ? -1 : 1;
} else {
return (firstDate == secondDate) ? 0 : (secondDate < firstDate) ? -1 : 1;
}
} else if (!isNaN(firstItem[currentSortBy]) && !isNaN(secondItem[currentSortBy])) {
var firstValue = parseInt(firstItem[currentSortBy], 10);
var secondValue = parseInt(secondItem[currentSortBy], 10);
if (currentSortType == "true") {
return (firstValue == secondValue) ? 0 : (firstValue < secondValue) ? -1 : 1;
} else {
return (firstValue == secondValue) ? 0 : (secondValue < firstValue) ? -1 : 1;
}
} else if (typeof(firstItem[currentSortBy]) == "string") {
var firstString = firstItem[currentSortBy].toLowerCase();
var secondString = secondItem[currentSortBy].toLowerCase();
if (currentSortType == "true") {
return (firstString == secondString) ? 0 : (firstString < secondString) ? -1 : 1;
} else {
return (firstString == secondString) ? 0 : (secondString < firstString) ? -1 : 1;
}
}
}
return 0;
});
} catch (err) {
}
return items;
};
/*
* get level 2 and beyond children (becomes a flat stucture)
*/
WcmDashboardWidgetCommon.getChilderenRecursive = function (items) {
for (var i = 0; i < items.length; i++) {
var item = items[i];
subChildren.push(item);
// add further dependencies
if (item.children && item.children.length > 0) {
WcmDashboardWidgetCommon.getChilderenRecursive(item.children);
}
}
}
/*
* build level 2 and beyond children (becomes a flat stucture)
*/
WcmDashboardWidgetCommon.getSubSubChilderen = function (table, parentClass, items, widgetId, depth) {
var rowHtml = "";
var instance = WcmDashboardWidgetCommon.dashboards[widgetId];
for (var i = 0; i < items.length; i++) {
var item = items[i];
//rowHtml += "<tr class='" + parentClass + "'><td colspan='5' class='ttBlankRow3'></td></tr>";
var itemRowStart = "<tr class='" + parentClass + "'>";
var itemRowEnd = "</tr>";
//create table row for this item
var itemRow = WcmDashboardWidgetCommon.buildItemTableRow(item, instance, false, i, depth);
rowHtml += itemRowStart + itemRow + itemRowEnd;
}
return rowHtml;
};
WcmDashboardWidgetCommon.getDisplayName = function (item) {
var displayName = '';
var hasLastName = !CStudioAuthoring.Utils.isEmpty(item.userLastName);
if (hasLastName) {
displayName += item.userLastName;
}
var hasFirstName = !CStudioAuthoring.Utils.isEmpty(item.userFirstName);
if (hasFirstName) {
displayName += hasLastName ? ', ' + item.userFirstName : item.userFirstName;
}
return displayName;
};
WcmDashboardWidgetCommon.getFormattedString = function (str, maxLength, isNewFile) {
var formattedString = "";
if (str != undefined && str != null) {
if (str.length > maxLength) {
formattedString = str.substring(0, maxLength) + "...";
} else {
formattedString = str;
}
}
if (isNewFile) formattedString = formattedString + "*";
return formattedString;
};
WcmDashboardWidgetCommon.Ajax = {
container: null,
loadingImage: null,
disableDashboard: function () {
if (WcmDashboardWidgetCommon.Ajax.container != null) {
document.body.removeChild(WcmDashboardWidgetCommon.Ajax.container);
}
if (WcmDashboardWidgetCommon.Ajax.loadingImage != null) {
document.body.removeChild(WcmDashboardWidgetCommon.Ajax.loadingImage);
}
var container = YDom.get();
WcmDashboardWidgetCommon.Ajax.container = document.createElement("div");
with (WcmDashboardWidgetCommon.Ajax.container.style) {
backgroundColor = "#FFFFFF";
opacity = "0";
position = "absolute";
//display = "block";
width = YDom.getDocumentWidth() + "px";
height = YDom.getDocumentHeight() + "px";
top = "0";
right = "0";
bottom = "0";
left = "0";
zIndex = "1000";
}
WcmDashboardWidgetCommon.Ajax.loadingImage = document.createElement("i");
WcmDashboardWidgetCommon.Ajax.loadingImage.className = ' fa fa-spinner fa-spin fa-3x fa-fw';
document.body.appendChild(WcmDashboardWidgetCommon.Ajax.container);
document.body.appendChild(WcmDashboardWidgetCommon.Ajax.loadingImage);
var imagePopUp = new YAHOO.widget.Overlay(WcmDashboardWidgetCommon.Ajax.loadingImage);
imagePopUp.center();
imagePopUp.render();
},
enableDashboard: function () {
if (WcmDashboardWidgetCommon.Ajax.container != null) {
document.body.removeChild(WcmDashboardWidgetCommon.Ajax.container);
WcmDashboardWidgetCommon.Ajax.container = null;
}
if (WcmDashboardWidgetCommon.Ajax.loadingImage != null) {
document.body.removeChild(WcmDashboardWidgetCommon.Ajax.loadingImage);
WcmDashboardWidgetCommon.Ajax.loadingImage = null;
}
}
};
WcmDashboardWidgetCommon.hideURLCol = function () {
if ($(".container").width() < 707) {
$(".urlCol").each(function () {
$(this).hide();
});
$("th[id*='browserUri-']").each(function () {
$(this).hide();
});
} else {
$(".urlCol").each(function () {
$(this).show();
});
$("th[id*='browserUri-']").each(function () {
$(this).show();
});
}
}
/**
* init widget
*/
WcmDashboardWidgetCommon.init = function (instance) {
var widgetId = instance.widgetId;
var sortBy = instance.defaultSortBy;
var pageId = instance.pageId;
var hideEmptyRow = instance.hideEmptyRow;
/////////////////////////////////////////////////////
// added to protect un wanted values in text boxes //
////////////////////////////////////////////////////
if (YDom.get("widget-showitems-" + widgetId) != null) {
YDom.get("widget-showitems-" + widgetId).value = 10;
YDom.get("widget-showitems-" + widgetId + "-label").innerHTML = CMgs.format(langBundle, "showNumItems");
}
YEvent.onAvailable(widgetId, function () {
WcmDashboardWidgetCommon.dashboards[widgetId] = instance;
dashboardEl = YDom.get(widgetId);
dashboardEl.style.display = "none";
var hasPermsForDashboardFn = function (perms, permission) {
var hasPerm = false;
for (var k = 0; k < perms.permissions.length; k++) {
if (permission == perms.permissions[k]) {
hasPerm = true;
break;
}
}
return hasPerm;
}
var getPermsCb = {
widgetId: widgetId,
dashboardEl: dashboardEl,
success: function (perms) {
WcmDashboardWidgetCommon.cachedPerms = perms;
var dashboardEl = this.dashboardEl;
var permission = "none";
if (this.widgetId == "GoLiveQueue"
|| this.widgetId == "recentlyMadeLive"
|| this.widgetId == "approvedScheduledItems") {
permission = "publish";
}
if (this.widgetId == "icon-guide"
|| this.widgetId == "MyRecentActivity"
|| hasPermsForDashboardFn(perms, permission)) {
dashboardEl.style.display = "block";
dashboardEl.instance = instance;
var state = WcmDashboardWidgetCommon.getCurrentWidgetTogglePreference(widgetId, pageId);
WcmDashboardWidgetCommon.toggleWidget(widgetId, pageId, state);
var checkboxClick = function (event, matchedEl) {
CStudioAuthoring.Utils.Cookies.createCookie("dashboard-selected", instance.widgetId.trim());
if (instance.onCheckedClickHandler) {
instance.onCheckedClickHandler(event, matchedEl);
}
else {
WcmDashboardWidgetCommon.selectItem(matchedEl, matchedEl.checked);
}
isChecked();
};
var isChecked = function () {
var inputsElt = YDom.get(instance.widgetId + "-tbody").getElementsByClassName("dashlet-item-check");
var checkedElts = false;
var checkAllElt = YDom.get(instance.widgetId + "CheckAll");
for (var i = 0; i < inputsElt.length; i++) {
if (inputsElt[i].checked == true) {
checkedElts = true;
}
}
if (checkedElts) {
checkAllElt.checked = true;
} else {
checkAllElt.checked = false;
}
}
var editClick = function (event, matchedEl) {
WcmDashboardWidgetCommon.editItem(matchedEl, matchedEl.checked);
matchedEl.style.pointerEvents = "none";
if (typeof CStudioAuthoring.editDisabled === 'undefined') {
CStudioAuthoring.editDisabled = []
}
CStudioAuthoring.editDisabled.push(matchedEl);
};
var viewClick = function (event, matchedEl) {
WcmDashboardWidgetCommon.viewItem(matchedEl, matchedEl.checked);
};
var previewClick = function (event, matchedEl) {
WcmDashboardWidgetCommon.previewItem(matchedEl, matchedEl.checked);
};
var dispatchLinkClick = function (event, matchedEl) {
if (matchedEl.className.indexOf("previewLink") != -1) {
previewClick(event, matchedEl);
}
else if (matchedEl.className.indexOf("viewLink") != -1) {
viewClick(event, matchedEl);
}
else if (matchedEl.className.indexOf("editLink") != -1
&& matchedEl.className.indexOf("non-previewable-edit") == -1) {
editClick(event, matchedEl);
}
}
YEvent.delegate(widgetId, "click", checkboxClick, "input:not(#" + widgetId + "CheckAll)");
YEvent.delegate(widgetId, "click", dispatchLinkClick, "a");
var searchLimitInput = YDom.get("widget-showitems-" + widgetId);
var filterByCount = null;
if (searchLimitInput) {
var searchNumber = CStudioAuthoring.Service.getWindowState(CStudioAuthoringContext.user,
pageId,
widgetId,
"searchNumber");
if (searchNumber && !isNaN(searchNumber)) {
searchLimitInput.value = parseInt(searchNumber, 10);
} else {
searchLimitInput.value = instance.defaultSearchNumber;
}
filterByCount = (isNaN(searchLimitInput.value) ? 10 : parseInt(searchLimitInput.value, 10));
}
var widgetFilterBy = CStudioAuthoring.Service.getWindowState(CStudioAuthoringContext.user,
pageId,
widgetId,
"widgetFilterBy");
var filterByEl = YDom.get("widget-filterBy-" + widgetId);
if (widgetFilterBy && widgetFilterBy != undefined && widgetFilterBy != "") {
WcmDashboardWidgetCommon.loadFilterTableData(sortBy, YDom.get(widgetId), widgetId, filterByCount, widgetFilterBy);
} else if (filterByCount != null) {
WcmDashboardWidgetCommon.loadTableData(sortBy, YDom.get(widgetId), widgetId, filterByCount);
} else {
WcmDashboardWidgetCommon.loadTableData(sortBy, YDom.get(widgetId), widgetId);
}
var controlsListEl =
YDom.getElementsByClassName("cstudio-widget-controls", null, dashboardEl)[0] ||
YDom.getElementsByClassName("widget-controls", null, dashboardEl)[0];
if (controlsListEl) {
if (instance.renderAuxControls) {
instance.renderAuxControls(controlsListEl, widgetId);
}
}
if (state == 'closed') {
YDom.setStyle(YAHOO.util.Selector.query("#" + widgetId + " .widget-FilterBy")[0], "display", "none");
}
//attach keydown event to search limit input
if (searchLimitInput) {
var isInt = function (val) {
var parsedVal = parseInt(val);
if (isNaN(parsedVal) || val == "0") return false;
return ( val == parsedVal && val.toString() == parsedVal.toString() );
};
var searchLimitInputEvent = function (event) {
var searchNumber = searchLimitInput.value;
//added to protect non numeric input.
if (event.keyCode == "13") {
if (!isInt(searchNumber)) { //execute the ajax only if its a number
searchLimitInput.value = instance.defaultSearchNumber;
searchNumber = searchLimitInput.value;
}
//var searchNumber=searchLimitInput.value;
if (isInt(searchNumber)) { //execute the ajax only if its a integer number.
searchNumber = searchNumber.replace(/\+/g, "").replace(/\-/g, "");
searchLimitInput.value = searchNumber;
CStudioAuthoring.Service.setWindowState(CStudioAuthoringContext.user,
pageId,
widgetId,
"searchNumber",
searchNumber);
var sortBy = instance.currentSortBy ? instance.currentSortBy : instance.defaultSortBy;
var filterByEl = YDom.get("widget-filterBy-" + widgetId);
if (filterByEl && filterByEl.value != undefined && filterByEl.value != "") {
WcmDashboardWidgetCommon.loadFilterTableData(sortBy, YDom.get(widgetId), widgetId, searchNumber, filterByEl.value);
} else {
WcmDashboardWidgetCommon.loadTableData(sortBy, YDom.get(widgetId), widgetId, searchNumber);
}
} else {
searchLimitInput.value = instance.defaultSearchNumber;
}
}
};
var validateSearchLimitInputValue = function (event) {
var searchNum = searchLimitInput.value;
//insert default value if invalid
if (!isInt(searchNum)) {
searchLimitInput.value = instance.defaultSearchNumber;
}
};
YEvent.addListener(searchLimitInput, "keyup", searchLimitInputEvent);
YEvent.addListener(searchLimitInput, "blur", validateSearchLimitInputValue);
}
}
},
failure: function () {
}
};
if (WcmDashboardWidgetCommon.cachedPerms) {
getPermsCb.success(WcmDashboardWidgetCommon.cachedPerms);
}
else {
CStudioAuthoring.Service.getUserPermissions(CStudioAuthoringContext.site, "~DASHBOARD~", getPermsCb);
}
$(window).resize(function () {
WcmDashboardWidgetCommon.hideURLCol();
});
});
};
WcmDashboardWidgetCommon.getSimpleRow = function (prefix, widgetId, rowTitle, classes) {
var row = '<th id=\"' + prefix + '-' + widgetId + '\" class=\"' + classes + '\">' +
'<span>' +
rowTitle +
'</span>' +
'</span>' +
'</th>';
return row;
};
WcmDashboardWidgetCommon.getSortableRow = function (prefix, widgetId, rowTitle, classes) {
var row = '<th id=\"' + prefix + '-' + widgetId + '\" class=\"' + classes + '\">' +
'<span>' +
'<a href="javascript:void(0);" id=\"sort' + prefix + '-' + widgetId + '\">' + rowTitle + '</a>' +
'<span class="wcm-widget-margin"/>' +
'</span>' +
'<span id=\"sortIcon-' + prefix + '-' + widgetId + '\" class=\"ttSortDesc wcm-go-live-sort-columns-' + widgetId + '\" style=\"display:none\"></span>' +
'</th>';
return row;
};
WcmDashboardWidgetCommon.getDefaultSortRow = function (prefix, widgetId, rowTitle, classes) {
var row = '<th id=\"' + prefix + '-' + widgetId + '\" class=\"' + classes + '\">' +
'<span>' +
rowTitle +
'<span class=\"wcm-widget-margin\"/>' +
'</span>' +
'<span id=\"sortIcon-' + prefix + '-' + widgetId + '\" class=\"ttSortBlack\"></span>' +
'</th>';
return row;
};
/**
* open and close a given dashboard widget
*/
WcmDashboardWidgetCommon.toggleWidget = function (widgetId, pageId, newState) {
var widgetBodyEl = YDom.get(widgetId + "-body");
var widgetToggleEl = YDom.get("widget-toggle-" + widgetId) || {};
var currentState = widgetToggleEl ? (widgetToggleEl.className == 'ttOpen' ? 'closed' : 'open') : 'open';
var collapseCookie = CStudioAuthoringContext.site + "-" + widgetId + "-panel";
var link = YDom.get("section-widget-" + widgetId);
if (YAHOO.lang.isUndefined(newState)) {
newState = currentState == 'closed' ? 'open' : 'closed';
}
if (newState == 'closed') {
widgetToggleEl.className = 'ttOpen';
widgetBodyEl.style.display = "none";
YDom.addClass(link, "studio-section-widget-close");
YDom.setStyle("expand-all-" + widgetId, "display", "none");
YDom.setStyle("widget-expand-state-" + widgetId, "display", "none");
YDom.setStyle(YAHOO.util.Selector.query("#" + widgetId + " .recently-made-live")[0], "display", "none");
YDom.setStyle(YAHOO.util.Selector.query("#" + widgetId + " .recently-made-live-right")[0], "display", "none");
YDom.setStyle(YAHOO.util.Selector.query("#" + widgetId + " .widget-FilterBy")[0], "display", "none");
} else {
if (!CStudioAuthoring.Utils.Cookies.readCookie(collapseCookie)) {
widgetBodyEl.style.display = "block";
} else {
YDom.addClass(link, "studio-section-widget-close");
}
widgetToggleEl.className = "ttClose";
YDom.setStyle("expand-all-" + widgetId, "display", "block");
YDom.setStyle("widget-expand-state-" + widgetId, "display", "block");
YDom.setStyle(YAHOO.util.Selector.query("#" + widgetId + " .recently-made-live")[0], "display", "block");
YDom.setStyle(YAHOO.util.Selector.query("#" + widgetId + " .recently-made-live-right")[0], "display", "block");
YDom.setStyle(YAHOO.util.Selector.query("#" + widgetId + " .widget-FilterBy")[0], "display", "block");
}
CStudioAuthoring.Service.setWindowState(
CStudioAuthoringContext.user,
pageId,
widgetId,
"widgetToggle",
newState);
return false;
};
/**
* get user's preference on widget state
*/
WcmDashboardWidgetCommon.getCurrentWidgetTogglePreference = function (widgetId, pageId) {
var widgetState = "";
widgetState = CStudioAuthoring.Service.getWindowState(
CStudioAuthoringContext.user,
pageId,
widgetId,
"widgetToggle");
return widgetState;
};
/**
* toggle (expand or collapse) a given line item
*/
WcmDashboardWidgetCommon.toggleLineItem = function (id, ignoreParent) {
var parentId = YDom.get(id),
childItems = CStudioAuthoring.Utils.getElementsByClassName(id),
length = childItems.length,
idx,
item;
if (parentId.className == "ttClose parent-div-widget") {
for (idx = 0; idx < length; idx++) {
item = childItems[idx];
if (item) {
item.style.display = "none";
}
}
parentId.className = "ttOpen parent-div-widget";
}
else {
for (idx = 0; idx < length; idx++) {
item = childItems[idx];
if (item) {
item.style.display = "";
}
}
parentId.className = "ttClose parent-div-widget";
}
// If all lines are collapsed, then the header link should change to "Expand All" and vice versa.
var expandAll = false,
tableEl = YDom.getAncestorByTagName(id, "table"),
rows = tableEl.rows,
arr = [],
widgetId = tableEl.id.split("-")[0],
widget = YDom.get(widgetId),
linkEl = YDom.get("expand-all-" + widgetId);
for (idx = 0; idx < rows.length; idx++) {
if (rows[idx].className === "avoid" || rows[idx].className == "") {
continue;
} else {
arr.push(rows[idx]);
}
}
for (idx = 0; idx < arr.length; idx++) {
if (arr[idx].style.display === "none") {
expandAll = true;
break;
}
}
if (!ignoreParent) {
this.toggleHeaderLink(widget, linkEl, expandAll);
}
};
WcmDashboardWidgetCommon.toggleHeaderLink = function (widget, linkEl, showCollapsed) {
if (showCollapsed) {
linkEl.setAttribute("href", "javascript:void(0);");
linkEl.innerHTML = CMgs.format(langBundle, "dashboardExpandAll");
linkEl.className = "btn btn-default btn-sm widget-collapse-state";
widget.instance.expanded = false;
}
else {
linkEl.setAttribute("href", "javascript:void(0);");
linkEl.innerHTML = CMgs.format(langBundle, "dashboardCollapseAll");
linkEl.className = "btn btn-default btn-sm widget-expand-state";
widget.instance.expanded = true;
}
}
/**
* toggle All items
*/
WcmDashboardWidgetCommon.toggleAllItems = function (widgetId) {
var widget = YDom.get(widgetId),
instance = widget.instance,
link = YDom.get("expand-all-" + widgetId),
items = YDom.getElementsByClassName("parent-div-widget", null, widget),
item,
length = items.length;
for (var count = 0; count < length; count++) {
item = items[count];
if (item) {
item.className = (instance.expanded) ? "ttClose parent-div-widget" : "ttOpen parent-div-widget";
this.toggleLineItem(item.id, true);
}
}
this.toggleHeaderLink(widget, link, instance.expanded);
};
/**
* toggle the whole table
*/
WcmDashboardWidgetCommon.toggleTable = function (widgetId) {
var table = YDom.get(widgetId + "-body"),
link = YDom.get("section-widget-" + widgetId),
site = CStudioAuthoringContext.site;
if (!YDom.hasClass(link, "studio-section-widget-close")) {
YDom.setStyle(table, "display", "none");
YDom.addClass(link, "studio-section-widget-close");
CStudioAuthoring.Utils.Cookies.createCookie(site + "-" + widgetId + "-panel", "collapse");
} else {
YDom.setStyle(table, "display", "block");
YDom.removeClass(link, "studio-section-widget-close");
CStudioAuthoring.Utils.Cookies.eraseCookie(site + "-" + widgetId + "-panel");
}
};
/**
* edit an item
*/
WcmDashboardWidgetCommon.editItem = function (matchedElement, isChecked) {
var editCallback = {
success: function (contentTO, editorId, name, value, draft) {
if(CStudioAuthoringContext.isPreview){
try{
CStudioAuthoring.Operations.refreshPreview();
}catch(err) {
if(!draft) {
this.callingWindow.location.reload(true);
}
}
}
else {
if(!draft) {
//this.callingWindow.location.reload(true);
}
}
if(contentTO.updatedModel && contentTO.initialModel &&
contentTO.updatedModel.orderDefault_f != contentTO.initialModel.orderDefault_f){
if(CStudioAuthoring.ContextualNav.WcmRootFolder) {
eventYS.data = contentTO.item;
eventYS.typeAction = "edit";
eventYS.draft = draft;
document.dispatchEvent(eventYS);
}else{
eventNS.data = contentTO.item;
eventNS.typeAction = "edit";
eventNS.draft = draft;
document.dispatchEvent(eventNS);
}
}else{
eventNS.data = contentTO.item;
eventNS.typeAction = "edit";
eventNS.draft = draft;
document.dispatchEvent(eventNS);
}
},
failure: function () {
},
callingWindow: window
};
var getContentCallback = {
success: function (contentTO) {
WcmDashboardWidgetCommon.Ajax.enableDashboard();
CStudioAuthoring.Operations.editContent(
contentTO.form,
CStudioAuthoringContext.siteId,
contentTO.uri,
contentTO.nodeRef,
contentTO.uri,
false,
editCallback);
},
failure: function () {
WcmDashboardWidgetCommon.Ajax.enableDashboard();
}
};
WcmDashboardWidgetCommon.Ajax.disableDashboard();
WcmDashboardWidgetCommon.getContentItemForMatchedElement(matchedElement, getContentCallback);
};
WcmDashboardWidgetCommon.viewItem = function (matchedElement, isChecked) {
var editCallback = {
success: function () {
this.callingWindow.location.reload(true);
},
failure: function () {
},
callingWindow: window
};
var getContentCallback = {
success: function (contentTO) {
WcmDashboardWidgetCommon.Ajax.enableDashboard();
if (contentTO.uri.indexOf("/site") == 0) {
CStudioAuthoring.Operations.viewContent(
contentTO.form,
CStudioAuthoringContext.siteId,
contentTO.uri,
contentTO.nodeRef,
contentTO.uri,
false,
editCallback);
}
else {
// CStudioAuthoring.Operations.openTemplateEditor(contentTO.uri, "default", editCallback);
}
},
failure: function () {
WcmDashboardWidgetCommon.Ajax.enableDashboard();
}
};
WcmDashboardWidgetCommon.Ajax.disableDashboard();
WcmDashboardWidgetCommon.getContentItemForMatchedElement(matchedElement, getContentCallback);
};
/**
* User clicked on preview link, open preview
*/
WcmDashboardWidgetCommon.previewItem = function (matchedElement, isChecked) {
var callback = {
success: function (contentTO) {
if (contentTO.name.indexOf(".xml") != -1) {
CStudioAuthoring.Storage.write(CStudioAuthoring.Service.menuParentPathKeyFromItemUrl(contentTO.path), contentTO.path);
}
CStudioAuthoring.Operations.openPreview(contentTO);
},
failure: function () {
}
};
WcmDashboardWidgetCommon.getContentItemForMatchedElement(matchedElement, callback);
};
/**
* Select an item in the dashboard widget
*/
WcmDashboardWidgetCommon.selectItem = function (matchedElement, isChecked, triggerEvent) {
if (matchedElement.type == "checkbox") WcmDashboardWidgetCommon.Ajax.disableDashboard();
var callback = {
success: function (contentTO) {
if (isChecked == true) {
CStudioAuthoring.SelectedContent.selectContent(contentTO, triggerEvent);
}
else {
CStudioAuthoring.SelectedContent.unselectContent(contentTO, triggerEvent);
}
WcmDashboardWidgetCommon.Ajax.enableDashboard();
},
failure: function () {
WcmDashboardWidgetCommon.Ajax.enableDashboard();
}
};
WcmDashboardWidgetCommon.getContentItemForMatchedElement(matchedElement, callback);
};
/**
* return the transfer object for the matched item
*/
WcmDashboardWidgetCommon.getContentItemForMatchedElement = function (matchedElement, callback) {
var itemUrl = "";
// walk the DOM to get the path get parent of current element
var parentTD = YDom.getAncestorByTagName(matchedElement, "td");
// get a sibling, that is <td>, that has attribute of title
var urlEl = YDom.getNextSiblingBy(parentTD, function (el) {
return el.getAttribute('title') == 'fullUri';
});
if (!urlEl) { // if url null return
callback.failure();
return;
}
else {
itemUrl = urlEl.innerHTML;
}
var getContentItemsCb = {
success: function (contentTO) {
callback.success(contentTO.item);
},
failure: function () {
callback.failure();
}
};
CStudioAuthoring.Service.lookupContentItem(CStudioAuthoringContext.site, itemUrl, getContentItemsCb, false, false);
}
/**
* load and render table data
*/
WcmDashboardWidgetCommon.loadTableData = function (sortBy, container, widgetId, filterByNumber, sortFromCachedData) {
var instance = WcmDashboardWidgetCommon.dashboards[widgetId];
var tableName = widgetId;
var webscriptName = widgetId + "-table";
var divTableContainer = widgetId + "-body";
var currentSortBy = (sortBy) ? sortBy : null;
var currentSortType = "";
var hideEmptyRow = instance.hideEmptyRow;
var pageId = instance.pageId;
var callback = {
success: function (results) {
if (results.total > 0) {
YDom.addClass(divTableContainer, "table-responsive");
}
instance.dashBoardData = results;
var sortDocuments = results.documents;
instance.tooltipLabels = new Array();
var newtable = "";
var blankRow = ''; // "<tr class='avoid'><td class='ttBlankRow' colspan='5'> </td></tr>";
var count = 0;
var sortedByValue = results.sortedBy;
var sortType = results.sortType;
var previousSortedBy = YDom.get('sortedBy-' + widgetId).innerHTML;
var previousSortType = YDom.get('sort-type-' + widgetId).innerHTML;
if (previousSortedBy == currentSortBy) {
if (previousSortType == "true") {
currentSortType = "false";
}
else {
currentSortType = "true";
}
}
else {
currentSortType = "false";
}
// update total count
var totalCountEl = YDom.get(widgetId + "-total-count");
if (totalCountEl != undefined) {
totalCountEl.innerHTML = results.total;
}
if (sortFromCachedData && sortDocuments.length > 1) {
if (instance.skipComponentSort) {
//Don't sort by components
} else {
//if skipComponentSort flag not available
sortDocuments = WcmDashboardWidgetCommon.sortItems(sortDocuments, currentSortBy, currentSortType)
}
}
// update custom header controls
// create line items
for (var j = 0; j < sortDocuments.length; j++) {
var items = sortDocuments[j].children;
var document = sortDocuments[j];
count = count + 1;
var name = (sortDocuments[j].internalName != undefined) ? sortDocuments[j].internalName : "error";
var parentClass = "wcm-table-parent-" + name + "-" + count;
if (!hideEmptyRow || sortDocuments[j].numOfChildren > 0) {
var table = "<tr>";
table += WcmDashboardWidgetCommon.buildItemTableRow(sortDocuments[j], instance, true, count, 0);
table += "</tr>";
if (sortFromCachedData) {
items = WcmDashboardWidgetCommon.sortItems(items, currentSortBy, currentSortType)
}
for (var i = 0; i < items.length; i++) {
var item = items[i];
//table = table + "<tr class='" + parentClass + "'><td colspan='5' class='ttBlankRow3'></td></tr>";
var itemRowStart = "<tr class='" + parentClass + "'>";
var itemRowEnd = "</tr>";
var subItemRowStart = "<tr class='" + parentClass + "'><td><span class='wcm-widget-margin'></span><span class='ttFirstCol128'><input title='All' class='dashlet-item-check1' id=tableName + 'CheckAll' type='checkbox' /></span><span class='wcm-widget-margin'></span>";
//create table row for this item
var itemRow = WcmDashboardWidgetCommon.buildItemTableRow(item, instance, false, i, 0);
table += itemRowStart + itemRow + itemRowEnd;
var subItems = item.children;
if (subItems && subItems.length > 0) {
subChildren = new Array();
WcmDashboardWidgetCommon.getChilderenRecursive(subItems);
subChildren = WcmDashboardWidgetCommon.sortItems(subChildren, currentSortBy, currentSortType)
table += WcmDashboardWidgetCommon.getSubSubChilderen(table, parentClass, subChildren, widgetId, 1);
//table += WcmDashboardWidgetCommon.getSubSubChilderenRecursive(table, parentClass, subItems, widgetId, 1);
}
}
newtable += table;
}
}
newtable = blankRow + newtable + blankRow;
var tableContentStart = '<table id="' + tableName + '-table" class="table">';
var theadContent = '<thead id="' + tableName + '-thead"><tr class="avoid">' + instance.renderItemsHeading() + '</tr></thead>';
var tbodyContent = '<tbody id="' + tableName + '-tbody" class="ttTbody">' + newtable + '</tbody>';
var tableContentEnd = '</table>';
//Check for already checked items,
//un-check then to remove those items from selected items list.
var checkboxArray = YDom.getElementsBy(function (el) {
return ( el.type === 'checkbox' && el.checked === true);
}, 'input', divTableContainer);
if (checkboxArray && checkboxArray.length >= 1) {
for (var chkIdx = 0; chkIdx < checkboxArray.length; chkIdx++) {
checkboxArray[chkIdx].checked = false;
WcmDashboardWidgetCommon.clearItem(checkboxArray[chkIdx], instance.dashBoardData);
}
}
YDom.get(divTableContainer).innerHTML = tableContentStart + theadContent + tbodyContent + tableContentEnd;
YEvent.delegate(widgetId + "-thead", "click", WcmDashboardWidgetCommon.sortClick, 'th a', {
'widgetId': widgetId,
'sortBy': currentSortBy
}, true);
WcmDashboardWidgetCommon.updateSortIconsInWidget(currentSortBy, currentSortType, widgetId);
YDom.get('sortedBy-' + widgetId).innerHTML = currentSortBy;
YDom.get('sort-type-' + widgetId).innerHTML = currentSortType;
instance.currentSortBy = sortBy;
instance.searchNumber = filterByNumber;
/**
* remove loading image for recent current widget
*/
YDom.setStyle("loading-" + widgetId, "display", "none");
/**
* ajax call link in dashboard widget will be showed/hide
* according to widget state..
*/
var widgetState = CStudioAuthoring.Service.getWindowState(CStudioAuthoringContext.user, pageId, widgetId, "widgetToggle");
if (widgetState == "closed") {
YDom.setStyle("widget-expand-state-" + widgetId, "display", "none");
} else {
YDom.setStyle("widget-expand-state-" + widgetId, "display", "block");
}
/*************************************************************
* registering mouse over and mouse out events for row items.
************************************************************/
var rowMouseover = function (event, matchedEl) {
YDom.addClass(matchedEl, "over");
};
var rowMouseout = function (event, matchedEl) {
YDom.removeClass(matchedEl, "over", "");
};
YEvent.delegate(webscriptName, "mouseover", rowMouseover, "tr");
YEvent.delegate(webscriptName, "mouseout", rowMouseout, "tr");
// adding tool tip display
if (instance.tooltipLabels && instance.tooltipLabels.length >= 1) {
var oTTContainer = YDom.get("acn-context-tooltip-widgets");
if (!oTTContainer) {
var toolTipContainer = window.document.createElement("div");
toolTipContainer.setAttribute("id", "acn-context-tooltip-widgets");
toolTipContainer.className = "acn-context-tooltip";
toolTipContainer.innerHTML = "<div style=\"z-index: 2; left: 73px; top: 144px; visibility: hidden;\"" +
" class=\"yui-module yui-overlay yui-tt\"" +
"id=\"acn-context-tooltipWrapper-widgets\"><div class=\"bd\"></div>" +
"<div class=\"yui-tt-shadow\"></div>" +
"<div class=\"yui-tt-shadow\"></div>" +
"<div class=\"yui-tt-shadow\"></div>" + "</div>";
window.document.body.appendChild(toolTipContainer);
}
new YAHOO.widget.Tooltip("acn-context-tooltipWrapper-widgets", {
context: instance.tooltipLabels,
hidedelay: 0,
showdelay: 500,
container: "acn-context-tooltip-widgets"
});
}
if (!instance.expanded) {
instance.expanded = true;
WcmDashboardWidgetCommon.toggleAllItems(widgetId);
}
YEvent.addListener(tableName + "CheckAll", 'click', function (e) {
YDom.setStyle("loading-" + widgetId, "display", "");
setTimeout(function(){
var checkAllElt = YDom.get(tableName + 'CheckAll');
var inputsElt = window.document.querySelectorAll("#" + tableName + " input:enabled");
var avoidEvent;
if (checkAllElt.checked == true) {
for (var i = 1; i < inputsElt.length; i++) {
inputsElt[i].checked = true;
avoidEvent = i == (inputsElt.length - 1) ? false : true;
WcmDashboardWidgetCommon.selectItem(inputsElt[i], inputsElt[i].checked, avoidEvent);
}
} else {
for (var i = 1; i < inputsElt.length; i++) {
inputsElt[i].checked = false;
avoidEvent = i == (inputsElt.length - 1) ? false : true;
WcmDashboardWidgetCommon.selectItem(inputsElt[i], inputsElt[i].checked, avoidEvent);
}
}
YDom.setStyle("loading-" + widgetId, "display", "none");
}, 10);
}, this, true);
WcmDashboardWidgetCommon.hideURLCol();
},
failure: function () {
YDom.setStyle("loading-" + widgetId, "display", "none");
},
beforeServiceCall: function () {
YDom.setStyle("loading-" + widgetId, "display", "");
}
};
if (sortFromCachedData && instance.dashBoardData) {
callback.success(instance.dashBoardData);
} else {
instance.retrieveTableData(currentSortBy, currentSortType, callback, null, filterByNumber);
}
};
/////For filtering Widgets
WcmDashboardWidgetCommon.loadFilterTableData = function (sortBy, container, widgetId, filterByNumber, filterBy) {
var instance = WcmDashboardWidgetCommon.dashboards[widgetId];
var tableName = widgetId;
var webscriptName = widgetId + "-table";
var divTableContainer = widgetId + "-body";
var currentSortBy = (sortBy) ? sortBy : null;
var currentSortType = "";
var hideEmptyRow = instance.hideEmptyRow;
var pageId = instance.pageId;
var callback = {
success: function (results) {
if (results.total > 0) {
YDom.addClass(divTableContainer, "table-responsive");
}
instance.dashBoardData = results;
var sortDocuments = results.documents;
instance.tooltipLabels = new Array();
var newtable = "";
var blankRow = ''; //"<tr class='avoid'><td class='ttBlankRow' colspan='5'> </td></tr>";
var count = 0;
var sortedByValue = results.sortedBy;
var sortType = results.sortType;
var previousSortedBy = YDom.get('sortedBy-' + widgetId).innerHTML;
var previousSortType = YDom.get('sort-type-' + widgetId).innerHTML;
if (previousSortedBy == currentSortBy) {
if (previousSortType == "true") {
currentSortType = "false";
}
else {
currentSortType = "true";
}
}
else {
currentSortType = "false";
}
// update total count
var totalCountEl = YDom.get(widgetId + "-total-count");
if (totalCountEl != undefined) {
totalCountEl.innerHTML = results.total;
}
// update custom header controls
// create line items
for (var j = 0; j < sortDocuments.length; j++) {
var items = sortDocuments[j].children;
var document = sortDocuments[j];
count = count + 1;
var name = (sortDocuments[j].internalName != undefined) ? sortDocuments[j].internalName : "error";
var parentClass = "wcm-table-parent-" + name + "-" + count;
if (!hideEmptyRow || sortDocuments[j].numOfChildren > 0) {
var table = "<tr>";
table += WcmDashboardWidgetCommon.buildItemTableRow(sortDocuments[j], instance, true, count, 0);
table += "</tr>";
for (var i = 0; i < items.length; i++) {
var item = items[i];
//table = table + "<tr class='" + parentClass + "'><td colspan='5' class='ttBlankRow3'></td></tr>";
var itemRowStart = "<tr class='" + parentClass + "'>";
var itemRowEnd = "</tr>";
var subItemRowStart = "<tr class='" + parentClass + "'><td><span class='wcm-widget-margin'></span><span class='ttFirstCol128'><input type='checkbox'/></span><span class='wcm-widget-margin'></span>";
//create table row for this item
var itemRow = WcmDashboardWidgetCommon.buildItemTableRow(item, instance, false, i, 0);
table += itemRowStart + itemRow + itemRowEnd;
var subItems = item.children;
if (subItems && subItems.length > 0) {
table += WcmDashboardWidgetCommon.getSubSubChilderenRecursive(table, parentClass, subItems, widgetId, 1);
}
}
newtable += table;
}
}
newtable = blankRow + newtable + blankRow;
var tableContentStart = '<table id="' + tableName + '-table" class="table" border="0">';
var theadContent = '<thead class="ttThead" id="' + tableName + '-thead"><tr class="avoid">' + instance.renderItemsHeading() + '</tr></thead>';
var tbodyContent = '<tbody class="ttTbody" id="' + tableName + '-tbody" class="ttTbody">' + newtable + '</tbody>';
var tableContentEnd = '</table>';
//Check for already checked items,
//un-check then to remove those items from selected items list.
var checkboxArray = YDom.getElementsBy(function (el) {
return ( el.type === 'checkbox' && el.checked === true);
},
'input',
divTableContainer);
if (checkboxArray && checkboxArray.length >= 1 && (eventNS.typeAction =="edit" && !eventNS.draft)) {
for (var chkIdx = 0; chkIdx < checkboxArray.length; chkIdx++) {
checkboxArray[chkIdx].checked = false;
WcmDashboardWidgetCommon.clearItem(checkboxArray[chkIdx], instance.dashBoardData);
}
}
YDom.get(divTableContainer).innerHTML = tableContentStart + theadContent + tbodyContent + tableContentEnd;
YEvent.delegate(widgetId + "-thead", "click", WcmDashboardWidgetCommon.sortClick, 'th a', {
'widgetId': widgetId,
'sortBy': currentSortBy
}, true);
WcmDashboardWidgetCommon.updateSortIconsInWidget(currentSortBy, currentSortType, widgetId);
YDom.get('sortedBy-' + widgetId).innerHTML = currentSortBy;
YDom.get('sort-type-' + widgetId).innerHTML = currentSortType;
instance.currentSortBy = sortBy;
instance.searchNumber = filterByNumber;
/**
* remove loading image for recent current widget
*/
YDom.setStyle("loading-" + widgetId, "display", "none");
/**
* ajax call link in dashboard widget will be showed/hide
* according to widget state..
*/
var widgetState = CStudioAuthoring.Service.getWindowState(CStudioAuthoringContext.user, pageId, widgetId, "widgetToggle");
if (widgetState == "closed") {
YDom.setStyle("widget-expand-state-" + widgetId, "display", "none");
} else {
YDom.setStyle("widget-expand-state-" + widgetId, "display", "block");
}
/*************************************************************
* registering mouse over and mouse out events for row items.
************************************************************/
var rowMouseover = function (event, matchedEl) {
YDom.addClass(matchedEl, "over");
};
var rowMouseout = function (event, matchedEl) {
YDom.removeClass(matchedEl, "over", "");
};
YEvent.delegate(webscriptName, "mouseover", rowMouseover, "tr");
YEvent.delegate(webscriptName, "mouseout", rowMouseout, "tr");
// adding tool tip display
if (instance.tooltipLabels && instance.tooltipLabels.length >= 1) {
var oTTContainer = YDom.get("acn-context-tooltip-widgets");
if (!oTTContainer) {
var toolTipContainer = window.document.createElement("div");
toolTipContainer.setAttribute("id", "acn-context-tooltip-widgets");
toolTipContainer.className = "acn-context-tooltip";
toolTipContainer.innerHTML = "<div style=\"z-index: 2; left: 73px; top: 144px; visibility: hidden;\"" +
" class=\"yui-module yui-overlay yui-tt\"" +
"id=\"acn-context-tooltipWrapper-widgets\"><div class=\"bd\"></div>" +
"<div class=\"yui-tt-shadow\"></div>" +
"<div class=\"yui-tt-shadow\"></div>" +
"<div class=\"yui-tt-shadow\"></div>" + "</div>";
window.document.body.appendChild(toolTipContainer);
}
new YAHOO.widget.Tooltip("acn-context-tooltipWrapper-widgets", {
context: instance.tooltipLabels,
hidedelay: 0,
showdelay: 500,
container: "acn-context-tooltip-widgets"
});
}
if (!instance.expanded) {
instance.expanded = true;
WcmDashboardWidgetCommon.toggleAllItems(widgetId);
}
YEvent.addListener(tableName + "CheckAll", 'click', function (e) {
var checkAllElt = YDom.get(tableName + 'CheckAll');
var inputsElt = window.document.querySelectorAll("#" + tableName + " input:enabled");
WcmDashboardWidgetCommon.Ajax.disableDashboard();
if (checkAllElt.checked == true) {
for (var i = 1; i < inputsElt.length; i++) {
inputsElt[i].checked = true;
WcmDashboardWidgetCommon.selectItem(inputsElt[i], inputsElt[i].checked);
}
} else {
for (var i = 1; i < inputsElt.length; i++) {
inputsElt[i].checked = false;
WcmDashboardWidgetCommon.selectItem(inputsElt[i], inputsElt[i].checked);
}
}
}, this, true);
},
failure: function () {
YDom.setStyle("loading-" + widgetId, "display", "none");
},
beforeServiceCall: function () {
YDom.setStyle("loading-" + widgetId, "display", "block");
}
};
instance.retrieveTableData(currentSortBy, currentSortType, callback, null, filterByNumber, filterBy);
};
/**
* Handle children level 2 and beyond (becomes a flat stucture)
*/
WcmDashboardWidgetCommon.getSubSubChilderenRecursive = function (table, parentClass, items, widgetId, depth) {
var rowHtml = "";
var instance = WcmDashboardWidgetCommon.dashboards[widgetId];
for (var i = 0; i < items.length; i++) {
var item = items[i];
//rowHtml += "<tr class='" + parentClass + "'><td colspan='5' class='ttBlankRow3'></td></tr>";
var itemRowStart = "<tr class='" + parentClass + "'>";
var itemRowEnd = "</tr>";
//create table row for this item
var itemRow = WcmDashboardWidgetCommon.buildItemTableRow(item, instance, false, i, depth);
rowHtml += itemRowStart + itemRow + itemRowEnd;
// add further dependencies
if (item.children && item.children.length > 0) {
rowHtml += WcmDashboardWidgetCommon.getSubSubChilderenRecursive(table, parentClass, item.children, widgetId, depth + 1);
}
}
return rowHtml;
};
/**
* call render line item for the particular kind of dashboard
* @param item - content object
* @param dashboardInstance instance of the dashboard
*/
WcmDashboardWidgetCommon.buildItemTableRow = function (item, dashboardInstance, firstRow, count, depth) {
return dashboardInstance.renderLineItem(item, firstRow, count, depth);
};
/**
* update sorting icons
*/
WcmDashboardWidgetCommon.updateSortIconsInWidget = function (currentSortBy, currentSortType, widgetId) {
if (YAHOO.lang.isNull(currentSortBy)) {
return;
}
//valid for sorting clicks
var currentSortById = "sortIcon-" + currentSortBy + '-' + widgetId;
if (currentSortType == "true") {
currentSortType = "ttSortAsc";
}
else {
currentSortType = "ttSortDesc";
}
var sortColumns = CStudioAuthoring.Utils.getElementsByClassName('wcm-go-live-sort-columns-' + widgetId);
var count = 0;
var length = sortColumns.length;
while (length > count) {
var item = sortColumns[count];
if (item != undefined) {
if (item.id == currentSortById) {
item.style.display = "inline-block";
item.className = currentSortType + " wcm-go-live-sort-columns-" + widgetId;
}
else {
item.style.display = "none";
}
}
count = count + 1;
}
};
WcmDashboardWidgetCommon.initFilterToWidget = function (widgetId, widgetFilterBy) {
var filterByEl = document.createElement("select");
if (widgetId) {
filterByEl.setAttribute("id", "widget-filterBy-" + widgetId);
}
filterByEl.className = 'form-control input-sm';
filterByEl.options[0] = new Option(CMgs.format(langBundle, "dashletFilterPages"), "page", true, false);
filterByEl.options[1] = new Option(CMgs.format(langBundle, "dashletFilterComponents"), "component", true, false);
filterByEl.options[2] = new Option(CMgs.format(langBundle, "dashletFilterDocuments"), "document", true, false);
filterByEl.options[3] = new Option(CMgs.format(langBundle, "dashletFilterAll"), "all", true, false);
//set default value from cookie
if (widgetFilterBy) {
for (var optIdx = 0; optIdx < filterByEl.options.length; optIdx++) {
if (filterByEl.options[optIdx].value == widgetFilterBy) {
filterByEl.options[optIdx].selected = true;
break;
}
}
}
return filterByEl;
};
/**
* get selected item from cache data
*/
WcmDashboardWidgetCommon.getContentRecursive = function (dashBoardData, itemUrl) {
var sortDocuments = dashBoardData.documents;
var result = null;
for (var j = 0; j < sortDocuments.length; j++) {
if (sortDocuments[j].uri == itemUrl) {
return sortDocuments[j];
}
if (sortDocuments[j].children && sortDocuments[j].children >= 1) {
result = WcmDashboardWidgetCommon.getContentRecursive(sortDocuments[j].children, itemUrl);
if (result) break;
}
}
return result;
};
/**
* clear selected item in the dashboard widget
*/
WcmDashboardWidgetCommon.clearItem = function (matchedElement, dashBoardData) {
if (matchedElement.type == "checkbox") {
if (dashBoardData) {
var itemUrl = "";
// walk the DOM to get the path get parent of current element
var parentTD = YDom.getAncestorByTagName(matchedElement, "td");
// get a sibling, that is <td>, that has attribute of title
var urlEl = YDom.getNextSiblingBy(parentTD, function (el) {
return el.getAttribute('title') == 'fullUri';
});
if (!urlEl) { // if url null return
return;
}
else {
itemUrl = urlEl.innerHTML;
}
//check for matched element from cache
var contentTO = WcmDashboardWidgetCommon.getContentRecursive(dashBoardData, itemUrl);
if (contentTO) {
CStudioAuthoring.SelectedContent.unselectContent(contentTO);
return;
}
}
WcmDashboardWidgetCommon.selectItem(matchedElement, false);
}
};
| jvega-crafter/studio-ui | static-assets/components/cstudio-dashboard-widgets/lib/wcm-dashboardwidget-common.js | JavaScript | gpl-3.0 | 65,409 | [
30522,
13075,
21076,
5358,
1027,
20643,
1012,
21183,
4014,
1012,
14383,
1025,
13075,
6300,
15338,
1027,
20643,
1012,
21183,
4014,
1012,
2724,
1025,
13075,
4942,
19339,
7389,
1027,
19701,
1025,
13075,
9530,
8873,
13512,
14428,
15975,
1027,
197... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/* Target-dependent code for PowerPC systems running FreeBSD.
Copyright (C) 2013-2017 Free Software Foundation, Inc.
This file is part of GDB.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include "defs.h"
#include "arch-utils.h"
#include "frame.h"
#include "gdbcore.h"
#include "frame-unwind.h"
#include "gdbtypes.h"
#include "osabi.h"
#include "regcache.h"
#include "regset.h"
#include "symtab.h"
#include "target.h"
#include "trad-frame.h"
#include "ppc-tdep.h"
#include "ppc64-tdep.h"
#include "ppc-fbsd-tdep.h"
#include "fbsd-tdep.h"
#include "solib-svr4.h"
/* 32-bit regset descriptions. */
static const struct ppc_reg_offsets ppc32_fbsd_reg_offsets =
{
/* General-purpose registers. */
/* .r0_offset = */ 0,
/* .gpr_size = */ 4,
/* .xr_size = */ 4,
/* .pc_offset = */ 144,
/* .ps_offset = */ -1,
/* .cr_offset = */ 132,
/* .lr_offset = */ 128,
/* .ctr_offset = */ 140,
/* .xer_offset = */ 136,
/* .mq_offset = */ -1,
/* Floating-point registers. */
/* .f0_offset = */ 0,
/* .fpscr_offset = */ 256,
/* .fpscr_size = */ 8,
#ifdef NOTYET
/* AltiVec registers. */
/* .vr0_offset = */ 0,
/* .vscr_offset = */ 512 + 12,
/* .vrsave_offset = */ 512
#endif
};
/* 64-bit regset descriptions. */
static const struct ppc_reg_offsets ppc64_fbsd_reg_offsets =
{
/* General-purpose registers. */
/* .r0_offset = */ 0,
/* .gpr_size = */ 8,
/* .xr_size = */ 8,
/* .pc_offset = */ 288,
/* .ps_offset = */ -1,
/* .cr_offset = */ 264,
/* .lr_offset = */ 256,
/* .ctr_offset = */ 280,
/* .xer_offset = */ 272,
/* .mq_offset = */ -1,
/* Floating-point registers. */
/* .f0_offset = */ 0,
/* .fpscr_offset = */ 256,
/* .fpscr_size = */ 8,
#ifdef NOYET
/* AltiVec registers. */
/* .vr0_offset = */ 0,
/* .vscr_offset = */ 512 + 12,
/* .vrsave_offset = */ 528
#endif
};
/* 32-bit general-purpose register set. */
static const struct regset ppc32_fbsd_gregset = {
&ppc32_fbsd_reg_offsets,
ppc_supply_gregset,
ppc_collect_gregset
};
/* 64-bit general-purpose register set. */
static const struct regset ppc64_fbsd_gregset = {
&ppc64_fbsd_reg_offsets,
ppc_supply_gregset,
ppc_collect_gregset
};
/* 32-/64-bit floating-point register set. */
static const struct regset ppc32_fbsd_fpregset = {
&ppc32_fbsd_reg_offsets,
ppc_supply_fpregset,
ppc_collect_fpregset
};
const struct regset *
ppc_fbsd_gregset (int wordsize)
{
return wordsize == 8 ? &ppc64_fbsd_gregset : &ppc32_fbsd_gregset;
}
const struct regset *
ppc_fbsd_fpregset (void)
{
return &ppc32_fbsd_fpregset;
}
/* Iterate over core file register note sections. */
static void
ppcfbsd_iterate_over_regset_sections (struct gdbarch *gdbarch,
iterate_over_regset_sections_cb *cb,
void *cb_data,
const struct regcache *regcache)
{
struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
if (tdep->wordsize == 4)
cb (".reg", 148, &ppc32_fbsd_gregset, NULL, cb_data);
else
cb (".reg", 296, &ppc64_fbsd_gregset, NULL, cb_data);
cb (".reg2", 264, &ppc32_fbsd_fpregset, NULL, cb_data);
}
/* Default page size. */
static const int ppcfbsd_page_size = 4096;
/* Offset for sigreturn(2). */
static const int ppcfbsd_sigreturn_offset[] = {
0xc, /* FreeBSD 32-bit */
-1
};
/* Signal trampolines. */
static int
ppcfbsd_sigtramp_frame_sniffer (const struct frame_unwind *self,
struct frame_info *this_frame,
void **this_cache)
{
struct gdbarch *gdbarch = get_frame_arch (this_frame);
enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
CORE_ADDR pc = get_frame_pc (this_frame);
CORE_ADDR start_pc = (pc & ~(ppcfbsd_page_size - 1));
const int *offset;
const char *name;
/* A stack trampoline is detected if no name is associated
to the current pc and if it points inside a trampoline
sequence. */
find_pc_partial_function (pc, &name, NULL, NULL);
/* If we have a name, we have no trampoline, return. */
if (name)
return 0;
for (offset = ppcfbsd_sigreturn_offset; *offset != -1; offset++)
{
gdb_byte buf[2 * PPC_INSN_SIZE];
unsigned long insn;
if (!safe_frame_unwind_memory (this_frame, start_pc + *offset,
buf, sizeof buf))
continue;
/* Check for "li r0,SYS_sigreturn". */
insn = extract_unsigned_integer (buf, PPC_INSN_SIZE, byte_order);
if (insn != 0x380001a1)
continue;
/* Check for "sc". */
insn = extract_unsigned_integer (buf + PPC_INSN_SIZE,
PPC_INSN_SIZE, byte_order);
if (insn != 0x44000002)
continue;
return 1;
}
return 0;
}
static struct trad_frame_cache *
ppcfbsd_sigtramp_frame_cache (struct frame_info *this_frame, void **this_cache)
{
struct gdbarch *gdbarch = get_frame_arch (this_frame);
struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
struct trad_frame_cache *cache;
CORE_ADDR addr, base, func;
gdb_byte buf[PPC_INSN_SIZE];
int i;
if (*this_cache)
return (struct trad_frame_cache *) *this_cache;
cache = trad_frame_cache_zalloc (this_frame);
*this_cache = cache;
func = get_frame_pc (this_frame);
func &= ~(ppcfbsd_page_size - 1);
if (!safe_frame_unwind_memory (this_frame, func, buf, sizeof buf))
return cache;
base = get_frame_register_unsigned (this_frame, gdbarch_sp_regnum (gdbarch));
addr = base + 0x10 + 2 * tdep->wordsize;
for (i = 0; i < ppc_num_gprs; i++, addr += tdep->wordsize)
{
int regnum = i + tdep->ppc_gp0_regnum;
trad_frame_set_reg_addr (cache, regnum, addr);
}
trad_frame_set_reg_addr (cache, tdep->ppc_lr_regnum, addr);
addr += tdep->wordsize;
trad_frame_set_reg_addr (cache, tdep->ppc_cr_regnum, addr);
addr += tdep->wordsize;
trad_frame_set_reg_addr (cache, tdep->ppc_xer_regnum, addr);
addr += tdep->wordsize;
trad_frame_set_reg_addr (cache, tdep->ppc_ctr_regnum, addr);
addr += tdep->wordsize;
trad_frame_set_reg_addr (cache, gdbarch_pc_regnum (gdbarch), addr);
/* SRR0? */
addr += tdep->wordsize;
/* Construct the frame ID using the function start. */
trad_frame_set_id (cache, frame_id_build (base, func));
return cache;
}
static void
ppcfbsd_sigtramp_frame_this_id (struct frame_info *this_frame,
void **this_cache, struct frame_id *this_id)
{
struct trad_frame_cache *cache =
ppcfbsd_sigtramp_frame_cache (this_frame, this_cache);
trad_frame_get_id (cache, this_id);
}
static struct value *
ppcfbsd_sigtramp_frame_prev_register (struct frame_info *this_frame,
void **this_cache, int regnum)
{
struct trad_frame_cache *cache =
ppcfbsd_sigtramp_frame_cache (this_frame, this_cache);
return trad_frame_get_register (cache, this_frame, regnum);
}
static const struct frame_unwind ppcfbsd_sigtramp_frame_unwind = {
SIGTRAMP_FRAME,
default_frame_unwind_stop_reason,
ppcfbsd_sigtramp_frame_this_id,
ppcfbsd_sigtramp_frame_prev_register,
NULL,
ppcfbsd_sigtramp_frame_sniffer
};
static enum return_value_convention
ppcfbsd_return_value (struct gdbarch *gdbarch, struct value *function,
struct type *valtype, struct regcache *regcache,
gdb_byte *readbuf, const gdb_byte *writebuf)
{
return ppc_sysv_abi_broken_return_value (gdbarch, function, valtype,
regcache, readbuf, writebuf);
}
static void
ppcfbsd_init_abi (struct gdbarch_info info, struct gdbarch *gdbarch)
{
struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
/* Generic FreeBSD support. */
fbsd_init_abi (info, gdbarch);
/* FreeBSD doesn't support the 128-bit `long double' from the psABI. */
set_gdbarch_long_double_bit (gdbarch, 64);
set_gdbarch_long_double_format (gdbarch, floatformats_ieee_double);
if (tdep->wordsize == 4)
{
set_gdbarch_return_value (gdbarch, ppcfbsd_return_value);
set_gdbarch_skip_trampoline_code (gdbarch, find_solib_trampoline_target);
set_solib_svr4_fetch_link_map_offsets (gdbarch,
svr4_ilp32_fetch_link_map_offsets);
frame_unwind_append_unwinder (gdbarch, &ppcfbsd_sigtramp_frame_unwind);
set_gdbarch_gcore_bfd_target (gdbarch, "elf32-powerpc");
}
if (tdep->wordsize == 8)
{
set_gdbarch_convert_from_func_ptr_addr
(gdbarch, ppc64_convert_from_func_ptr_addr);
set_gdbarch_elf_make_msymbol_special (gdbarch,
ppc64_elf_make_msymbol_special);
set_gdbarch_skip_trampoline_code (gdbarch, ppc64_skip_trampoline_code);
set_solib_svr4_fetch_link_map_offsets (gdbarch,
svr4_lp64_fetch_link_map_offsets);
set_gdbarch_gcore_bfd_target (gdbarch, "elf64-powerpc");
}
set_gdbarch_iterate_over_regset_sections
(gdbarch, ppcfbsd_iterate_over_regset_sections);
set_gdbarch_fetch_tls_load_module_address (gdbarch,
svr4_fetch_objfile_link_map);
}
/* Provide a prototype to silence -Wmissing-prototypes. */
void _initialize_ppcfbsd_tdep (void);
void
_initialize_ppcfbsd_tdep (void)
{
gdbarch_register_osabi (bfd_arch_powerpc, bfd_mach_ppc, GDB_OSABI_FREEBSD,
ppcfbsd_init_abi);
gdbarch_register_osabi (bfd_arch_powerpc, bfd_mach_ppc64, GDB_OSABI_FREEBSD,
ppcfbsd_init_abi);
gdbarch_register_osabi (bfd_arch_rs6000, 0, GDB_OSABI_FREEBSD,
ppcfbsd_init_abi);
}
| totalspectrum/binutils-propeller | gdb/ppc-fbsd-tdep.c | C | gpl-2.0 | 9,858 | [
30522,
1013,
1008,
4539,
1011,
7790,
3642,
2005,
2373,
15042,
3001,
2770,
2489,
5910,
2094,
1012,
9385,
1006,
1039,
1007,
2286,
1011,
2418,
2489,
4007,
3192,
1010,
4297,
1012,
2023,
5371,
2003,
2112,
1997,
1043,
18939,
1012,
2023,
2565,
2... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Config\Definition\Builder;
use Symfony\Component\Config\Definition\ArrayNode;
use Symfony\Component\Config\Definition\PrototypedArrayNode;
use Symfony\Component\Config\Definition\Exception\InvalidDefinitionException;
/**
* This class provides a fluent interface for defining an array node.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class ArrayNodeDefinition extends NodeDefinition implements ParentNodeDefinitionInterface
{
protected $performDeepMerging = true;
protected $ignoreExtraKeys = false;
protected $children = array();
protected $prototype;
protected $atLeastOne = false;
protected $allowNewKeys = true;
protected $key;
protected $removeKeyItem;
protected $addDefaults = false;
protected $addDefaultChildren = false;
protected $nodeBuilder;
protected $normalizeKeys = true;
/**
* {@inheritdoc}
*/
public function __construct($name, NodeParentInterface $parent = null)
{
parent::__construct($name, $parent);
$this->nullEquivalent = array();
$this->trueEquivalent = array();
}
/**
* Sets a custom children builder.
*
* @param NodeBuilder $builder A custom NodeBuilder
*/
public function setBuilder(NodeBuilder $builder)
{
$this->nodeBuilder = $builder;
}
/**
* Returns a builder to add children nodes.
*
* @return NodeBuilder
*/
public function children()
{
return $this->getNodeBuilder();
}
/**
* Sets a prototype for child nodes.
*
* @param string $type the type of node
*
* @return NodeDefinition
*/
public function prototype($type)
{
return $this->prototype = $this->getNodeBuilder()->node(null, $type)->setParent($this);
}
/**
* Adds the default value if the node is not set in the configuration.
*
* This method is applicable to concrete nodes only (not to prototype nodes).
* If this function has been called and the node is not set during the finalization
* phase, it's default value will be derived from its children default values.
*
* @return $this
*/
public function addDefaultsIfNotSet()
{
$this->addDefaults = true;
return $this;
}
/**
* Adds children with a default value when none are defined.
*
* @param int|string|array|null $children The number of children|The child name|The children names to be added
*
* This method is applicable to prototype nodes only.
*
* @return $this
*/
public function addDefaultChildrenIfNoneSet($children = null)
{
$this->addDefaultChildren = $children;
return $this;
}
/**
* Requires the node to have at least one element.
*
* This method is applicable to prototype nodes only.
*
* @return $this
*/
public function requiresAtLeastOneElement()
{
$this->atLeastOne = true;
return $this;
}
/**
* Disallows adding news keys in a subsequent configuration.
*
* If used all keys have to be defined in the same configuration file.
*
* @return $this
*/
public function disallowNewKeysInSubsequentConfigs()
{
$this->allowNewKeys = false;
return $this;
}
/**
* Sets a normalization rule for XML configurations.
*
* @param string $singular The key to remap
* @param string $plural The plural of the key for irregular plurals
*
* @return $this
*/
public function fixXmlConfig($singular, $plural = null)
{
$this->normalization()->remap($singular, $plural);
return $this;
}
/**
* Sets the attribute which value is to be used as key.
*
* This is useful when you have an indexed array that should be an
* associative array. You can select an item from within the array
* to be the key of the particular item. For example, if "id" is the
* "key", then:
*
* array(
* array('id' => 'my_name', 'foo' => 'bar'),
* );
*
* becomes
*
* array(
* 'my_name' => array('foo' => 'bar'),
* );
*
* If you'd like "'id' => 'my_name'" to still be present in the resulting
* array, then you can set the second argument of this method to false.
*
* This method is applicable to prototype nodes only.
*
* @param string $name The name of the key
* @param bool $removeKeyItem Whether or not the key item should be removed
*
* @return $this
*/
public function useAttributeAsKey($name, $removeKeyItem = true)
{
$this->key = $name;
$this->removeKeyItem = $removeKeyItem;
return $this;
}
/**
* Sets whether the node can be unset.
*
* @param bool $allow
*
* @return $this
*/
public function canBeUnset($allow = true)
{
$this->merge()->allowUnset($allow);
return $this;
}
/**
* Adds an "enabled" boolean to enable the current section.
*
* By default, the section is disabled. If any configuration is specified then
* the node will be automatically enabled:
*
* enableableArrayNode: {enabled: true, ...} # The config is enabled & default values get overridden
* enableableArrayNode: ~ # The config is enabled & use the default values
* enableableArrayNode: true # The config is enabled & use the default values
* enableableArrayNode: {other: value, ...} # The config is enabled & default values get overridden
* enableableArrayNode: {enabled: false, ...} # The config is disabled
* enableableArrayNode: false # The config is disabled
*
* @return $this
*/
public function canBeEnabled()
{
$this
->addDefaultsIfNotSet()
->treatFalseLike(array('enabled' => false))
->treatTrueLike(array('enabled' => true))
->treatNullLike(array('enabled' => true))
->beforeNormalization()
->ifArray()
->then(function ($v) {
$v['enabled'] = isset($v['enabled']) ? $v['enabled'] : true;
return $v;
})
->end()
->children()
->booleanNode('enabled')
->defaultFalse()
;
return $this;
}
/**
* Adds an "enabled" boolean to enable the current section.
*
* By default, the section is enabled.
*
* @return $this
*/
public function canBeDisabled()
{
$this
->addDefaultsIfNotSet()
->treatFalseLike(array('enabled' => false))
->treatTrueLike(array('enabled' => true))
->treatNullLike(array('enabled' => true))
->children()
->booleanNode('enabled')
->defaultTrue()
;
return $this;
}
/**
* Disables the deep merging of the node.
*
* @return $this
*/
public function performNoDeepMerging()
{
$this->performDeepMerging = false;
return $this;
}
/**
* Allows extra config keys to be specified under an array without
* throwing an exception.
*
* Those config values are simply ignored and removed from the
* resulting array. This should be used only in special cases where
* you want to send an entire configuration array through a special
* tree that processes only part of the array.
*
* @return $this
*/
public function ignoreExtraKeys()
{
$this->ignoreExtraKeys = true;
return $this;
}
/**
* Sets key normalization.
*
* @param bool $bool Whether to enable key normalization
*
* @return $this
*/
public function normalizeKeys($bool)
{
$this->normalizeKeys = (bool) $bool;
return $this;
}
/**
* Appends a node definition.
*
* $node = new ArrayNodeDefinition()
* ->children()
* ->scalarNode('foo')->end()
* ->scalarNode('baz')->end()
* ->end()
* ->append($this->getBarNodeDefinition())
* ;
*
* @param NodeDefinition $node A NodeDefinition instance
*
* @return $this
*/
public function append(NodeDefinition $node)
{
$this->children[$node->name] = $node->setParent($this);
return $this;
}
/**
* Returns a node builder to be used to add children and prototype.
*
* @return NodeBuilder The node builder
*/
protected function getNodeBuilder()
{
if (null === $this->nodeBuilder) {
$this->nodeBuilder = new NodeBuilder();
}
return $this->nodeBuilder->setParent($this);
}
/**
* {@inheritdoc}
*/
protected function createNode()
{
if (null === $this->prototype) {
$node = new ArrayNode($this->name, $this->parent);
$this->validateConcreteNode($node);
$node->setAddIfNotSet($this->addDefaults);
foreach ($this->children as $child) {
$child->parent = $node;
$node->addChild($child->getNode());
}
} else {
$node = new PrototypedArrayNode($this->name, $this->parent);
$this->validatePrototypeNode($node);
if (null !== $this->key) {
$node->setKeyAttribute($this->key, $this->removeKeyItem);
}
if (true === $this->atLeastOne) {
$node->setMinNumberOfElements(1);
}
if ($this->default) {
$node->setDefaultValue($this->defaultValue);
}
if (false !== $this->addDefaultChildren) {
$node->setAddChildrenIfNoneSet($this->addDefaultChildren);
if ($this->prototype instanceof static && null === $this->prototype->prototype) {
$this->prototype->addDefaultsIfNotSet();
}
}
$this->prototype->parent = $node;
$node->setPrototype($this->prototype->getNode());
}
$node->setAllowNewKeys($this->allowNewKeys);
$node->addEquivalentValue(null, $this->nullEquivalent);
$node->addEquivalentValue(true, $this->trueEquivalent);
$node->addEquivalentValue(false, $this->falseEquivalent);
$node->setPerformDeepMerging($this->performDeepMerging);
$node->setRequired($this->required);
$node->setIgnoreExtraKeys($this->ignoreExtraKeys);
$node->setNormalizeKeys($this->normalizeKeys);
if (null !== $this->normalization) {
$node->setNormalizationClosures($this->normalization->before);
$node->setXmlRemappings($this->normalization->remappings);
}
if (null !== $this->merge) {
$node->setAllowOverwrite($this->merge->allowOverwrite);
$node->setAllowFalse($this->merge->allowFalse);
}
if (null !== $this->validation) {
$node->setFinalValidationClosures($this->validation->rules);
}
return $node;
}
/**
* Validate the configuration of a concrete node.
*
* @param ArrayNode $node The related node
*
* @throws InvalidDefinitionException
*/
protected function validateConcreteNode(ArrayNode $node)
{
$path = $node->getPath();
if (null !== $this->key) {
throw new InvalidDefinitionException(
sprintf('->useAttributeAsKey() is not applicable to concrete nodes at path "%s"', $path)
);
}
if (true === $this->atLeastOne) {
throw new InvalidDefinitionException(
sprintf('->requiresAtLeastOneElement() is not applicable to concrete nodes at path "%s"', $path)
);
}
if ($this->default) {
throw new InvalidDefinitionException(
sprintf('->defaultValue() is not applicable to concrete nodes at path "%s"', $path)
);
}
if (false !== $this->addDefaultChildren) {
throw new InvalidDefinitionException(
sprintf('->addDefaultChildrenIfNoneSet() is not applicable to concrete nodes at path "%s"', $path)
);
}
}
/**
* Validate the configuration of a prototype node.
*
* @param PrototypedArrayNode $node The related node
*
* @throws InvalidDefinitionException
*/
protected function validatePrototypeNode(PrototypedArrayNode $node)
{
$path = $node->getPath();
if ($this->addDefaults) {
throw new InvalidDefinitionException(
sprintf('->addDefaultsIfNotSet() is not applicable to prototype nodes at path "%s"', $path)
);
}
if (false !== $this->addDefaultChildren) {
if ($this->default) {
throw new InvalidDefinitionException(
sprintf('A default value and default children might not be used together at path "%s"', $path)
);
}
if (null !== $this->key && (null === $this->addDefaultChildren || is_int($this->addDefaultChildren) && $this->addDefaultChildren > 0)) {
throw new InvalidDefinitionException(
sprintf('->addDefaultChildrenIfNoneSet() should set default children names as ->useAttributeAsKey() is used at path "%s"', $path)
);
}
if (null === $this->key && (is_string($this->addDefaultChildren) || is_array($this->addDefaultChildren))) {
throw new InvalidDefinitionException(
sprintf('->addDefaultChildrenIfNoneSet() might not set default children names as ->useAttributeAsKey() is not used at path "%s"', $path)
);
}
}
}
}
| JannethB/SistemaInventario | vendor/symfony/symfony/src/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php | PHP | mit | 14,417 | [
30522,
1026,
1029,
25718,
1013,
1008,
1008,
2023,
5371,
2003,
2112,
1997,
1996,
25353,
2213,
14876,
4890,
7427,
1012,
1008,
1008,
1006,
1039,
1007,
6904,
11283,
2078,
8962,
2368,
19562,
1026,
6904,
11283,
2078,
1030,
25353,
2213,
14876,
489... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
class RenameActivityTypeIdByHand < ActiveRecord::Migration
def change
change_table :user_activities do |t|
t.rename :activity_type_id, :user_activity_type_id
end
end
end
| emadb/scrooge | db/migrate/20121220232116_rename_activity_type_id_by_hand.rb | Ruby | mit | 187 | [
30522,
2465,
14916,
14074,
18908,
7730,
13874,
3593,
3762,
11774,
1026,
3161,
2890,
27108,
2094,
1024,
1024,
9230,
13366,
2689,
2689,
1035,
2795,
1024,
5310,
1035,
3450,
2079,
1064,
1056,
1064,
1056,
1012,
14916,
14074,
1024,
4023,
1035,
28... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*------------------------------------------------------------------
* test_strremovews_s
*
*
*------------------------------------------------------------------
*/
#include "test_private.h"
#include "safe_str_lib.h"
#define LEN ( 128 )
int main()
{
errno_t rc;
int ind;
uint32_t len;
char str[LEN];
/*--------------------------------------------------*/
len = 5;
rc = strremovews_s(NULL, len);
if (rc != ESNULLP) {
printf("%s %u Error rc=%u \n",
__FUNCTION__, __LINE__, rc );
}
/*--------------------------------------------------*/
len = 0;
rc = strremovews_s("test", len);
if (rc != ESZEROL) {
printf("%s %u Error rc=%u \n",
__FUNCTION__, __LINE__, rc );
}
/*--------------------------------------------------*/
len = 99999;
rc = strremovews_s("test", len);
if (rc != ESLEMAX) {
printf("%s %u Error rc=%u \n",
__FUNCTION__, __LINE__, rc );
}
/*--------------------------------------------------*/
strzero_s(str, LEN);
strcpy (str, "ABCDEFGHIJK");
len = 1;
rc = strremovews_s(str, len);
if (rc != EOK) {
printf("%s %u Error rc=%u \n",
__FUNCTION__, __LINE__, rc );
}
if (str[0] != '\0') {
printf("%s %u Error -%s- \n",
__FUNCTION__, __LINE__, str);
}
/*--------------------------------------------------*/
strzero_s(str, LEN);
strcpy (str, "ABCDEFGHIJK");
len = 2;
rc = strremovews_s(str, len);
if (rc != ESUNTERM) {
printf("%s %u Error rc=%u --%s--\n",
__FUNCTION__, __LINE__, rc, str );
}
/*--------------------------------------------------*/
strzero_s(str, LEN);
strcpy (str, " ABCDEFGHIJK");
len = 3;
rc = strremovews_s(str, len);
if (rc != ESUNTERM) {
printf("%s %u Error rc=%u --%s--\n",
__FUNCTION__, __LINE__, rc, str );
}
if (str[0] != '\0') {
printf("%s %u Error rc=%u --%s--\n",
__FUNCTION__, __LINE__, rc, str );
}
/*--------------------------------------------------*/
strzero_s(str, LEN);
strcpy (str, " ABCDEFGHIJK");
len = 9;
rc = strremovews_s(str, len);
if (rc != ESUNTERM) {
printf("%s %u Error rc=%u --%s--\n",
__FUNCTION__, __LINE__, rc, str );
}
/*--------------------------------------------------*/
strzero_s(str, LEN);
strcpy (str, "A");
len = 1;
/* a one char string will be emptied - str[0]=='\0' */
rc = strremovews_s(str, len);
if (rc != EOK) {
printf("%s %u Error rc=%u \n",
__FUNCTION__, __LINE__, rc );
}
if (str[0] != '\0') {
printf("%s %u Error -%s- \n",
__FUNCTION__, __LINE__, str);
}
/*--------------------------------------------------*/
strzero_s(str, LEN);
strcpy (str, "ABC");
len = 8;
rc = strremovews_s(str, len);
if (rc != EOK) {
printf("%s %u Error rc=%u \n",
__FUNCTION__, __LINE__, rc );
}
if (str[0] != 'A') {
printf("%s %u Error -%s- \n",
__FUNCTION__, __LINE__, str);
}
/*--------------------------------------------------*/
strzero_s(str, LEN);
strcpy(str, " B");
len = strlen(str);
rc = strremovews_s(str, len);
if (rc != EOK) {
printf("%s %u Error rc=%u \n",
__FUNCTION__, __LINE__, rc );
}
if (str[0] != 'B') {
printf("%s %u Error -%s- \n",
__FUNCTION__, __LINE__, str);
}
/*--------------------------------------------------*/
strzero_s(str, LEN);
strcpy(str, " C ");
len = strlen(str);
rc = strremovews_s(str, len);
if (rc != EOK) {
printf("%s %u Error rc=%u \n",
__FUNCTION__, __LINE__, rc );
}
ind = strcmp(str, "C");
if (ind != 0) {
printf("%s %u Error -%s- \n",
__FUNCTION__, __LINE__, str);
}
/*--------------------------------------------------*/
strzero_s(str, LEN);
strcpy(str, " NowISTHETimE 1 2 ");
len = strlen(str);
rc = strremovews_s(str, len);
if (rc != EOK) {
printf("%s %u Error rc=%u \n",
__FUNCTION__, __LINE__, rc );
}
ind = strcmp(str, "NowISTHETimE 1 2");
if (ind != 0) {
printf("%s %u Error -%s- \n",
__FUNCTION__, __LINE__, str);
}
/*--------------------------------------------------*/
strzero_s(str, LEN);
strcpy (str, " q q21ego");
len = strlen(str);
rc = strremovews_s(str, len);
if (rc != EOK) {
printf("%s %u Error rc=%u \n",
__FUNCTION__, __LINE__, rc );
}
ind = strcmp(str, "q q21ego");
if (ind != 0) {
printf("%s %u Error -%s- \n",
__FUNCTION__, __LINE__, str);
}
/*--------------------------------------------------*/
strzero_s(str, LEN);
strcpy (str, " 1 2 3 4 ");
len = strlen(str);
rc = strremovews_s(str, len);
if (rc != EOK) {
printf("%s %u Error rc=%u \n",
__FUNCTION__, __LINE__, rc );
}
ind = strcmp(str, "1 2 3 4");
if (ind != 0) {
printf("%s %u Error -%s- \n",
__FUNCTION__, __LINE__, str);
}
/*--------------------------------------------------*/
return (0);
}
| coruus/safeclib | tests/test_strremovews_s.c | C | mit | 5,614 | [
30522,
1013,
1008,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
101... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
import"./chunk-1fafdf15.js";import"./helpers.js";import"./chunk-953eb524.js";import{r as registerComponent,u as use}from"./chunk-cca88db8.js";import{T as Tooltip}from"./chunk-f6e15a82.js";export{T as BTooltip}from"./chunk-f6e15a82.js";var Plugin={install:function(o){registerComponent(o,Tooltip)}};use(Plugin);export default Plugin; | cdnjs/cdnjs | ajax/libs/buefy/0.9.7/esm/tooltip.min.js | JavaScript | mit | 332 | [
30522,
12324,
1000,
1012,
1013,
20000,
1011,
1015,
7011,
2546,
20952,
16068,
1012,
1046,
2015,
1000,
1025,
12324,
1000,
1012,
1013,
2393,
2545,
1012,
1046,
2015,
1000,
1025,
12324,
1000,
1012,
1013,
20000,
1011,
5345,
2509,
15878,
25746,
25... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language;?>" >
<?php
/* @package mx_joomla121 Template
* @author mixwebtemplates http://www.mixwebtemplates.com
* @copyright Copyright (c) 2006 - 2012 mixwebtemplates. All rights reserved
*/
defined( '_JEXEC' ) or die( 'Restricted access' );
if(!defined('DS')){define('DS',DIRECTORY_SEPARATOR);}
$tcParams = '';
include_once(dirname(__FILE__).DS.'tclibs'.DS.'head.php');
include_once(dirname(__FILE__).DS.'tclibs'.DS.'settings.php');
$tcParams .= '<body id="tc">';
$tcParams .= TCShowModule('adverts', 'mx_xhtml', 'container');
$tcParams .= '<div id="mx_wrapper" class="mx_wrapper">';
$tcParams .= TCShowModule('header', 'mx_xhtml', 'container');
$tcParams .= '<jdoc:include type="modules" name="sign_in" />';
include_once(dirname(__FILE__).DS.'tclibs'.DS.'slider.php');
include_once(dirname(__FILE__).DS.'tclibs'.DS.'social.php');
$tcParams .= TCShowModule('slider', 'mx_xhtml', 'container');
$tcParams .= TCShowModule('top', 'mx_xhtml', 'container');
$tcParams .= TCShowModule('info', 'mx_xhtml', 'container');
$tcParams .= '<section class="mx_wrapper_info mx_section">'
.'<div class="container mx_group"><jdoc:include type="modules" name="search_jobs_box" />'
// .'<div><jdoc:include type="modules" name="test1" /></div>'
.'</div></section>';
//Latest Jobs blocks
$tcParams .= '<div class="row"><jdoc:include type="modules" name="latest_jobs" /></div>'
;
//Slide top
$tcParams .= '<section class="mx_wrapper_top mx_section">'
.'<div class="container mx_group">'
.'<jdoc:include type="modules" name="top_slide" />'
.'</div></section>';
//very maintop content block
$tcParams .= '<section class="mx_wrapper_maintop mx_section">'
.'<div class="container mx_group">'
.'<jdoc:include type="modules" name="top_block" />'
.'</div></section>';
$tcParams .= TCShowModule('maintop', 'mx_xhtml', 'container');
$tcParams .= '<main class="mx_main container clearfix">'.$component.'</main>';
$tcParams .= TCShowModule('mainbottom', 'mx_xhtml', 'container').
TCShowModule('feature', 'mx_xhtml', 'container').
TCShowModule('bottom', 'mx_xhtml', 'container').
TCShowModule('footer', 'mx_xhtml', 'container');
//Advise widget
$tcParams .= '<div class="row">'
.'<jdoc:include type="modules" name="advise-widget" />'
.'</div>';
//Resume nav bar
$tcParams .= '<div class="mod-content clearfix">'
.'<jdoc:include type="modules" name="Create_ResumeNavBar" />'
.'</div>';
//Feature blocks
$tcParams .= '<section class="mx_wrapper_feature mx_section">'
.'<div class="container mx_group">'
.'<jdoc:include type="modules" name="feature-1" />'
.'</div></section>';
//Footer blocks
$tcParams .= '<section class="mx_wrapper_bottom mx_section">'
.'<div class="container mx_group">'
.'<jdoc:include type="modules" name="footer_block" />'
.'</div></section>';
$tcParams .= '<footer class="mx_wrapper_copyright mx_section">'.
'<div class="container clearfix">'.
'<div class="col-md-12">'.($copyright ? '<div style="padding:10px;">'.$cpright.' </div>' : ''). /* You CAN NOT remove (or unreadable) this without mixwebtemplates.com permission */ //'<div style="padding-bottom:10px; text-align:right; ">Designed by <a href="http://www.mixwebtemplates.com/" title="Visit mixwebtemplates.com!" target="blank">mixwebtemplates.com</a></div>'.
'</div>'.
'</div>'.
'</footer>';
$tcParams .='</div>';
include_once(dirname(__FILE__).DS.'tclibs'.DS.'debug.php');
$tcParams .='</body>';
$tcParams .='</html>';
echo $tcParams;
?> | sondang86/hasico | templates/temp_template/index.php | PHP | gpl-2.0 | 3,934 | [
30522,
1026,
999,
9986,
13874,
16129,
2270,
1000,
1011,
1013,
1013,
1059,
2509,
2278,
1013,
1013,
26718,
2094,
1060,
11039,
19968,
1015,
1012,
1014,
17459,
1013,
1013,
4372,
1000,
1000,
8299,
1024,
1013,
1013,
7479,
1012,
1059,
2509,
1012,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
import atexit
from flask import Flask, jsonify, g, request, make_response
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from flask_jwt_extended import JWTManager, set_access_cookies, jwt_required, unset_jwt_cookies
from apscheduler.schedulers.background import BackgroundScheduler
import logging
logging.basicConfig()
app = Flask(__name__)
app.config.from_pyfile('./config/config.py')
db = SQLAlchemy(app)
CORS(app, supports_credentials=True)
migrate = Migrate(app, db)
jwt = JWTManager(app)
from tasks.next_reservation_check import check_all_users
from DB.User import User
from endpoints import reservation, user
scheduler = BackgroundScheduler(daemon=True)
scheduler.add_job(check_all_users,'interval', hours=4)
scheduler.start()
# Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())
@app.route('/')
def index():
return "Hello, this is an API, Swagger documentation will follow here..."
@app.route('/token')
def get_auth_token():
if not request.authorization:
response = make_response(jsonify({'error':'Login required'}))
response.headers.set('WWW-Authenticate', 'Basic realm="patklaey.ch"')
return response, 401
if not verify_password(request.authorization.username, request.authorization.password):
response = jsonify({'error':'Invalid username or password'})
return response, 401
token = g.user.generate_auth_token()
response = jsonify({'token': token})
set_access_cookies(response, token)
return response, 200
def verify_password(username, password):
user = User.query.filter_by(username=username, active=True).first()
if not user or not user.verify_password(password):
return False
g.user = user
return True
@app.route('/logout', methods=['POST'])
def logout():
resp = jsonify({'logout': True})
unset_jwt_cookies(resp)
return resp, 200
| patklaey/ZermattReservationAPI | main.py | Python | mit | 1,957 | [
30522,
12324,
8823,
9048,
2102,
2013,
13109,
19895,
12324,
13109,
19895,
1010,
1046,
3385,
8757,
1010,
1043,
1010,
5227,
1010,
2191,
1035,
3433,
2013,
13109,
19895,
1035,
22806,
12324,
22806,
2013,
13109,
19895,
1035,
29296,
2389,
5403,
8029,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
require 'bandcamp/band'
require 'bandcamp/album'
require 'bandcamp/track'
require 'bandcamp/request'
module Bandcamp
class Getter
def initialize request
@request = request
end
def track track_id
response = @request.track track_id
response.nil? ? nil : Track.new(response)
end
def tracks *tracks
track_list = tracks.join(',')
response = @request.track track_list
if response.nil?
[]
else
response.collect{|key,val| Track.new val}
end
end
def album album_id
response = @request.album album_id
response.nil? ? nil : Album.new(response)
end
def search band_name
response = @request.search band_name
if response.nil?
[]
else
response.collect{|band_json| Band.new band_json}
end
end
def band name
response = @request.band name
response.nil? ? nil : Band.new(response)
end
def url address
response = @request.url address
return nil if response.nil?
case
when response.has_key?("album_id")
album(response["album_id"])
when response.has_key?("track_id")
track(response["track_id"])
when (response.keys.length == 1) && response.has_key?("band_id")
band(response["band_id"])
end
end
end
end
| sleepycat/bandcamp_api | lib/bandcamp/getter.rb | Ruby | mit | 1,343 | [
30522,
5478,
1005,
2316,
26468,
1013,
2316,
1005,
5478,
1005,
2316,
26468,
1013,
2201,
1005,
5478,
1005,
2316,
26468,
1013,
2650,
1005,
5478,
1005,
2316,
26468,
1013,
5227,
1005,
11336,
2316,
26468,
2465,
2131,
3334,
13366,
3988,
4697,
5227... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<html>
<head>
<script src="../../fast/js/resources/js-test-pre.js"></script>
<script src="resources/shared.js"></script>
</head>
<body>
<script src="resources/index-unique.js"></script>
<script src="../../fast/js/resources/js-test-post.js"></script>
</body>
</html>
| leighpauls/k2cro4 | content/test/data/layout_tests/LayoutTests/storage/indexeddb/index-unique.html | HTML | bsd-3-clause | 266 | [
30522,
1026,
16129,
1028,
1026,
2132,
1028,
1026,
5896,
5034,
2278,
1027,
1000,
1012,
1012,
1013,
1012,
1012,
1013,
3435,
1013,
1046,
2015,
1013,
4219,
1013,
1046,
2015,
1011,
3231,
1011,
3653,
1012,
1046,
2015,
1000,
1028,
1026,
1013,
58... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.