text
stringlengths 2
1.04M
| meta
dict |
---|---|
#ifndef QMITKDATAMANAGERPREFERENCEPAGE_H_
#define QMITKDATAMANAGERPREFERENCEPAGE_H_
#include "berryIQtPreferencePage.h"
#include <org_mitk_gui_qt_datamanager_Export.h>
#include <berryIPreferences.h>
class QWidget;
class QCheckBox;
struct MITK_QT_DATAMANAGER QmitkDataManagerPreferencePage : public QObject, public berry::IQtPreferencePage
{
Q_OBJECT
Q_INTERFACES(berry::IPreferencePage)
public:
QmitkDataManagerPreferencePage();
void Init(berry::IWorkbench::Pointer workbench) override;
void CreateQtControl(QWidget* widget) override;
QWidget* GetQtControl() const override;
///
/// \see IPreferencePage::PerformOk()
///
virtual bool PerformOk() override;
///
/// \see IPreferencePage::PerformCancel()
///
virtual void PerformCancel() override;
///
/// \see IPreferencePage::Update()
///
virtual void Update() override;
protected:
QWidget* m_MainControl;
QCheckBox* m_EnableSingleEditing;
QCheckBox* m_PlaceNewNodesOnTop;
QCheckBox* m_ShowHelperObjects;
QCheckBox* m_ShowNodesContainingNoData;
QCheckBox* m_GlobalReinitOnNodeDelete;
QCheckBox* m_GlobalReinitOnNodeAdded;
QCheckBox* m_UseSurfaceDecimation;
QCheckBox* m_AllowParentChange;
berry::IPreferences::Pointer m_DataManagerPreferencesNode;
};
#endif /* QMITKDATAMANAGERPREFERENCEPAGE_H_ */
| {
"content_hash": "3f845cc24af43239d290c693585945d2",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 107,
"avg_line_length": 23.535714285714285,
"alnum_prop": 0.7617602427921093,
"repo_name": "RabadanLab/MITKats",
"id": "b45b5b77aea2d65b9b503860e455edb10ca3f62c",
"size": "1816",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerPreferencePage.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "3346369"
},
{
"name": "C++",
"bytes": "31343449"
},
{
"name": "CMake",
"bytes": "1009499"
},
{
"name": "CSS",
"bytes": "118558"
},
{
"name": "HTML",
"bytes": "102168"
},
{
"name": "JavaScript",
"bytes": "162600"
},
{
"name": "Jupyter Notebook",
"bytes": "228462"
},
{
"name": "Makefile",
"bytes": "25077"
},
{
"name": "Objective-C",
"bytes": "26578"
},
{
"name": "Python",
"bytes": "275885"
},
{
"name": "QML",
"bytes": "28009"
},
{
"name": "QMake",
"bytes": "5583"
},
{
"name": "Shell",
"bytes": "1261"
}
],
"symlink_target": ""
} |
<footer class="postmetadata">
<!--
Posted by <span class="byline author vcard"><span class="fn"><?php the_author() ?></span></span> in <?php the_category(', ') ?>
-->
<?php comments_popup_link('No Comments', '1 Comment', '% Comments', 'comments-link', ''); ?>.
<?php the_tags('Tags: ', ', ', '<br />'); ?>
</footer> | {
"content_hash": "7710f68ed6a890565d8035b92689cefd",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 128,
"avg_line_length": 41.5,
"alnum_prop": 0.5662650602409639,
"repo_name": "dharmatech/BrightstarDB",
"id": "08636c1e0b310d2c5fdb2f5bb933abf539714bc9",
"size": "332",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "website/site/blog/wp-content/themes/brightstar/_/inc/meta.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "23323"
},
{
"name": "C#",
"bytes": "6108330"
},
{
"name": "CSS",
"bytes": "87510"
},
{
"name": "JavaScript",
"bytes": "783"
},
{
"name": "Makefile",
"bytes": "6786"
},
{
"name": "PHP",
"bytes": "48867"
},
{
"name": "Python",
"bytes": "9712"
},
{
"name": "Ruby",
"bytes": "52759"
},
{
"name": "Shell",
"bytes": "9073"
},
{
"name": "Smalltalk",
"bytes": "168153"
},
{
"name": "XSLT",
"bytes": "1351"
}
],
"symlink_target": ""
} |
package com.versionone.om;
import com.versionone.DB.DateTime;
import com.versionone.om.filters.BuildRunFilter;
import java.util.Collection;
import java.util.Map;
/**
* Represents a Build Project in the VersionOne System.
*/
@MetaDataAttribute("BuildProject")
public class BuildProject extends BaseAsset {
/**
* Constructor used to represent an BuildProject entity that DOES exist in
* the VersionOne System.
*
* @param id Unique ID of this entity.
* @param instance this entity belongs to.
*/
BuildProject(AssetID id, V1Instance instance) {
super(id, instance);
}
/**
* Constructor used to represent an BuildProject entity that does NOT yet
* exist in the VersionOne System.
*
* @param instance this entity belongs to.
*/
BuildProject(V1Instance instance) {
super(instance);
}
/**
* @return Reference of this Build Project.
*/
public String getReference() {
return (String) get("Reference");
}
/**
* @param value Reference of this Build Project.
*/
public void setReference(String value) {
set("Reference", value);
}
/**
* @param filter limit the build runs returned; (If null, then all items
* returned).
* @return A collection of Build Runs associated with this Build Project.
*/
public Collection<BuildRun> getBuildRuns(BuildRunFilter filter) {
filter = (filter == null) ? new BuildRunFilter() : filter;
filter.buildProjects.clear();
filter.buildProjects.add(this);
return getInstance().get().buildRuns(filter);
}
/**
* Create a Build Run with the given name and date in this Build Project.
*
* @param name of creating BuildRun.
* @param date of creating BuildRun.
* @return A new Build Run in this Build Project.
*/
public BuildRun createBuildRun(String name, DateTime date) {
return getInstance().create().buildRun(this, name, date);
}
/**
* Create a Build Run with the given name and date in this Build Project.
*
* @param name of creating BuildRun.
* @param date of creating BuildRun.
* @param attributes additional attributes for the BuildRun.
* @return A new Build Run in this Build Project.
*/
public BuildRun createBuildRun(String name, DateTime date, Map<String, Object> attributes) {
return getInstance().create().buildRun(this, name, date, attributes);
}
@Override
void closeImpl() throws UnsupportedOperationException {
getInstance().executeOperation(BuildProject.class, this, "Inactivate");
}
@Override
void reactivateImpl() throws UnsupportedOperationException {
getInstance().executeOperation(BuildProject.class, this, "Reactivate");
}
}
| {
"content_hash": "f42e8396d85d463c06f60c526e657d90",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 96,
"avg_line_length": 30,
"alnum_prop": 0.6536842105263158,
"repo_name": "versionone/VersionOne.SDK.Java.ObjectModel",
"id": "4c601a272bc2cea49731e2659d73759a302943b3",
"size": "2915",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/com/versionone/om/BuildProject.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "1132916"
},
{
"name": "Shell",
"bytes": "1267"
},
{
"name": "XSLT",
"bytes": "291"
}
],
"symlink_target": ""
} |
package ficha1_SV_13_14;
/**
* Created by Ruben Gomes on 25/06/2015.
*/
public interface ReflectIterable <T> extends Iterable<T> {
ReflectIterable<T> filter (String fieldName,Object expected);
}
| {
"content_hash": "73e1c0189dd1ec3279832ea8001dbb16",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 65,
"avg_line_length": 25.25,
"alnum_prop": 0.7227722772277227,
"repo_name": "RubenGomes10/MPD-Modeling-and-design-patterns",
"id": "1dada9e06040ce8fffd49e01c7289d460cb483c4",
"size": "202",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Test_Resolutions/src/main/java/ficha1_SV_13_14/ReflectIterable.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "43463"
}
],
"symlink_target": ""
} |
package org.apache.hadoop.hdfs.server.blockmanagement;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockManagerSafeMode.BMSafeModeStatus;
import org.apache.hadoop.hdfs.server.namenode.FSNamesystem;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.hdfs.server.protocol.DatanodeStorage;
import org.apache.hadoop.hdfs.server.protocol.StorageReport;
import org.apache.hadoop.util.Daemon;
import org.junit.Assert;
import com.google.common.base.Preconditions;
import org.mockito.internal.util.reflection.Whitebox;
public class BlockManagerTestUtil {
public static void setNodeReplicationLimit(final BlockManager blockManager,
final int limit) {
blockManager.maxReplicationStreams = limit;
}
/** @return the datanode descriptor for the given the given storageID. */
public static DatanodeDescriptor getDatanode(final FSNamesystem ns,
final String storageID) {
ns.readLock();
try {
return ns.getBlockManager().getDatanodeManager().getDatanode(storageID);
} finally {
ns.readUnlock();
}
}
public static Iterator<BlockInfo> getBlockIterator(final FSNamesystem ns,
final String storageID, final int startBlock) {
ns.readLock();
try {
DatanodeDescriptor dn =
ns.getBlockManager().getDatanodeManager().getDatanode(storageID);
return dn.getBlockIterator(startBlock);
} finally {
ns.readUnlock();
}
}
public static Iterator<BlockInfo> getBlockIterator(DatanodeStorageInfo s) {
return s.getBlockIterator();
}
/**
* Refresh block queue counts on the name-node.
*/
public static void updateState(final BlockManager blockManager) {
blockManager.updateState();
}
/**
* @return a tuple of the replica state (number racks, number live
* replicas, and number needed replicas) for the given block.
*/
public static int[] getReplicaInfo(final FSNamesystem namesystem, final Block b) {
final BlockManager bm = namesystem.getBlockManager();
namesystem.readLock();
try {
final BlockInfo storedBlock = bm.getStoredBlock(b);
return new int[]{getNumberOfRacks(bm, b),
bm.countNodes(storedBlock).liveReplicas(),
bm.neededReconstruction.contains(storedBlock) ? 1 : 0};
} finally {
namesystem.readUnlock();
}
}
/**
* @return the number of racks over which a given block is replicated
* decommissioning/decommissioned nodes are not counted. corrupt replicas
* are also ignored
*/
private static int getNumberOfRacks(final BlockManager blockManager,
final Block b) {
final Set<String> rackSet = new HashSet<String>(0);
final Collection<DatanodeDescriptor> corruptNodes =
getCorruptReplicas(blockManager).getNodes(b);
for(DatanodeStorageInfo storage : blockManager.blocksMap.getStorages(b)) {
final DatanodeDescriptor cur = storage.getDatanodeDescriptor();
if (!cur.isDecommissionInProgress() && !cur.isDecommissioned()) {
if ((corruptNodes == null ) || !corruptNodes.contains(cur)) {
String rackName = cur.getNetworkLocation();
if (!rackSet.contains(rackName)) {
rackSet.add(rackName);
}
}
}
}
return rackSet.size();
}
/**
* @return redundancy monitor thread instance from block manager.
*/
public static Daemon getRedundancyThread(final BlockManager blockManager) {
return blockManager.getRedundancyThread();
}
/**
* Stop the redundancy monitor thread.
*/
public static void stopRedundancyThread(final BlockManager blockManager)
throws IOException {
blockManager.enableRMTerminationForTesting();
blockManager.getRedundancyThread().interrupt();
try {
blockManager.getRedundancyThread().join();
} catch (InterruptedException ie) {
throw new IOException(
"Interrupted while trying to stop RedundancyMonitor");
}
}
public static HeartbeatManager getHeartbeatManager(
final BlockManager blockManager) {
return blockManager.getDatanodeManager().getHeartbeatManager();
}
/**
* @return corruptReplicas from block manager
*/
public static CorruptReplicasMap getCorruptReplicas(final BlockManager blockManager){
return blockManager.corruptReplicas;
}
/**
* @return computed block replication and block invalidation work that can be
* scheduled on data-nodes.
* @throws IOException
*/
public static int getComputedDatanodeWork(final BlockManager blockManager) throws IOException
{
return blockManager.computeDatanodeWork();
}
public static int computeInvalidationWork(BlockManager bm) {
return bm.computeInvalidateWork(Integer.MAX_VALUE);
}
/**
* Compute all the replication and invalidation work for the
* given BlockManager.
*
* This differs from the above functions in that it computes
* replication work for all DNs rather than a particular subset,
* regardless of invalidation/replication limit configurations.
*
* NB: you may want to set
* {@link DFSConfigKeys#DFS_NAMENODE_REPLICATION_MAX_STREAMS_KEY} to
* a high value to ensure that all work is calculated.
*/
public static int computeAllPendingWork(BlockManager bm) {
int work = computeInvalidationWork(bm);
work += bm.computeBlockReconstructionWork(Integer.MAX_VALUE);
return work;
}
/**
* Ensure that the given NameNode marks the specified DataNode as
* entirely dead/expired.
* @param nn the NameNode to manipulate
* @param dnName the name of the DataNode
*/
public static void noticeDeadDatanode(NameNode nn, String dnName) {
FSNamesystem namesystem = nn.getNamesystem();
namesystem.writeLock();
try {
DatanodeManager dnm = namesystem.getBlockManager().getDatanodeManager();
HeartbeatManager hbm = dnm.getHeartbeatManager();
DatanodeDescriptor[] dnds = hbm.getDatanodes();
DatanodeDescriptor theDND = null;
for (DatanodeDescriptor dnd : dnds) {
if (dnd.getXferAddr().equals(dnName)) {
theDND = dnd;
}
}
Assert.assertNotNull("Could not find DN with name: " + dnName, theDND);
synchronized (hbm) {
DFSTestUtil.setDatanodeDead(theDND);
hbm.heartbeatCheck();
}
} finally {
namesystem.writeUnlock();
}
}
/**
* Change whether the block placement policy will prefer the writer's
* local Datanode or not.
* @param prefer if true, prefer local node
*/
public static void setWritingPrefersLocalNode(
BlockManager bm, boolean prefer) {
BlockPlacementPolicy bpp = bm.getBlockPlacementPolicy();
Preconditions.checkState(bpp instanceof BlockPlacementPolicyDefault,
"Must use default policy, got %s", bpp.getClass());
((BlockPlacementPolicyDefault)bpp).setPreferLocalNode(prefer);
}
/**
* Call heartbeat check function of HeartbeatManager
* @param bm the BlockManager to manipulate
*/
public static void checkHeartbeat(BlockManager bm) {
HeartbeatManager hbm = bm.getDatanodeManager().getHeartbeatManager();
hbm.restartHeartbeatStopWatch();
hbm.heartbeatCheck();
}
/**
* Call heartbeat check function of HeartbeatManager and get
* under replicated blocks count within write lock to make sure
* computeDatanodeWork doesn't interfere.
* @param namesystem the FSNamesystem
* @param bm the BlockManager to manipulate
* @return the number of under replicated blocks
*/
public static int checkHeartbeatAndGetUnderReplicatedBlocksCount(
FSNamesystem namesystem, BlockManager bm) {
namesystem.writeLock();
try {
bm.getDatanodeManager().getHeartbeatManager().heartbeatCheck();
return bm.getUnderReplicatedNotMissingBlocks();
} finally {
namesystem.writeUnlock();
}
}
public static DatanodeStorageInfo updateStorage(DatanodeDescriptor dn,
DatanodeStorage s) {
return dn.updateStorage(s);
}
/**
* Call heartbeat check function of HeartbeatManager
* @param bm the BlockManager to manipulate
*/
public static void rescanPostponedMisreplicatedBlocks(BlockManager bm) {
bm.rescanPostponedMisreplicatedBlocks();
}
public static DatanodeDescriptor getLocalDatanodeDescriptor(
boolean initializeStorage) {
DatanodeDescriptor dn = new DatanodeDescriptor(DFSTestUtil.getLocalDatanodeID());
if (initializeStorage) {
dn.updateStorage(new DatanodeStorage(DatanodeStorage.generateUuid()));
}
return dn;
}
public static DatanodeDescriptor getDatanodeDescriptor(String ipAddr,
String rackLocation, boolean initializeStorage) {
return getDatanodeDescriptor(ipAddr, rackLocation,
initializeStorage? new DatanodeStorage(DatanodeStorage.generateUuid()): null);
}
public static DatanodeDescriptor getDatanodeDescriptor(String ipAddr,
String rackLocation, DatanodeStorage storage) {
return getDatanodeDescriptor(ipAddr, rackLocation, storage, "host");
}
public static DatanodeDescriptor getDatanodeDescriptor(String ipAddr,
String rackLocation, DatanodeStorage storage, String hostname) {
DatanodeDescriptor dn = DFSTestUtil.getDatanodeDescriptor(ipAddr,
DFSConfigKeys.DFS_DATANODE_DEFAULT_PORT, rackLocation, hostname);
if (storage != null) {
dn.updateStorage(storage);
}
return dn;
}
public static DatanodeStorageInfo newDatanodeStorageInfo(
DatanodeDescriptor dn, DatanodeStorage s) {
return new DatanodeStorageInfo(dn, s);
}
public static StorageReport[] getStorageReportsForDatanode(
DatanodeDescriptor dnd) {
ArrayList<StorageReport> reports = new ArrayList<StorageReport>();
for (DatanodeStorageInfo storage : dnd.getStorageInfos()) {
DatanodeStorage dns = new DatanodeStorage(
storage.getStorageID(), storage.getState(), storage.getStorageType());
StorageReport report = new StorageReport(
dns ,false, storage.getCapacity(),
storage.getDfsUsed(), storage.getRemaining(),
storage.getBlockPoolUsed(), 0);
reports.add(report);
}
return reports.toArray(StorageReport.EMPTY_ARRAY);
}
/**
* Have DatanodeManager check decommission state.
* @param dm the DatanodeManager to manipulate
*/
public static void recheckDecommissionState(DatanodeManager dm)
throws ExecutionException, InterruptedException {
dm.getDecomManager().runMonitorForTest();
}
/**
* add block to the replicateBlocks queue of the Datanode
*/
public static void addBlockToBeReplicated(DatanodeDescriptor node,
Block block, DatanodeStorageInfo[] targets) {
node.addBlockToBeReplicated(block, targets);
}
public static void setStartupSafeModeForTest(BlockManager bm) {
BlockManagerSafeMode bmSafeMode = (BlockManagerSafeMode)Whitebox
.getInternalState(bm, "bmSafeMode");
Whitebox.setInternalState(bmSafeMode, "extension", Integer.MAX_VALUE);
Whitebox.setInternalState(bmSafeMode, "status", BMSafeModeStatus.EXTENSION);
}
/**
* Check if a given Datanode (specified by uuid) is removed. Removed means the
* Datanode is no longer present in HeartbeatManager and NetworkTopology.
* @param nn Namenode
* @param dnUuid Datanode UUID
* @return true if datanode is removed.
*/
public static boolean isDatanodeRemoved(NameNode nn, String dnUuid){
final DatanodeManager dnm =
nn.getNamesystem().getBlockManager().getDatanodeManager();
return !dnm.getNetworkTopology().contains(dnm.getDatanode(dnUuid));
}
}
| {
"content_hash": "ed05d1420fe9ca6bf368a9f69082986b",
"timestamp": "",
"source": "github",
"line_count": 345,
"max_line_length": 95,
"avg_line_length": 34.655072463768114,
"alnum_prop": 0.7208096353295417,
"repo_name": "Ethanlm/hadoop",
"id": "77e2ffb1dc392f83d635452d237e78cc8550a7e7",
"size": "12762",
"binary": false,
"copies": "3",
"ref": "refs/heads/trunk",
"path": "hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManagerTestUtil.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "68758"
},
{
"name": "C",
"bytes": "1406803"
},
{
"name": "C++",
"bytes": "1816626"
},
{
"name": "CMake",
"bytes": "54617"
},
{
"name": "CSS",
"bytes": "58347"
},
{
"name": "HTML",
"bytes": "205485"
},
{
"name": "Java",
"bytes": "64946878"
},
{
"name": "JavaScript",
"bytes": "606717"
},
{
"name": "Protocol Buffer",
"bytes": "269457"
},
{
"name": "Python",
"bytes": "23553"
},
{
"name": "Shell",
"bytes": "380068"
},
{
"name": "TLA",
"bytes": "14993"
},
{
"name": "TeX",
"bytes": "19322"
},
{
"name": "XSLT",
"bytes": "16894"
}
],
"symlink_target": ""
} |
class ProblemKeyword < ApplicationRecord
self.primary_keys = :problem_id, :keyword
belongs_to :problem
end
| {
"content_hash": "24ac3320a2b097c5a4d78b5bbcfe2e28",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 43,
"avg_line_length": 27.75,
"alnum_prop": 0.7747747747747747,
"repo_name": "KellenWatt/hundis",
"id": "dfb792601ac9889f7eeebd6397dea1ed95c25a00",
"size": "111",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "jje/app/models/problem_keyword.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6937"
},
{
"name": "CoffeeScript",
"bytes": "2110"
},
{
"name": "Dockerfile",
"bytes": "2166"
},
{
"name": "HTML",
"bytes": "40213"
},
{
"name": "JavaScript",
"bytes": "1234"
},
{
"name": "Python",
"bytes": "19471"
},
{
"name": "Ruby",
"bytes": "109954"
},
{
"name": "Shell",
"bytes": "5903"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_65) on Wed Nov 12 13:03:03 UTC 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class com.hazelcast.mapreduce.impl.operation.RequestPartitionProcessed (Hazelcast Root 3.3.3 API)</title>
<meta name="date" content="2014-11-12">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.hazelcast.mapreduce.impl.operation.RequestPartitionProcessed (Hazelcast Root 3.3.3 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../com/hazelcast/mapreduce/impl/operation/RequestPartitionProcessed.html" title="class in com.hazelcast.mapreduce.impl.operation">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/hazelcast/mapreduce/impl/operation/class-use/RequestPartitionProcessed.html" target="_top">Frames</a></li>
<li><a href="RequestPartitionProcessed.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.hazelcast.mapreduce.impl.operation.RequestPartitionProcessed" class="title">Uses of Class<br>com.hazelcast.mapreduce.impl.operation.RequestPartitionProcessed</h2>
</div>
<div class="classUseContainer">No usage of com.hazelcast.mapreduce.impl.operation.RequestPartitionProcessed</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../com/hazelcast/mapreduce/impl/operation/RequestPartitionProcessed.html" title="class in com.hazelcast.mapreduce.impl.operation">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/hazelcast/mapreduce/impl/operation/class-use/RequestPartitionProcessed.html" target="_top">Frames</a></li>
<li><a href="RequestPartitionProcessed.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2014 <a href="http://www.hazelcast.com/">Hazelcast, Inc.</a>. All Rights Reserved.</small></p>
</body>
</html>
| {
"content_hash": "94236dbf25d1c560b929e2b516f7069c",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 191,
"avg_line_length": 40.48717948717949,
"alnum_prop": 0.6328900147772852,
"repo_name": "SoCe/SoCe",
"id": "80de43fb4c8de003a3e62a2c0deb8ec77855acb3",
"size": "4737",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Server/thirdparty/hazelcast/hazelcast-3.3.3/docs/javadoc/com/hazelcast/mapreduce/impl/operation/class-use/RequestPartitionProcessed.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "87092"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LanMachines")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("eXPerience")]
[assembly: AssemblyProduct("LanMachines")]
[assembly: AssemblyCopyright("Copyright © eXPerience 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("dee67b36-2d21-451d-96a3-f0e66ab38af3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "536aee7b2b952471ab6378c602ea6aef",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 39.30555555555556,
"alnum_prop": 0.7484098939929329,
"repo_name": "RedSpiderMkV/LANMachines",
"id": "a4b69dfe42b6fdaec04971a3464f970de55bd506",
"size": "1418",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/LanMachinesRunner/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "45185"
}
],
"symlink_target": ""
} |
require 'spree_core'
require 'spree_affirm/engine'
| {
"content_hash": "67464eb27606ec124254b43b612284c9",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 29,
"avg_line_length": 25.5,
"alnum_prop": 0.7843137254901961,
"repo_name": "CasperSleep/spree_affirm",
"id": "406323d9a31826a43e16e83b47a1b179153f9775",
"size": "51",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "lib/spree_affirm.rb",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
ACCEPTED
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "b7f4df03170a517f87997de4a5dd1d52",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 47,
"avg_line_length": 10.923076923076923,
"alnum_prop": 0.7183098591549296,
"repo_name": "mdoering/backbone",
"id": "ff8c408dd8d05c3ec860ee1ad506ac91696fbaad",
"size": "214",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Dermateaceae/Pilidium/Pilidium carbonaceum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.servicecontrol.v2.model;
/**
* An individual log entry.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Service Control API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class V2LogEntry extends com.google.api.client.json.GenericJson {
/**
* Optional. Information about the HTTP request associated with this log entry, if applicable.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private V2HttpRequest httpRequest;
/**
* A unique ID for the log entry used for deduplication. If omitted, the implementation will
* generate one based on operation_id.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String insertId;
/**
* A set of user-defined (key, value) data that provides additional information about the log
* entry.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.Map<String, java.lang.String> labels;
/**
* A set of user-defined (key, value) data that provides additional information about the
* moniotored resource that the log entry belongs to.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.Map<String, java.lang.String> monitoredResourceLabels;
/**
* Required. The log to which this log entry belongs. Examples: `"syslog"`, `"book_log"`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* Optional. Information about an operation associated with the log entry, if applicable.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private V2LogEntryOperation operation;
/**
* The log entry payload, represented as a protocol buffer that is expressed as a JSON object. The
* only accepted type currently is AuditLog.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.Map<String, java.lang.Object> protoPayload;
/**
* The severity of the log entry. The default value is `LogSeverity.DEFAULT`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String severity;
/**
* Optional. Source code location information associated with the log entry, if any.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private V2LogEntrySourceLocation sourceLocation;
/**
* The log entry payload, represented as a structure that is expressed as a JSON object.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.Map<String, java.lang.Object> structPayload;
/**
* The log entry payload, represented as a Unicode string (UTF-8).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String textPayload;
/**
* The time the event described by the log entry occurred. If omitted, defaults to operation start
* time.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String timestamp;
/**
* Optional. Resource name of the trace associated with the log entry, if any. If this field
* contains a relative resource name, you can assume the name is relative to
* `//tracing.googleapis.com`. Example: `projects/my-
* projectid/traces/06796866738c859f2f19b7cfb3214824`
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String trace;
/**
* Optional. Information about the HTTP request associated with this log entry, if applicable.
* @return value or {@code null} for none
*/
public V2HttpRequest getHttpRequest() {
return httpRequest;
}
/**
* Optional. Information about the HTTP request associated with this log entry, if applicable.
* @param httpRequest httpRequest or {@code null} for none
*/
public V2LogEntry setHttpRequest(V2HttpRequest httpRequest) {
this.httpRequest = httpRequest;
return this;
}
/**
* A unique ID for the log entry used for deduplication. If omitted, the implementation will
* generate one based on operation_id.
* @return value or {@code null} for none
*/
public java.lang.String getInsertId() {
return insertId;
}
/**
* A unique ID for the log entry used for deduplication. If omitted, the implementation will
* generate one based on operation_id.
* @param insertId insertId or {@code null} for none
*/
public V2LogEntry setInsertId(java.lang.String insertId) {
this.insertId = insertId;
return this;
}
/**
* A set of user-defined (key, value) data that provides additional information about the log
* entry.
* @return value or {@code null} for none
*/
public java.util.Map<String, java.lang.String> getLabels() {
return labels;
}
/**
* A set of user-defined (key, value) data that provides additional information about the log
* entry.
* @param labels labels or {@code null} for none
*/
public V2LogEntry setLabels(java.util.Map<String, java.lang.String> labels) {
this.labels = labels;
return this;
}
/**
* A set of user-defined (key, value) data that provides additional information about the
* moniotored resource that the log entry belongs to.
* @return value or {@code null} for none
*/
public java.util.Map<String, java.lang.String> getMonitoredResourceLabels() {
return monitoredResourceLabels;
}
/**
* A set of user-defined (key, value) data that provides additional information about the
* moniotored resource that the log entry belongs to.
* @param monitoredResourceLabels monitoredResourceLabels or {@code null} for none
*/
public V2LogEntry setMonitoredResourceLabels(java.util.Map<String, java.lang.String> monitoredResourceLabels) {
this.monitoredResourceLabels = monitoredResourceLabels;
return this;
}
/**
* Required. The log to which this log entry belongs. Examples: `"syslog"`, `"book_log"`.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Required. The log to which this log entry belongs. Examples: `"syslog"`, `"book_log"`.
* @param name name or {@code null} for none
*/
public V2LogEntry setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* Optional. Information about an operation associated with the log entry, if applicable.
* @return value or {@code null} for none
*/
public V2LogEntryOperation getOperation() {
return operation;
}
/**
* Optional. Information about an operation associated with the log entry, if applicable.
* @param operation operation or {@code null} for none
*/
public V2LogEntry setOperation(V2LogEntryOperation operation) {
this.operation = operation;
return this;
}
/**
* The log entry payload, represented as a protocol buffer that is expressed as a JSON object. The
* only accepted type currently is AuditLog.
* @return value or {@code null} for none
*/
public java.util.Map<String, java.lang.Object> getProtoPayload() {
return protoPayload;
}
/**
* The log entry payload, represented as a protocol buffer that is expressed as a JSON object. The
* only accepted type currently is AuditLog.
* @param protoPayload protoPayload or {@code null} for none
*/
public V2LogEntry setProtoPayload(java.util.Map<String, java.lang.Object> protoPayload) {
this.protoPayload = protoPayload;
return this;
}
/**
* The severity of the log entry. The default value is `LogSeverity.DEFAULT`.
* @return value or {@code null} for none
*/
public java.lang.String getSeverity() {
return severity;
}
/**
* The severity of the log entry. The default value is `LogSeverity.DEFAULT`.
* @param severity severity or {@code null} for none
*/
public V2LogEntry setSeverity(java.lang.String severity) {
this.severity = severity;
return this;
}
/**
* Optional. Source code location information associated with the log entry, if any.
* @return value or {@code null} for none
*/
public V2LogEntrySourceLocation getSourceLocation() {
return sourceLocation;
}
/**
* Optional. Source code location information associated with the log entry, if any.
* @param sourceLocation sourceLocation or {@code null} for none
*/
public V2LogEntry setSourceLocation(V2LogEntrySourceLocation sourceLocation) {
this.sourceLocation = sourceLocation;
return this;
}
/**
* The log entry payload, represented as a structure that is expressed as a JSON object.
* @return value or {@code null} for none
*/
public java.util.Map<String, java.lang.Object> getStructPayload() {
return structPayload;
}
/**
* The log entry payload, represented as a structure that is expressed as a JSON object.
* @param structPayload structPayload or {@code null} for none
*/
public V2LogEntry setStructPayload(java.util.Map<String, java.lang.Object> structPayload) {
this.structPayload = structPayload;
return this;
}
/**
* The log entry payload, represented as a Unicode string (UTF-8).
* @return value or {@code null} for none
*/
public java.lang.String getTextPayload() {
return textPayload;
}
/**
* The log entry payload, represented as a Unicode string (UTF-8).
* @param textPayload textPayload or {@code null} for none
*/
public V2LogEntry setTextPayload(java.lang.String textPayload) {
this.textPayload = textPayload;
return this;
}
/**
* The time the event described by the log entry occurred. If omitted, defaults to operation start
* time.
* @return value or {@code null} for none
*/
public String getTimestamp() {
return timestamp;
}
/**
* The time the event described by the log entry occurred. If omitted, defaults to operation start
* time.
* @param timestamp timestamp or {@code null} for none
*/
public V2LogEntry setTimestamp(String timestamp) {
this.timestamp = timestamp;
return this;
}
/**
* Optional. Resource name of the trace associated with the log entry, if any. If this field
* contains a relative resource name, you can assume the name is relative to
* `//tracing.googleapis.com`. Example: `projects/my-
* projectid/traces/06796866738c859f2f19b7cfb3214824`
* @return value or {@code null} for none
*/
public java.lang.String getTrace() {
return trace;
}
/**
* Optional. Resource name of the trace associated with the log entry, if any. If this field
* contains a relative resource name, you can assume the name is relative to
* `//tracing.googleapis.com`. Example: `projects/my-
* projectid/traces/06796866738c859f2f19b7cfb3214824`
* @param trace trace or {@code null} for none
*/
public V2LogEntry setTrace(java.lang.String trace) {
this.trace = trace;
return this;
}
@Override
public V2LogEntry set(String fieldName, Object value) {
return (V2LogEntry) super.set(fieldName, value);
}
@Override
public V2LogEntry clone() {
return (V2LogEntry) super.clone();
}
}
| {
"content_hash": "b984c737f1e97d381c93a61c83e33f7d",
"timestamp": "",
"source": "github",
"line_count": 378,
"max_line_length": 182,
"avg_line_length": 32.283068783068785,
"alnum_prop": 0.6978611816766369,
"repo_name": "googleapis/google-api-java-client-services",
"id": "1f29181ba5dad34a0fd5ff9e5c34af15b37bd625",
"size": "12203",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "clients/google-api-services-servicecontrol/v2/1.31.0/com/google/api/services/servicecontrol/v2/model/V2LogEntry.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.red5.server.stream;
import org.red5.server.api.event.IEvent;
/**
* Source for streams
*/
public interface IStreamSource {
/**
* Is there something more to stream?
*
* @return <pre>
* true
* </pre>
*
* if there's streamable data,
*
* <pre>
* false
* </pre>
*
* otherwise
*/
public abstract boolean hasMore();
/**
* Double ended queue of event objects
*
* @return Event from queue
*/
public abstract IEvent dequeue();
/**
* Close stream source
*/
public abstract void close();
}
| {
"content_hash": "8ddd0e5cc613882c1466a7cd83e86f58",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 42,
"avg_line_length": 16.15,
"alnum_prop": 0.5170278637770898,
"repo_name": "Red5/red5-server",
"id": "12078b504ff6a69ec4d8c3c87a7ed7660a27270f",
"size": "1315",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/src/main/java/org/red5/server/stream/IStreamSource.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "6368"
},
{
"name": "Groovy",
"bytes": "1568"
},
{
"name": "HTML",
"bytes": "31778"
},
{
"name": "Java",
"bytes": "4191635"
},
{
"name": "JavaScript",
"bytes": "59280"
},
{
"name": "Python",
"bytes": "2832"
},
{
"name": "Ruby",
"bytes": "3453"
},
{
"name": "Shell",
"bytes": "6447"
}
],
"symlink_target": ""
} |
[](https://travis-ci.org/dorada/DRNetworkUpdatingPlist)
[](http://cocoapods.org/pods/DRNetworkUpdatingPlist)
[](http://cocoapods.org/pods/DRNetworkUpdatingPlist)
[](http://cocoapods.org/pods/DRNetworkUpdatingPlist)
## Usage
To run the example project, clone the repo, and run `pod install` from the Example directory first.
## Requirements
## Installation
DRNetworkUpdatingPlist is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:
```ruby
pod "DRNetworkUpdatingPlist"
```
## Author
Daniel Broad, [email protected]
## License
DRNetworkUpdatingPlist is available under the MIT license. See the LICENSE file for more info.
| {
"content_hash": "dd7dfdf80c976949dfb69fefe1e35a51",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 142,
"avg_line_length": 38.370370370370374,
"alnum_prop": 0.7847490347490348,
"repo_name": "dorada/DRNetworkUpdatingPlist",
"id": "4635d9724c056734874e1d7e19a9ceddea482c61",
"size": "1062",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "12679"
},
{
"name": "Ruby",
"bytes": "1906"
},
{
"name": "Shell",
"bytes": "16456"
}
],
"symlink_target": ""
} |
package Paws::ELB::AttachLoadBalancerToSubnetsOutput;
use Moose;
has Subnets => (is => 'ro', isa => 'ArrayRef[Str|Undef]');
has _request_id => (is => 'ro', isa => 'Str');
1;
### main pod documentation begin ###
=head1 NAME
Paws::ELB::AttachLoadBalancerToSubnetsOutput
=head1 ATTRIBUTES
=head2 Subnets => ArrayRef[Str|Undef]
The IDs of the subnets attached to the load balancer.
=head2 _request_id => Str
=cut
| {
"content_hash": "d198ea5ff477ca82bbb4f18c2e860b1f",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 60,
"avg_line_length": 16.46153846153846,
"alnum_prop": 0.6799065420560748,
"repo_name": "ioanrogers/aws-sdk-perl",
"id": "b8bc6be104bd30e1d2f8d5d9b54464005f597699",
"size": "429",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "auto-lib/Paws/ELB/AttachLoadBalancerToSubnetsOutput.pm",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "1292"
},
{
"name": "Perl",
"bytes": "20360380"
},
{
"name": "Perl 6",
"bytes": "99393"
},
{
"name": "Shell",
"bytes": "445"
}
],
"symlink_target": ""
} |
using gpu_blink::WebGraphicsContext3DInProcessCommandBufferImpl;
namespace content {
class ContextProviderInProcess::LostContextCallbackProxy
: public blink::WebGraphicsContext3D::WebGraphicsContextLostCallback {
public:
explicit LostContextCallbackProxy(ContextProviderInProcess* provider)
: provider_(provider) {
provider_->WebContext3DImpl()->setContextLostCallback(this);
}
~LostContextCallbackProxy() override {
provider_->WebContext3DImpl()->setContextLostCallback(NULL);
}
void onContextLost() override {
provider_->OnLostContext();
}
private:
ContextProviderInProcess* provider_;
};
// static
scoped_refptr<ContextProviderInProcess> ContextProviderInProcess::Create(
scoped_ptr<WebGraphicsContext3DInProcessCommandBufferImpl> context3d,
const std::string& debug_name) {
if (!context3d)
return NULL;
return new ContextProviderInProcess(std::move(context3d), debug_name);
}
ContextProviderInProcess::ContextProviderInProcess(
scoped_ptr<WebGraphicsContext3DInProcessCommandBufferImpl> context3d,
const std::string& debug_name)
: debug_name_(debug_name) {
DCHECK(main_thread_checker_.CalledOnValidThread());
DCHECK(context3d);
gr_interface_ = skia::AdoptRef(
new GrGLInterfaceForWebGraphicsContext3D(std::move(context3d)));
DCHECK(gr_interface_->WebContext3D());
context_thread_checker_.DetachFromThread();
}
ContextProviderInProcess::~ContextProviderInProcess() {
DCHECK(main_thread_checker_.CalledOnValidThread() ||
context_thread_checker_.CalledOnValidThread());
}
blink::WebGraphicsContext3D* ContextProviderInProcess::WebContext3D() {
DCHECK(lost_context_callback_proxy_); // Is bound to thread.
DCHECK(context_thread_checker_.CalledOnValidThread());
return WebContext3DImpl();
}
gpu_blink::WebGraphicsContext3DInProcessCommandBufferImpl*
ContextProviderInProcess::WebContext3DImpl() {
DCHECK(gr_interface_->WebContext3D());
return
static_cast<gpu_blink::WebGraphicsContext3DInProcessCommandBufferImpl*>(
gr_interface_->WebContext3D());
}
bool ContextProviderInProcess::BindToCurrentThread() {
DCHECK(WebContext3DImpl());
// This is called on the thread the context will be used.
DCHECK(context_thread_checker_.CalledOnValidThread());
if (lost_context_callback_proxy_)
return true;
if (!WebContext3DImpl()->InitializeOnCurrentThread())
return false;
gr_interface_->BindToCurrentThread();
InitializeCapabilities();
const std::string unique_context_name =
base::StringPrintf("%s-%p", debug_name_.c_str(), WebContext3DImpl());
WebContext3DImpl()->traceBeginCHROMIUM("gpu_toplevel",
unique_context_name.c_str());
lost_context_callback_proxy_.reset(new LostContextCallbackProxy(this));
return true;
}
void ContextProviderInProcess::DetachFromThread() {
context_thread_checker_.DetachFromThread();
}
void ContextProviderInProcess::InitializeCapabilities() {
capabilities_.gpu = WebContext3DImpl()->GetImplementation()->capabilities();
size_t mapped_memory_limit = WebContext3DImpl()->GetMappedMemoryLimit();
capabilities_.max_transfer_buffer_usage_bytes =
mapped_memory_limit ==
WebGraphicsContext3DInProcessCommandBufferImpl::kNoLimit
? std::numeric_limits<size_t>::max()
: mapped_memory_limit;
}
cc::ContextProvider::Capabilities
ContextProviderInProcess::ContextCapabilities() {
DCHECK(lost_context_callback_proxy_); // Is bound to thread.
DCHECK(context_thread_checker_.CalledOnValidThread());
return capabilities_;
}
::gpu::gles2::GLES2Interface* ContextProviderInProcess::ContextGL() {
DCHECK(WebContext3DImpl());
DCHECK(lost_context_callback_proxy_); // Is bound to thread.
DCHECK(context_thread_checker_.CalledOnValidThread());
return WebContext3DImpl()->GetGLInterface();
}
::gpu::ContextSupport* ContextProviderInProcess::ContextSupport() {
DCHECK(WebContext3DImpl());
if (!lost_context_callback_proxy_)
return NULL; // Not bound to anything.
DCHECK(context_thread_checker_.CalledOnValidThread());
return WebContext3DImpl()->GetContextSupport();
}
class GrContext* ContextProviderInProcess::GrContext() {
DCHECK(lost_context_callback_proxy_); // Is bound to thread.
DCHECK(context_thread_checker_.CalledOnValidThread());
if (gr_context_)
return gr_context_->get();
gr_context_.reset(new GrContextForWebGraphicsContext3D(gr_interface_));
return gr_context_->get();
}
void ContextProviderInProcess::InvalidateGrContext(uint32_t state) {
DCHECK(lost_context_callback_proxy_); // Is bound to thread.
DCHECK(context_thread_checker_.CalledOnValidThread());
if (gr_context_)
return gr_context_->get()->resetContext(state);
}
void ContextProviderInProcess::SetupLock() {
WebContext3DImpl()->SetLock(&context_lock_);
}
base::Lock* ContextProviderInProcess::GetLock() {
return &context_lock_;
}
void ContextProviderInProcess::DeleteCachedResources() {
DCHECK(context_thread_checker_.CalledOnValidThread());
if (gr_context_)
gr_context_->FreeGpuResources();
}
void ContextProviderInProcess::OnLostContext() {
DCHECK(context_thread_checker_.CalledOnValidThread());
if (!lost_context_callback_.is_null())
base::ResetAndReturn(&lost_context_callback_).Run();
if (gr_context_)
gr_context_->OnLostContext();
}
void ContextProviderInProcess::SetLostContextCallback(
const LostContextCallback& lost_context_callback) {
DCHECK(context_thread_checker_.CalledOnValidThread());
DCHECK(lost_context_callback_.is_null() ||
lost_context_callback.is_null());
lost_context_callback_ = lost_context_callback;
}
} // namespace content
| {
"content_hash": "5e187c1f3941ca374d9481b5df531932",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 78,
"avg_line_length": 31.502762430939228,
"alnum_prop": 0.7437741143458436,
"repo_name": "highweb-project/highweb-webcl-html5spec",
"id": "9f4fbc2d827bb9193850ec57cc09f2689b480ed3",
"size": "6393",
"binary": false,
"copies": "9",
"ref": "refs/heads/highweb-20160310",
"path": "content/browser/android/in_process/context_provider_in_process.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v11/enums/value_rule_set_dimension.proto
package com.google.ads.googleads.v11.enums;
/**
* <pre>
* Container for enum describing possible dimensions of a conversion value rule
* set.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum}
*/
public final class ValueRuleSetDimensionEnum extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum)
ValueRuleSetDimensionEnumOrBuilder {
private static final long serialVersionUID = 0L;
// Use ValueRuleSetDimensionEnum.newBuilder() to construct.
private ValueRuleSetDimensionEnum(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ValueRuleSetDimensionEnum() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new ValueRuleSetDimensionEnum();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v11.enums.ValueRuleSetDimensionProto.internal_static_google_ads_googleads_v11_enums_ValueRuleSetDimensionEnum_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v11.enums.ValueRuleSetDimensionProto.internal_static_google_ads_googleads_v11_enums_ValueRuleSetDimensionEnum_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum.class, com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum.Builder.class);
}
/**
* <pre>
* Possible dimensions of a conversion value rule set.
* </pre>
*
* Protobuf enum {@code google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum.ValueRuleSetDimension}
*/
public enum ValueRuleSetDimension
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <pre>
* Not specified.
* </pre>
*
* <code>UNSPECIFIED = 0;</code>
*/
UNSPECIFIED(0),
/**
* <pre>
* Used for return value only. Represents value unknown in this version.
* </pre>
*
* <code>UNKNOWN = 1;</code>
*/
UNKNOWN(1),
/**
* <pre>
* Dimension for geo location.
* </pre>
*
* <code>GEO_LOCATION = 2;</code>
*/
GEO_LOCATION(2),
/**
* <pre>
* Dimension for device type.
* </pre>
*
* <code>DEVICE = 3;</code>
*/
DEVICE(3),
/**
* <pre>
* Dimension for audience.
* </pre>
*
* <code>AUDIENCE = 4;</code>
*/
AUDIENCE(4),
/**
* <pre>
* This dimension implies the rule will always apply.
* </pre>
*
* <code>NO_CONDITION = 5;</code>
*/
NO_CONDITION(5),
UNRECOGNIZED(-1),
;
/**
* <pre>
* Not specified.
* </pre>
*
* <code>UNSPECIFIED = 0;</code>
*/
public static final int UNSPECIFIED_VALUE = 0;
/**
* <pre>
* Used for return value only. Represents value unknown in this version.
* </pre>
*
* <code>UNKNOWN = 1;</code>
*/
public static final int UNKNOWN_VALUE = 1;
/**
* <pre>
* Dimension for geo location.
* </pre>
*
* <code>GEO_LOCATION = 2;</code>
*/
public static final int GEO_LOCATION_VALUE = 2;
/**
* <pre>
* Dimension for device type.
* </pre>
*
* <code>DEVICE = 3;</code>
*/
public static final int DEVICE_VALUE = 3;
/**
* <pre>
* Dimension for audience.
* </pre>
*
* <code>AUDIENCE = 4;</code>
*/
public static final int AUDIENCE_VALUE = 4;
/**
* <pre>
* This dimension implies the rule will always apply.
* </pre>
*
* <code>NO_CONDITION = 5;</code>
*/
public static final int NO_CONDITION_VALUE = 5;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static ValueRuleSetDimension valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static ValueRuleSetDimension forNumber(int value) {
switch (value) {
case 0: return UNSPECIFIED;
case 1: return UNKNOWN;
case 2: return GEO_LOCATION;
case 3: return DEVICE;
case 4: return AUDIENCE;
case 5: return NO_CONDITION;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<ValueRuleSetDimension>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
ValueRuleSetDimension> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<ValueRuleSetDimension>() {
public ValueRuleSetDimension findValueByNumber(int number) {
return ValueRuleSetDimension.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum.getDescriptor().getEnumTypes().get(0);
}
private static final ValueRuleSetDimension[] VALUES = values();
public static ValueRuleSetDimension valueOf(
com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException(
"EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private ValueRuleSetDimension(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum.ValueRuleSetDimension)
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum)) {
return super.equals(obj);
}
com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum other = (com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum) obj;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Container for enum describing possible dimensions of a conversion value rule
* set.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum)
com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnumOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v11.enums.ValueRuleSetDimensionProto.internal_static_google_ads_googleads_v11_enums_ValueRuleSetDimensionEnum_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v11.enums.ValueRuleSetDimensionProto.internal_static_google_ads_googleads_v11_enums_ValueRuleSetDimensionEnum_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum.class, com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum.Builder.class);
}
// Construct using com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum.newBuilder()
private Builder() {
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v11.enums.ValueRuleSetDimensionProto.internal_static_google_ads_googleads_v11_enums_ValueRuleSetDimensionEnum_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum getDefaultInstanceForType() {
return com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum build() {
com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum buildPartial() {
com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum result = new com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum(this);
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum) {
return mergeFrom((com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum other) {
if (other == com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum.getDefaultInstance()) return this;
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum)
private static final com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum();
}
public static com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ValueRuleSetDimensionEnum>
PARSER = new com.google.protobuf.AbstractParser<ValueRuleSetDimensionEnum>() {
@java.lang.Override
public ValueRuleSetDimensionEnum parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ValueRuleSetDimensionEnum> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ValueRuleSetDimensionEnum> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v11.enums.ValueRuleSetDimensionEnum getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| {
"content_hash": "cdd661f381eae2b78e1e3c37820b74f6",
"timestamp": "",
"source": "github",
"line_count": 607,
"max_line_length": 166,
"avg_line_length": 34.32125205930807,
"alnum_prop": 0.6942831085297365,
"repo_name": "googleads/google-ads-java",
"id": "6b871aadc5c611c267d650f819f9869e739e3457",
"size": "20833",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "google-ads-stubs-v11/src/main/java/com/google/ads/googleads/v11/enums/ValueRuleSetDimensionEnum.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "28701198"
}
],
"symlink_target": ""
} |
.. meta::
:robots: index, follow
:description: ndtypes documentation
:keywords: Python, array computing
.. sectionauthor:: Stefan Krah <skrah at bytereef.org>
ndtypes
-------
ndtypes is a Python module based on libndtypes.
.. toctree::
quickstart.rst
types.rst
pattern-matching.rst
buffer-protocol.rst
| {
"content_hash": "233a9be4c14d9af975bc26d3bddb413c",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 54,
"avg_line_length": 15.761904761904763,
"alnum_prop": 0.6948640483383686,
"repo_name": "skrah/ndtypes",
"id": "5074dc644d98a237ba7d54dbe3c4708a8f037d19",
"size": "331",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "doc/ndtypes/index.rst",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "2903"
},
{
"name": "C",
"bytes": "1968451"
},
{
"name": "C++",
"bytes": "14553"
},
{
"name": "Lex",
"bytes": "12245"
},
{
"name": "M4",
"bytes": "3838"
},
{
"name": "Makefile",
"bytes": "15268"
},
{
"name": "Python",
"bytes": "105168"
},
{
"name": "Shell",
"bytes": "14315"
},
{
"name": "Yacc",
"bytes": "31122"
}
],
"symlink_target": ""
} |
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/bitrise-io/go-steputils/command/rubycommand"
"github.com/bitrise-io/go-utils/command"
"github.com/bitrise-io/go-utils/fileutil"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-utils/pathutil"
"github.com/bitrise-io/go-xcode/simulator"
shellquote "github.com/kballard/go-shellquote"
)
// ConfigsModel ...
type ConfigsModel struct {
WorkDir string
GemFilePath string
AppPath string
Options string
SimulatorDevice string
SimulatorOsVersion string
CalabashCucumberVersion string
}
func createConfigsModelFromEnvs() ConfigsModel {
return ConfigsModel{
WorkDir: os.Getenv("work_dir"),
GemFilePath: os.Getenv("gem_file_path"),
AppPath: os.Getenv("app_path"),
Options: os.Getenv("additional_options"),
SimulatorDevice: os.Getenv("simulator_device"),
SimulatorOsVersion: os.Getenv("simulator_os_version"),
CalabashCucumberVersion: os.Getenv("calabash_cucumber_version"),
}
}
func (configs ConfigsModel) print() {
log.Infof("Configs:")
log.Printf("- WorkDir: %s", configs.WorkDir)
log.Printf("- GemFilePath: %s", configs.GemFilePath)
log.Printf("- AppPath: %s", configs.AppPath)
log.Printf("- Options: %s", configs.Options)
log.Printf("- SimulatorDevice: %s", configs.SimulatorDevice)
log.Printf("- SimulatorOsVersion: %s", configs.SimulatorOsVersion)
log.Printf("- CalabashCucumberVersion: %s", configs.CalabashCucumberVersion)
}
func (configs ConfigsModel) validate() error {
if configs.WorkDir == "" {
return errors.New("no WorkDir parameter specified")
}
if exist, err := pathutil.IsDirExists(configs.WorkDir); err != nil {
return fmt.Errorf("failed to check if WorkDir exist, error: %s", err)
} else if !exist {
return fmt.Errorf("WorkDir directory not exists at: %s", configs.WorkDir)
}
if configs.AppPath != "" {
if exist, err := pathutil.IsDirExists(configs.AppPath); err != nil {
return fmt.Errorf("failed to check if AppPath exist, error: %s", err)
} else if !exist {
return fmt.Errorf("AppPath directory not exists at: %s", configs.AppPath)
}
}
if configs.SimulatorDevice == "" {
return errors.New("no SimulatorDevice parameter specified")
}
if configs.SimulatorOsVersion == "" {
return errors.New("no SimulatorOsVersion parameter specified")
}
return nil
}
func exportEnvironmentWithEnvman(keyStr, valueStr string) error {
cmd := command.New("envman", "add", "--key", keyStr)
cmd.SetStdin(strings.NewReader(valueStr))
return cmd.Run()
}
func registerFail(format string, v ...interface{}) {
log.Errorf(format, v...)
if err := exportEnvironmentWithEnvman("BITRISE_XAMARIN_TEST_RESULT", "failed"); err != nil {
log.Warnf("Failed to export environment: %s, error: %s", "BITRISE_XAMARIN_TEST_RESULT", err)
}
os.Exit(1)
}
func calabashCucumberFromGemfileLockContent(content string) string {
relevantLines := []string{}
lines := strings.Split(content, "\n")
specsStart := false
for _, line := range lines {
if strings.Contains(line, "specs:") {
specsStart = true
}
trimmed := strings.Trim(line, " ")
if trimmed == "" {
break
}
if specsStart {
relevantLines = append(relevantLines, line)
}
}
exp := regexp.MustCompile(`calabash-cucumber \((.+)\)`)
for _, line := range relevantLines {
match := exp.FindStringSubmatch(line)
if match != nil && len(match) == 2 {
return match[1]
}
}
return ""
}
func calabashCucumberVersionFromGemfileLock(gemfileLockPth string) (string, error) {
content, err := fileutil.ReadStringFromFile(gemfileLockPth)
if err != nil {
return "", err
}
return calabashCucumberFromGemfileLockContent(content), nil
}
func copyDir(src, dst string, contentOnly bool) error {
if !contentOnly {
return os.Rename(src, dst)
}
files, err := pathutil.ListPathInDirSortedByComponents(src, false)
if err != nil {
return err
}
for _, file := range files {
base := filepath.Base(file)
pth := filepath.Join(dst, base)
if err := os.Rename(file, pth); err != nil {
return err
}
}
return nil
}
func indexInStringSlice(value string, list []string) int {
for i, v := range list {
if v == value {
return i
}
}
return -1
}
func main() {
configs := createConfigsModelFromEnvs()
fmt.Println()
configs.print()
if err := configs.validate(); err != nil {
registerFail("Issue with input: %s", err)
}
options, err := shellquote.Split(configs.Options)
if err != nil {
registerFail("Failed to split additional options (%s), error: %s", configs.Options, err)
}
// Get Simulator Infos
fmt.Println()
log.Infof("Collecting simulator info...")
var simulatorInfo simulator.InfoModel
if configs.SimulatorOsVersion == "latest" {
info, version, err := simulator.GetLatestSimulatorInfoAndVersion("iOS", configs.SimulatorDevice)
if err != nil {
registerFail("Failed to get simulator info, error: %s", err)
}
simulatorInfo = info
log.Printf("Latest os version: %s", version)
} else {
info, err := simulator.GetSimulatorInfo(configs.SimulatorOsVersion, configs.SimulatorDevice)
if err != nil {
registerFail("Failed to get simulator info, error: %s", err)
}
simulatorInfo = info
}
log.Donef("Simulator (%s), id: (%s), status: %s", simulatorInfo.Name, simulatorInfo.ID, simulatorInfo.Status)
// ---
// Ensure if app is compatible with simulator device
if configs.AppPath != "" {
monotouch32Dir := filepath.Join(configs.AppPath, ".monotouch-32")
monotouch32DirExist, err := pathutil.IsDirExists(monotouch32Dir)
if err != nil {
registerFail("Failed to check if path (%s) exist, error: %s", monotouch32Dir, err)
}
monotouch64Dir := filepath.Join(configs.AppPath, ".monotouch-64")
monotouch64DirExist, err := pathutil.IsDirExists(monotouch64Dir)
if err != nil {
registerFail("Failed to check if path (%s) exist, error: %s", monotouch64Dir, err)
}
if monotouch32DirExist && monotouch64DirExist {
fmt.Println()
log.Warnf("The .app file generated for 'i386 + x86_64' architecture")
is64Bit, err := simulator.Is64BitArchitecture(configs.SimulatorDevice)
if err != nil {
registerFail("Failed to check simulator architecture, error: %s", err)
}
log.Warnf("Simulator is 64-bit architecture: %v", is64Bit)
tmpDir, err := pathutil.NormalizedOSTempDirPath("_calabash_ios_")
if err != nil {
registerFail("Failed to create tmp dir, error: %s", err)
}
appName := filepath.Base(configs.AppPath)
newAppPath := filepath.Join(tmpDir, appName)
log.Warnf("Creating compatible .app file at: %s", newAppPath)
if err := command.CopyDir(configs.AppPath, tmpDir, false); err != nil {
registerFail("Failed to copy .app to (%s), error: %s", newAppPath, err)
}
newAppMonotouch32Dir := filepath.Join(newAppPath, ".monotouch-32")
newAppMonotouch64Dir := filepath.Join(newAppPath, ".monotouch-64")
if is64Bit {
log.Warnf("Copy files from .monotouch-64 dir...")
if err := command.CopyDir(newAppMonotouch64Dir, newAppPath, true); err != nil {
registerFail("Failed to copy .monotouch-64 files, error: %s", err)
}
} else {
log.Warnf("Copy files from .monotouch-32 dir...")
if err := command.CopyDir(newAppMonotouch32Dir, newAppPath, true); err != nil {
registerFail("Failed to copy .monotouch-32 files, error: %s", err)
}
}
configs.AppPath = newAppPath
}
}
// ---
//
// Determining calabash-cucumber version
fmt.Println()
log.Infof("Determining calabash-cucumber version...")
workDir, err := pathutil.AbsPath(configs.WorkDir)
if err != nil {
registerFail("Failed to expand WorkDir (%s), error: %s", configs.WorkDir, err)
}
gemFilePath := ""
if configs.GemFilePath != "" {
gemFilePath, err = pathutil.AbsPath(configs.GemFilePath)
if err != nil {
registerFail("Failed to expand GemFilePath (%s), error: %s", configs.GemFilePath, err)
}
}
useBundler := false
if gemFilePath != "" {
if exist, err := pathutil.IsPathExists(gemFilePath); err != nil {
registerFail("Failed to check if Gemfile exists at (%s) exist, error: %s", gemFilePath, err)
} else if exist {
log.Printf("Gemfile exists at: %s", gemFilePath)
gemfileDir := filepath.Dir(gemFilePath)
gemfileLockPth := filepath.Join(gemfileDir, "Gemfile.lock")
if exist, err := pathutil.IsPathExists(gemfileLockPth); err != nil {
registerFail("Failed to check if Gemfile.lock exists at (%s), error: %s", gemfileLockPth, err)
} else if exist {
log.Printf("Gemfile.lock exists at: %s", gemfileLockPth)
version, err := calabashCucumberVersionFromGemfileLock(gemfileLockPth)
if err != nil {
registerFail("Failed to get calabash-cucumber version from Gemfile.lock, error: %s", err)
}
log.Printf("calabash-cucumber version in Gemfile.lock: %s", version)
useBundler = true
} else {
log.Warnf("Gemfile.lock doest no find with calabash-cucumber gem at: %s", gemfileLockPth)
}
} else {
log.Warnf("Gemfile doest no find with calabash-cucumber gem at: %s", gemFilePath)
}
}
if configs.CalabashCucumberVersion != "" {
log.Donef("using calabash-cucumber version: %s", configs.CalabashCucumberVersion)
} else if useBundler {
log.Donef("using calabash-cucumber with bundler")
} else {
log.Donef("using calabash-cucumber latest version")
}
// ---
//
// Intsalling cucumber gem
fmt.Println()
log.Infof("Installing calabash-cucumber...")
if configs.CalabashCucumberVersion != "" {
installed, err := rubycommand.IsGemInstalled("calabash-cucumber", configs.CalabashCucumberVersion)
if err != nil {
registerFail("Failed to check if calabash-cucumber (v%s) installed, error: %s", configs.CalabashCucumberVersion, err)
}
if !installed {
installCommands, err := rubycommand.GemInstall("calabash-cucumber", configs.CalabashCucumberVersion, false)
if err != nil {
registerFail("Failed to create gem install commands, error: %s", err)
}
for _, installCommand := range installCommands {
log.Printf("$ %s", installCommand.PrintableCommandArgs())
installCommand.SetStdout(os.Stdout).SetStderr(os.Stderr)
if err := installCommand.Run(); err != nil {
registerFail("command failed, error: %s", err)
}
}
} else {
log.Printf("calabash-cucumber %s installed", configs.CalabashCucumberVersion)
}
} else if useBundler {
bundleInstallCmd, err := rubycommand.New("bundle", "install", "--jobs", "20", "--retry", "5")
if err != nil {
registerFail("Failed to create command, error: %s", err)
}
bundleInstallCmd.AppendEnvs("BUNDLE_GEMFILE=" + gemFilePath)
bundleInstallCmd.SetStdout(os.Stdout).SetStderr(os.Stderr)
log.Printf("$ %s", bundleInstallCmd.PrintableCommandArgs())
if err := bundleInstallCmd.Run(); err != nil {
registerFail("bundle install failed, error: %s", err)
}
} else {
installCommands, err := rubycommand.GemInstall("calabash-cucumber", "", false)
if err != nil {
registerFail("Failed to create gem install commands, error: %s", err)
}
for _, installCommand := range installCommands {
log.Printf("$ %s", installCommand.PrintableCommandArgs())
installCommand.SetStdout(os.Stdout).SetStderr(os.Stderr)
if err := installCommand.Run(); err != nil {
registerFail("command failed, error: %s", err)
}
}
}
//
// Run cucumber
fmt.Println()
log.Infof("Running cucumber test...")
cucumberEnvs := []string{"DEVICE_TARGET=" + simulatorInfo.ID}
if configs.AppPath != "" {
cucumberEnvs = append(cucumberEnvs, "APP="+configs.AppPath)
}
cucumberArgs := []string{"cucumber"}
if configs.CalabashCucumberVersion != "" {
cucumberArgs = append(cucumberArgs, fmt.Sprintf("_%s_", configs.CalabashCucumberVersion))
} else if useBundler {
cucumberArgs = append([]string{"bundle", "exec"}, cucumberArgs...)
cucumberEnvs = append(cucumberEnvs, "BUNDLE_GEMFILE="+gemFilePath)
}
cucumberArgs = append(cucumberArgs, options...)
cucumberCmd, err := rubycommand.NewFromSlice(cucumberArgs)
if err != nil {
registerFail("Failed to create command, error: %s", err)
}
cucumberCmd.AppendEnvs(cucumberEnvs...)
cucumberCmd.SetDir(workDir)
cucumberCmd.SetStdout(os.Stdout).SetStderr(os.Stderr)
log.Printf("$ %s", cucumberCmd.PrintableCommandArgs())
fmt.Println()
if err := cucumberCmd.Run(); err != nil {
fmt.Println()
log.Errorf("Failed to run command, error: %s", err)
if err := exportEnvironmentWithEnvman("BITRISE_XAMARIN_TEST_RESULT", "failed"); err != nil {
log.Warnf("Failed to export environment: %s, error: %s", "BITRISE_XAMARIN_TEST_RESULT", err)
}
// find --out flag and get the next index containing output file's pth
outputFilePth := ""
if index := indexInStringSlice("--out", options); index != -1 {
outputFilePth = options[index+1]
}
if outputFilePth == "" {
os.Exit(1)
}
// if --out is BITRISE_DEPLOY_DIR, print Deploy to bitrise.io step usage
if filepath.Dir(outputFilePth) == os.Getenv("BITRISE_DEPLOY_DIR") {
log.Printf("Use Deploy to bitrise.io step to attach report file (%s) to your build artifacts.", outputFilePth)
} else {
log.Printf("The generated report file is available at: %s", outputFilePth)
}
fmt.Println()
// read output file
outputFileContent, err := fileutil.ReadStringFromFile(outputFilePth)
if err != nil {
registerFail("Failed to read output file (%s), error: %s", outputFilePth, err)
}
// check if output format is html
if index := indexInStringSlice("--format", options); index != -1 && (options[index+1] == "html") {
// regex messages from output html and avoid duplicating messages
outputs := []string{}
exp := regexp.MustCompile(`<div class="message"><pre>(?s)(.*?)</pre></div>`)
for _, match := range exp.FindAllStringSubmatch(outputFileContent, -1) {
if len(match) > 1 {
if index := indexInStringSlice(match[1], outputs); index == -1 {
log.Printf(match[1])
outputs = append(outputs, match[1])
}
}
}
os.Exit(1)
}
// output isn't html, print file content
log.Printf(outputFileContent)
os.Exit(1)
}
// ---
if err := exportEnvironmentWithEnvman("BITRISE_XAMARIN_TEST_RESULT", "succeeded"); err != nil {
log.Warnf("Failed to export environment: %s, error: %s", "BITRISE_XAMARIN_TEST_RESULT", err)
}
}
| {
"content_hash": "5415ed80a377c962cbce02e86b620db6",
"timestamp": "",
"source": "github",
"line_count": 482,
"max_line_length": 120,
"avg_line_length": 29.6597510373444,
"alnum_prop": 0.6885842193620593,
"repo_name": "bitrise-steplib/steps-calabash-ios-uitest",
"id": "e823d0e74a8b34750d1877a50bb3895a60ff2e71",
"size": "14296",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "main.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "14331"
},
{
"name": "Shell",
"bytes": "453"
}
],
"symlink_target": ""
} |
class Game_Notice
{
enum class Slide_State
{
Slide_In,
Slide_Out,
Slided
};
public:
Game_Notice();
void setString (std::string message);
void toggleOn ();
void update();
bool canDraw () const;
void draw ();
private:
sf::RectangleShape m_sprite;
sf::Text m_text;
bool m_canDraw;
sf::Clock m_timer;
};
#endif // GAME_NOTICE_H_INCLUDED
| {
"content_hash": "b249af1c938b4187be8c8cf9279f33e2",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 46,
"avg_line_length": 15.34375,
"alnum_prop": 0.48065173116089616,
"repo_name": "Hopson97/Hero",
"id": "f47df1e265fa00fb64ebdfa73851e456f7833075",
"size": "584",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/Game/Game_Notice.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "170"
},
{
"name": "C++",
"bytes": "87485"
},
{
"name": "CMake",
"bytes": "14114"
},
{
"name": "Shell",
"bytes": "762"
}
],
"symlink_target": ""
} |
package nl.sense_os.commonsense.main.client.sensors;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceTokenizer;
import com.google.gwt.place.shared.Prefix;
public class SensorsPlace extends Place {
/**
* PlaceTokenizer knows how to serialize the Place's state to a URL token.
*/
@Prefix("sensors")
public static class Tokenizer implements PlaceTokenizer<SensorsPlace> {
@Override
public SensorsPlace getPlace(String token) {
return new SensorsPlace(token);
}
@Override
public String getToken(SensorsPlace place) {
return place.getToken();
}
}
private String token;
public SensorsPlace() {
this("");
}
public SensorsPlace(String token) {
this.token = token;
}
public String getToken() {
return this.token;
}
}
| {
"content_hash": "eb634f854af6472890591bd60049ac98",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 75,
"avg_line_length": 20.256410256410255,
"alnum_prop": 0.730379746835443,
"repo_name": "senseobservationsystems/commonsense-frontend",
"id": "d9107b3a08ed6011affce429e0d3a49c0efa7b8f",
"size": "790",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/nl/sense_os/commonsense/main/client/sensors/SensorsPlace.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "292534"
},
{
"name": "Java",
"bytes": "910953"
},
{
"name": "Nu",
"bytes": "45"
},
{
"name": "PHP",
"bytes": "74660"
}
],
"symlink_target": ""
} |
""" Framework for filtered REST requests
@copyright: 2013-14 (c) Sahana Software Foundation
@license: MIT
@requires: U{B{I{gluon}} <http://web2py.com>}
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 AUTHORS OR COPYRIGHT
HOLDERS 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.
"""
__all__ = ("S3DateFilter",
"S3Filter",
"S3FilterForm",
"S3FilterString",
"S3FilterWidget",
"S3HierarchyFilter",
"S3LocationFilter",
"S3OptionsFilter",
"S3RangeFilter",
"S3TextFilter",
"get_s3_filter_opts",
)
import datetime
import re
try:
import json # try stdlib (Python 2.6)
except ImportError:
try:
import simplejson as json # try external module
except:
import gluon.contrib.simplejson as json # fallback to pure-Python module
try:
# Python 2.7
from collections import OrderedDict
except:
# Python 2.6
from gluon.contrib.simplejson.ordered_dict import OrderedDict
from gluon import *
from gluon.storage import Storage
from gluon.tools import callback
from s3rest import S3Method
from s3query import S3ResourceField, S3ResourceQuery, S3URLQuery
from s3utils import s3_get_foreign_key, s3_unicode, S3TypeConverter
from s3validators import *
from s3widgets import S3DateWidget, S3DateTimeWidget, S3GroupedOptionsWidget, S3MultiSelectWidget, S3HierarchyWidget
# Compact JSON encoding
SEPARATORS = (",", ":")
# =============================================================================
def get_s3_filter_opts(tablename,
fieldname = "name",
location_filter = False,
org_filter = False,
none = False,
translate = False,
):
"""
Lazy options getter
- this is useful when the expected number of options is significantly smaller than the number of records to iterate through
NB This reason is no longer required with S3Filter, but is a legacy from S3Search: S3Filter already does an efficient Reverse-Query
@ToDo: Deprecate
- note this doesn't check if options are actually in-use
@param tablename: the name of the lookup table
@param fieldname: the name of the field to represent options with
@param location_filter: whether to filter the values by location
@param org_filter: whether to filter the values by root_org
@param none: whether to include an option for None
@param translate: whether to translate the values
"""
auth = current.auth
table = current.s3db.table(tablename)
if auth.s3_has_permission("read", table):
query = auth.s3_accessible_query("read", table)
if location_filter:
location = current.session.s3.location_filter
if location:
query &= (table.location_id == location)
if org_filter:
root_org = auth.root_org()
if root_org:
query &= ((table.organisation_id == root_org) | \
(table.organisation_id == None))
#else:
# query &= (table.organisation_id == None)
rows = current.db(query).select(table.id,
table[fieldname],
# Options are sorted later
#orderby = table[fieldname]
)
if translate:
T = current.T
opts = dict((row.id, T(row[fieldname])) for row in rows)
else:
opts = dict((row.id, row[fieldname]) for row in rows)
if none:
opts[None] = current.messages["NONE"]
else:
opts = {}
return opts
# =============================================================================
class S3FilterWidget(object):
""" Filter widget for interactive search forms (base class) """
#: the HTML class for the widget type
_class = "generic-filter"
#: the default query operator(s) for the widget type
operator = None
#: alternatives for client-side changeable operators
alternatives = None
# -------------------------------------------------------------------------
def widget(self, resource, values):
"""
Prototype method to render this widget as an instance of
a web2py HTML helper class, to be implemented by subclasses.
@param resource: the S3Resource to render with widget for
@param values: the values for this widget from the URL query
"""
raise NotImplementedError
# -------------------------------------------------------------------------
def variable(self, resource, get_vars=None):
"""
Prototype method to generate the name for the URL query variable
for this widget, can be overwritten in subclasses.
@param resource: the resource
@return: the URL query variable name (or list of
variable names if there are multiple operators)
"""
label, self.selector = self._selector(resource, self.field)
if not self.selector:
return None
if self.alternatives and get_vars is not None:
# Get the actual operator from get_vars
operator = self._operator(get_vars, self.selector)
if operator:
self.operator = operator
if "label" not in self.opts:
self.opts["label"] = label
return self._variable(self.selector, self.operator)
# -------------------------------------------------------------------------
def data_element(self, variable):
"""
Prototype method to construct the hidden element that holds the
URL query term corresponding to an input element in the widget.
@param variable: the URL query variable
"""
if type(variable) is list:
variable = "&".join(variable)
return INPUT(_type="hidden",
_id="%s-data" % self.attr["_id"],
_class="filter-widget-data %s-data" % self._class,
_value=variable)
# -------------------------------------------------------------------------
# Helper methods
#
def __init__(self, field=None, **attr):
"""
Constructor to configure the widget
@param field: the selector(s) for the field(s) to filter by
@param attr: configuration options for this widget
Configuration options:
@keyword label: label for the widget
@keyword comment: comment for the widget
@keyword hidden: render widget initially hidden (="advanced"
option)
@keyword levels: list of location hierarchy levels
(L{S3LocationFilter})
@keyword widget: widget to use (L{S3OptionsFilter}),
"select", "multiselect" (default),
or "groupedopts"
@keyword cols: number of columns of checkboxes (L{S3OptionsFilter}
and L{S3LocationFilter} with "groupedopts" widget)
@keyword filter: show filter for options (L{S3OptionsFilter},
L{S3LocationFilter} with "multiselect" widget)
@keyword header: show header in widget (L{S3OptionsFilter},
L{S3LocationFilter} with "multiselect" widget)
@keyword selectedList: number of selected items to show before
collapsing into number of items
(L{S3OptionsFilter}, L{S3LocationFilter}
with "multiselect" widget)
@keyword no_opts: text to show if no options available
(L{S3OptionsFilter}, L{S3LocationFilter})
@keyword resource: alternative resource to look up options
(L{S3LocationFilter}, L{S3OptionsFilter})
@keyword lookup: field in the alternative resource to look up
options (L{S3LocationFilter})
@keyword options: fixed set of options (L{S3OptionsFilter}: dict
of {value: label} or a callable that returns one,
L{S3LocationFilter}: list of gis_location IDs)
@keyword size: maximum size of multi-letter options groups
(L{S3OptionsFilter} with "groupedopts" widget)
@keyword help_field: field in the referenced table to display on
hovering over a foreign key option
(L{S3OptionsFilter} with "groupedopts" widget)
@keyword none: label for explicit None-option in many-to-many
fields (L{S3OptionsFilter})
@keyword fieldtype: explicit field type "date" or "datetime" to
use for context or virtual fields
(L{S3DateFilter})
@keyword hide_time: don't show time selector (L{S3DateFilter})
"""
self.field = field
self.alias = None
attributes = Storage()
options = Storage()
for k, v in attr.iteritems():
if k[0] == "_":
attributes[k] = v
else:
options[k] = v
self.attr = attributes
self.opts = options
self.selector = None
self.values = Storage()
# -------------------------------------------------------------------------
def __call__(self, resource, get_vars=None, alias=None):
"""
Entry point for the form builder
@param resource: the S3Resource to render the widget for
@param get_vars: the GET vars (URL query vars) to prepopulate
the widget
@param alias: the resource alias to use
"""
self.alias = alias
# Initialize the widget attributes
self._attr(resource)
# Extract the URL values to populate the widget
variable = self.variable(resource, get_vars)
if type(variable) is list:
values = Storage()
for k in variable:
if k in self.values:
values[k] = self.values[k]
else:
values[k] = self._values(get_vars, k)
else:
if variable in self.values:
values = self.values[variable]
else:
values = self._values(get_vars, variable)
# Construct and populate the widget
widget = self.widget(resource, values)
# Recompute variable in case operator got changed in widget()
if self.alternatives:
variable = self._variable(self.selector, self.operator)
# Construct the hidden data element
data = self.data_element(variable)
if type(data) is list:
data.append(widget)
else:
data = [data, widget]
return TAG[""](*data)
# -------------------------------------------------------------------------
def _attr(self, resource):
""" Initialize and return the HTML attributes for this widget """
_class = self._class
# Construct name and id for the widget
attr = self.attr
if "_name" not in attr:
if not resource:
raise SyntaxError("%s: _name parameter required " \
"when rendered without resource." % \
self.__class__.__name__)
flist = self.field
if type(flist) is not list:
flist = [flist]
colnames = []
for f in flist:
rfield = S3ResourceField(resource, f)
colname = rfield.colname
if colname:
colnames.append(colname)
else:
colnames.append(rfield.fname)
name = "%s-%s-%s" % (resource.alias, "-".join(colnames), _class)
attr["_name"] = name.replace(".", "_")
if "_id" not in attr:
attr["_id"] = attr["_name"]
return attr
# -------------------------------------------------------------------------
@classmethod
def _operator(cls, get_vars, selector):
"""
Helper method to get the operators from the URL query
@param get_vars: the GET vars (a dict)
@param selector: field selector
@return: query operator - None, str or list
"""
variables = ["%s__%s" % (selector, op) for op in cls.alternatives]
slen = len(selector) + 2
operators = [k[slen:] for k, v in get_vars.iteritems()
if k in variables]
if not operators:
return None
elif len(operators) == 1:
return operators[0]
else:
return operators
# -------------------------------------------------------------------------
def _prefix(self, selector):
"""
Helper method to prefix an unprefixed field selector
@param alias: the resource alias to use as prefix
@param selector: the field selector
@return: the prefixed selector
"""
alias = self.alias
if alias is None:
alias = "~"
if "." not in selector.split("$", 1)[0]:
return "%s.%s" % (alias, selector)
else:
return selector
# -------------------------------------------------------------------------
def _selector(self, resource, fields):
"""
Helper method to generate a filter query selector for the
given field(s) in the given resource.
@param resource: the S3Resource
@param fields: the field selectors (as strings)
@return: the field label and the filter query selector, or None
if none of the field selectors could be resolved
"""
prefix = self._prefix
label = None
if not fields:
return label, None
if not isinstance(fields, (list, tuple)):
fields = [fields]
selectors = []
for field in fields:
if resource:
try:
rfield = S3ResourceField(resource, field)
except (AttributeError, TypeError):
continue
if not rfield.field and not rfield.virtual:
# Unresolvable selector
continue
if not label:
label = rfield.label
selectors.append(prefix(rfield.selector))
else:
selectors.append(field)
if selectors:
return label, "|".join(selectors)
else:
return label, None
# -------------------------------------------------------------------------
@staticmethod
def _values(get_vars, variable):
"""
Helper method to get all values of a URL query variable
@param get_vars: the GET vars (a dict)
@param variable: the name of the query variable
@return: a list of values
"""
if not variable:
return []
elif variable in get_vars:
values = S3URLQuery.parse_value(get_vars[variable])
if not isinstance(values, (list, tuple)):
values = [values]
return values
else:
return []
# -------------------------------------------------------------------------
@classmethod
def _variable(cls, selector, operator):
"""
Construct URL query variable(s) name from a filter query
selector and the given operator(s)
@param selector: the selector
@param operator: the operator (or tuple/list of operators)
@return: the URL query variable name (or list of variable names)
"""
if isinstance(operator, (tuple, list)):
return [cls._variable(selector, o) for o in operator]
elif operator:
return "%s__%s" % (selector, operator)
else:
return selector
# =============================================================================
class S3TextFilter(S3FilterWidget):
""" Text filter widget """
_class = "text-filter"
operator = "like"
# -------------------------------------------------------------------------
def widget(self, resource, values):
"""
Render this widget as HTML helper object(s)
@param resource: the resource
@param values: the search values from the URL query
"""
attr = self.attr
if "_size" not in attr:
attr.update(_size="40")
if "_class" in attr and attr["_class"]:
_class = "%s %s" % (attr["_class"], self._class)
else:
_class = self._class
attr["_class"] = _class
attr["_type"] = "text"
values = [v.strip("*") for v in values if v is not None]
if values:
attr["_value"] = " ".join(values)
return INPUT(**attr)
# =============================================================================
class S3RangeFilter(S3FilterWidget):
""" Numerical Range Filter Widget """
# Overall class
_class = "range-filter"
# Class for visible input boxes.
_input_class = "%s-%s" % (_class, "input")
operator = ["ge", "le"]
# Untranslated labels for individual input boxes.
input_labels = {"ge": "Minimum", "le": "Maximum"}
# -------------------------------------------------------------------------
def data_element(self, variables):
"""
Overrides S3FilterWidget.data_element(), constructs multiple
hidden INPUTs (one per variable) with element IDs of the form
<id>-<operator>-data (where no operator is translated as "eq").
@param variables: the variables
"""
if variables is None:
operators = self.operator
if type(operators) is not list:
operators = [operators]
variables = self._variable(self.selector, operators)
else:
# Split the operators off the ends of the variables.
if type(variables) is not list:
variables = [variables]
operators = [v.split("__")[1]
if "__" in v else "eq"
for v in variables]
elements = []
id = self.attr["_id"]
for o, v in zip(operators, variables):
elements.append(
INPUT(_type="hidden",
_id="%s-%s-data" % (id, o),
_class="filter-widget-data %s-data" % self._class,
_value=v))
return elements
# -------------------------------------------------------------------------
def widget(self, resource, values):
"""
Render this widget as HTML helper object(s)
@param resource: the resource
@param values: the search values from the URL query
"""
attr = self.attr
_class = self._class
if "_class" in attr and attr["_class"]:
_class = "%s %s" % (attr["_class"], _class)
else:
_class = _class
attr["_class"] = _class
input_class = self._input_class
input_labels = self.input_labels
input_elements = DIV()
ie_append = input_elements.append
selector = self.selector
_variable = self._variable
id = attr["_id"]
for operator in self.operator:
input_id = "%s-%s" % (id, operator)
input_box = INPUT(_name=input_id,
_id=input_id,
_type="text",
_class=input_class)
variable = _variable(selector, operator)
# Populate with the value, if given
# if user has not set any of the limits, we get [] in values.
value = values.get(variable, None)
if value not in [None, []]:
if type(value) is list:
value = value[0]
input_box["_value"] = value
input_box["value"] = value
ie_append(DIV(
DIV(LABEL(current.T(input_labels[operator] + ":"),
_for=input_id),
_class="range-filter-label"),
DIV(input_box,
_class="range-filter-widget"),
_class="range-filter-field"))
return input_elements
# =============================================================================
class S3DateFilter(S3RangeFilter):
"""
Date Range Filter Widget
@see: L{Configuration Options<S3FilterWidget.__init__>}
"""
_class = "date-filter"
# Class for visible input boxes.
_input_class = "%s-%s" % (_class, "input")
operator = ["ge", "le"]
# Untranslated labels for individual input boxes.
input_labels = {"ge": "From", "le": "To"}
# -------------------------------------------------------------------------
def widget(self, resource, values):
"""
Render this widget as HTML helper object(s)
@param resource: the resource
@param values: the search values from the URL query
"""
attr = self.attr
# CSS class and element ID
_class = self._class
if "_class" in attr and attr["_class"]:
_class = "%s %s" % (attr["_class"], _class)
else:
_class = _class
_id = attr["_id"]
# Determine the field type
if resource:
rfield = S3ResourceField(resource, self.field)
field = rfield.field
else:
rfield = field = None
if not field:
if not rfield or rfield.virtual:
ftype = self.opts.get("fieldtype", "datetime")
else:
# Unresolvable selector
return ""
else:
ftype = rfield.ftype
if not field:
# S3DateTimeWidget requires a Field
if rfield:
tname, fname = rfield.tname, rfield.fname
else:
tname, fname = "notable", "datetime"
if not _id:
raise SyntaxError("%s: _id parameter required " \
"when rendered without resource." % \
self.__class__.__name__)
dtformat = current.deployment_settings.get_L10n_date_format()
field = Field(fname, ftype,
requires = IS_DATE_IN_RANGE(format = dtformat))
field.tablename = field._tablename = tname
# Options
hide_time = self.opts.get("hide_time", False)
# Generate the input elements
T = current.T
selector = self.selector
_variable = self._variable
input_class = self._input_class
input_labels = self.input_labels
input_elements = DIV(_id=_id, _class=_class)
append = input_elements.append
for operator in self.operator:
input_id = "%s-%s" % (_id, operator)
# Determine the widget class
if ftype == "date":
widget = S3DateWidget()
else:
opts = {}
if operator == "ge":
opts["set_min"] = "%s-%s" % (_id, "le")
elif operator == "le":
opts["set_max"] = "%s-%s" % (_id, "ge")
widget = S3DateTimeWidget(hide_time=hide_time, **opts)
# Populate with the value, if given
# if user has not set any of the limits, we get [] in values.
variable = _variable(selector, operator)
value = values.get(variable, None)
if value not in [None, []]:
if type(value) is list:
value = value[0]
else:
value = None
# Render the widget
picker = widget(field, value,
_name=input_id,
_id=input_id,
_class=input_class)
# Append label and widget
append(DIV(
DIV(LABEL("%s:" % T(input_labels[operator]),
_for=input_id),
_class="range-filter-label"),
DIV(picker,
_class="range-filter-widget"),
_class="range-filter-field"))
return input_elements
# =============================================================================
class S3LocationFilter(S3FilterWidget):
"""
Hierarchical Location Filter Widget
@see: L{Configuration Options<S3FilterWidget.__init__>}
NB This will show records linked to all child locations of the Lx
"""
_class = "location-filter"
operator = "belongs"
# -------------------------------------------------------------------------
def __init__(self, field=None, **attr):
"""
Constructor to configure the widget
@param field: the selector(s) for the field(s) to filter by
@param attr: configuration options for this widget
"""
if not field:
field = "location_id"
# Translate options using gis_location_name?
settings = current.deployment_settings
translate = settings.get_L10n_translate_gis_location()
if translate:
language = current.session.s3.language
if language == settings.get_L10n_default_language():
translate = False
self.translate = translate
super(S3LocationFilter, self).__init__(field=field, **attr)
# -------------------------------------------------------------------------
def widget(self, resource, values):
"""
Render this widget as HTML helper object(s)
@param resource: the resource
@param values: the search values from the URL query
"""
attr = self._attr(resource)
opts = self.opts
name = attr["_name"]
ftype, levels, noopt = self._options(resource, values=values)
if noopt:
return SPAN(noopt, _class="no-options-available")
# Filter class (default+custom)
_class = self._class
if "_class" in attr and attr["_class"]:
_class = "%s %s" % (_class, attr["_class"])
attr["_class"] = _class
# Store id and name for the data element
base_id = attr["_id"]
base_name = attr["_name"]
widgets = []
w_append = widgets.append
operator = self.operator
field_name = self.field
fname = self._prefix(field_name) if resource else field_name
#widget_type = opts["widget"]
# Use groupedopts widget if we specify cols, otherwise assume multiselect
cols = opts.get("cols", None)
if cols:
# Grouped Checkboxes
# @ToDo: somehow working, but ugly, not usable (deprecated?)
if "groupedopts-filter-widget" not in _class:
attr["_class"] = "%s groupedopts-filter-widget" % _class
attr["cols"] = cols
# Add one widget per level
for level in levels:
options = levels[level]["options"]
groupedopts = S3GroupedOptionsWidget(cols = cols,
size = opts["size"] or 12,
)
# Dummy field
name = "%s-%s" % (base_name, level)
dummy_field = Storage(name=name,
type=ftype,
requires=IS_IN_SET(options,
multiple=True))
# Unique ID/name
attr["_id"] = "%s-%s" % (base_id, level)
attr["_name"] = name
# Find relevant values to pre-populate
_values = values.get("%s$%s__%s" % (fname, level, operator))
w_append(groupedopts(dummy_field, _values, **attr))
else:
# Multiselect is default
T = current.T
# Multiselect Dropdown with Checkboxes
if "multiselect-filter-widget" not in _class:
_class = "%s multiselect-filter-widget" % _class
# Add one widget per level
first = True
hide = True
for level in levels:
# Dummy field
name = "%s-%s" % (base_name, level)
options = levels[level]["options"]
dummy_field = Storage(name=name,
type=ftype,
requires=IS_IN_SET(options,
multiple=True))
# Unique ID/name
attr["_id"] = "%s-%s" % (base_id, level)
attr["_name"] = name
# Find relevant values to pre-populate the widget
_values = values.get("%s$%s__%s" % (fname, level, operator))
w = S3MultiSelectWidget(filter = opts.get("filter", "auto"),
header = opts.get("header", False),
selectedList = opts.get("selectedList", 3),
noneSelectedText = T("Select %(location)s") % \
dict(location=levels[level]["label"]))
if first:
attr["_class"] = _class
elif hide:
# Hide dropdowns other than first
_class = "%s hide" % _class
attr["_class"] = _class
hide = False
widget = w(dummy_field, _values, **attr)
w_append(widget)
first = False
# Restore id and name for the data_element
attr["_id"] = base_id
attr["_name"] = base_name
# Render the filter widget
return TAG[""](*widgets)
# -------------------------------------------------------------------------
def data_element(self, variable):
"""
Construct the hidden element that holds the
URL query term corresponding to an input element in the widget.
@param variable: the URL query variable
"""
output = []
oappend = output.append
i = 0
for level in self.levels:
widget = INPUT(_type="hidden",
_id="%s-%s-data" % (self.attr["_id"], level),
_class="filter-widget-data %s-data" % self._class,
_value=variable[i])
oappend(widget)
i += 1
return output
# -------------------------------------------------------------------------
def ajax_options(self, resource):
attr = self._attr(resource)
ftype, levels, noopt = self._options(resource, inject_hierarchy=False)
opts = {}
base_id = attr["_id"]
for level in levels:
if noopt:
opts["%s-%s" % (base_id, level)] = str(noopt)
else:
options = levels[level]["options"]
opts["%s-%s" % (base_id, level)] = options
return opts
# -------------------------------------------------------------------------
@staticmethod
def __options(row, levels, inject_hierarchy, hierarchy, _level, translate, name_l10n):
if inject_hierarchy:
parent = None
grandparent = None
greatgrandparent = None
greatgreatgrandparent = None
greatgreatgreatgrandparent = None
i = 0
for level in levels:
v = row[level]
if v:
o = levels[level]["options"]
if v not in o:
if translate:
o[v] = name_l10n.get(v, v)
else:
o.append(v)
if inject_hierarchy:
if i == 0:
h = hierarchy[_level]
if v not in h:
h[v] = {}
parent = v
elif i == 1:
h = hierarchy[_level][parent]
if v not in h:
h[v] = {}
grandparent = parent
parent = v
elif i == 2:
h = hierarchy[_level][grandparent][parent]
if v not in h:
h[v] = {}
greatgrandparent = grandparent
grandparent = parent
parent = v
elif i == 3:
h = hierarchy[_level][greatgrandparent][grandparent][parent]
if v not in h:
h[v] = {}
greatgreatgrandparent = greatgrandparent
greatgrandparent = grandparent
grandparent = parent
parent = v
elif i == 4:
h = hierarchy[_level][greatgreatgrandparent][greatgrandparent][grandparent][parent]
if v not in h:
h[v] = {}
greatgreatgreatgrandparent = greatgreatgrandparent
greatgreatgrandparent = greatgrandparent
greatgrandparent = grandparent
grandparent = parent
parent = v
elif i == 5:
h = hierarchy[_level][greatgreatgreatgrandparent][greatgreatgrandparent][greatgrandparent][grandparent][parent]
if v not in h:
h[v] = {}
i += 1
# -------------------------------------------------------------------------
def _options(self, resource, inject_hierarchy=True, values=None):
T = current.T
s3db = current.s3db
gtable = s3db.gis_location
NOOPT = T("No options available")
#attr = self.attr
opts = self.opts
translate = self.translate
# Which levels should we display?
# Lookup the appropriate labels from the GIS configuration
if "levels" in opts:
hierarchy = current.gis.get_location_hierarchy()
levels = OrderedDict()
for level in opts["levels"]:
levels[level] = hierarchy.get(level, level)
else:
levels = current.gis.get_relevant_hierarchy_levels(as_dict=True)
# Pass to data_element
self.levels = levels
if "label" not in opts:
opts["label"] = T("Filter by Location")
ftype = "reference gis_location"
default = (ftype, levels.keys(), opts.get("no_opts", NOOPT))
# Resolve the field selector
selector = None
if resource is None:
rname = opts.get("resource")
if rname:
resource = s3db.resource(rname)
selector = opts.get("lookup", "location_id")
else:
selector = self.field
options = opts.get("options")
if options:
# Fixed options (=list of location IDs)
resource = s3db.resource("gis_location", id=options)
fields = ["id"] + [l for l in levels]
if translate:
fields.append("path")
joined = False
elif selector:
# Lookup options from resource
rfield = S3ResourceField(resource, selector)
if not rfield.field or rfield.ftype != ftype:
# Must be a real reference to gis_location
return default
fields = [selector] + ["%s$%s" % (selector, l) for l in levels]
if translate:
fields.append("%s$path" % selector)
joined = True
# Filter out old Locations
# @ToDo: Allow override
resource.add_filter(gtable.end_date == None)
else:
# Neither fixed options nor resource to look them up
return default
# Find the options
rows = resource.select(fields=fields,
limit=None,
virtual=False,
as_rows=True)
rows2 = []
if not rows:
if values:
# Make sure the selected options are in the available options
resource = s3db.resource("gis_location")
fields = ["id"] + [l for l in levels]
if translate:
fields.append("path")
joined = False
rows = []
for f in values:
v = values[f]
if not v:
continue
level = "L%s" % f.split("L", 1)[1][0]
resource.clear_query()
query = (gtable.level == level) & \
(gtable.name.belongs(v))
resource.add_filter(query)
# Filter out old Locations
# @ToDo: Allow override
resource.add_filter(gtable.end_date == None)
_rows = resource.select(fields=fields,
limit=None,
virtual=False,
as_rows=True)
if rows:
rows &= _rows
else:
rows = _rows
if not rows:
# No options
return default
elif values:
# Make sure the selected options are in the available options
resource2 = s3db.resource("gis_location")
fields = ["id"] + [l for l in levels]
if translate:
fields.append("path")
for f in values:
v = values[f]
if not v:
continue
level = "L%s" % f.split("L", 1)[1][0]
resource2.clear_query()
query = (gtable.level == level) & \
(gtable.name.belongs(v))
resource2.add_filter(query)
# Filter out old Locations
# @ToDo: Allow override
resource2.add_filter(gtable.end_date == None)
_rows = resource2.select(fields=fields,
limit=None,
virtual=False,
as_rows=True)
if rows2:
rows2 &= _rows
else:
rows2 = _rows
# Initialise Options Storage & Hierarchy
hierarchy = {}
first = True
for level in levels:
if first:
hierarchy[level] = {}
_level = level
first = False
levels[level] = {"label": levels[level],
"options": {} if translate else [],
}
# Generate a name localization lookup dict
name_l10n = {}
if translate:
# Get IDs via Path to lookup name_l10n
ids = set()
if joined:
if "$" in selector:
selector = "%s.%s" % (rfield.field.tablename, selector.split("$", 1)[1])
elif "." in selector:
selector = "%s.%s" % (rfield.field.tablename, selector.split(".", 1)[1])
else:
selector = "%s.%s" % (resource.tablename, selector)
for row in rows:
_row = getattr(row, "gis_location") if joined else row
path = _row.path
if path:
path = path.split("/")
else:
# Build it
if joined:
location_id = row[selector]
if location_id:
_row.id = location_id
if "id" in _row:
path = current.gis.update_location_tree(_row)
path = path.split("/")
if path:
ids |= set(path)
for row in rows2:
path = row.path
if path:
path = path.split("/")
else:
# Build it
if "id" in row:
path = current.gis.update_location_tree(row)
path = path.split("/")
if path:
ids |= set(path)
# Build lookup table for name_l10n
ntable = s3db.gis_location_name
query = (gtable.id.belongs(ids)) & \
(ntable.deleted == False) & \
(ntable.location_id == gtable.id) & \
(ntable.language == current.session.s3.language)
nrows = current.db(query).select(gtable.name,
ntable.name_l10n,
limitby=(0, len(ids)),
)
for row in nrows:
name_l10n[row["gis_location.name"]] = row["gis_location_name.name_l10n"]
# Populate the Options and the Hierarchy
for row in rows:
_row = getattr(row, "gis_location") if joined else row
self.__options(_row, levels, inject_hierarchy, hierarchy, _level, translate, name_l10n)
for row in rows2:
self.__options(row, levels, inject_hierarchy, hierarchy, _level, translate, name_l10n)
if translate:
# Sort the options dicts
for level in levels:
options = levels[level]["options"]
options = OrderedDict(sorted(options.iteritems()))
else:
# Sort the options lists
for level in levels:
levels[level]["options"].sort()
if inject_hierarchy:
# Inject the Location Hierarchy
hierarchy = "S3.location_filter_hierarchy=%s" % \
json.dumps(hierarchy, separators=SEPARATORS)
js_global = current.response.s3.js_global
js_global.append(hierarchy)
if translate:
# Inject lookup list
name_l10n = "S3.location_name_l10n=%s" % \
json.dumps(name_l10n, separators=SEPARATORS)
js_global.append(name_l10n)
return (ftype, levels, None)
# -------------------------------------------------------------------------
def _selector(self, resource, fields):
"""
Helper method to generate a filter query selector for the
given field(s) in the given resource.
@param resource: the S3Resource
@param fields: the field selectors (as strings)
@return: the field label and the filter query selector, or None if none of the
field selectors could be resolved
"""
prefix = self._prefix
if resource:
rfield = S3ResourceField(resource, fields)
label = rfield.label
else:
label = None
if "levels" in self.opts:
levels = self.opts.levels
else:
levels = current.gis.get_relevant_hierarchy_levels()
fields = ["%s$%s" % (fields, level) for level in levels]
if resource:
selectors = []
for field in fields:
try:
rfield = S3ResourceField(resource, field)
except (AttributeError, TypeError):
continue
selectors.append(prefix(rfield.selector))
else:
selectors = fields
if selectors:
return label, "|".join(selectors)
else:
return label, None
# -------------------------------------------------------------------------
@classmethod
def _variable(cls, selector, operator):
"""
Construct URL query variable(s) name from a filter query
selector and the given operator(s)
@param selector: the selector
@param operator: the operator (or tuple/list of operators)
@return: the URL query variable name (or list of variable names)
"""
selectors = selector.split("|")
return ["%s__%s" % (selector, operator) for selector in selectors]
# =============================================================================
class S3OptionsFilter(S3FilterWidget):
"""
Options filter widget
@see: L{Configuration Options<S3FilterWidget.__init__>}
"""
_class = "options-filter"
operator = "belongs"
alternatives = ["anyof", "contains"]
# -------------------------------------------------------------------------
def widget(self, resource, values):
"""
Render this widget as HTML helper object(s)
@param resource: the resource
@param values: the search values from the URL query
"""
attr = self._attr(resource)
opts = self.opts
name = attr["_name"]
# Get the options
ftype, options, noopt = self._options(resource, values=values)
if noopt:
return SPAN(noopt, _class="no-options-available")
else:
options = OrderedDict(options)
# Any-All-Option : for many-to-many fields the user can
# search for records containing all the options or any
# of the options:
if len(options) > 1 and ftype[:4] == "list":
operator = opts.get("operator", None)
if operator:
self.operator = operator
any_all = ""
else:
operator = self.operator
any_all = True
if operator == "anyof":
filter_type = "any"
else:
filter_type = "all"
if operator == "belongs":
operator = "contains"
if any_all:
# Provide a form to prompt the user to choose
T = current.T
any_all = DIV(T("Filter type"),
INPUT(_name="%s_filter" % name,
_id="%s_filter_any" % name,
_type="radio",
_value="any",
value=filter_type),
LABEL(T("Any"),
_for="%s_filter_any" % name),
INPUT(_name="%s_filter" % name,
_id="%s_filter_all" % name,
_type="radio",
_value="all",
value=filter_type),
LABEL(T("All"),
_for="%s_filter_all" % name),
_class="s3-options-filter-anyall",
)
else:
any_all = ""
# Initialize widget
#widget_type = opts["widget"]
# Use groupedopts widget if we specify cols, otherwise assume multiselect
cols = opts.get("cols", None)
if cols:
widget_class = "groupedopts-filter-widget"
w = S3GroupedOptionsWidget(options = options,
multiple = opts.get("multiple", True),
cols = cols,
size = opts["size"] or 12,
help_field = opts["help_field"],
)
else:
# Default widget_type = "multiselect"
widget_class = "multiselect-filter-widget"
w = S3MultiSelectWidget(filter = opts.get("filter", "auto"),
header = opts.get("header", False),
selectedList = opts.get("selectedList", 3),
multiple = opts.get("multiple", True),
)
# Add widget class and default class
classes = set(attr.get("_class", "").split()) | \
set((widget_class, self._class))
attr["_class"] = " ".join(classes) if classes else None
# Render the widget
dummy_field = Storage(name=name,
type=ftype,
requires=IS_IN_SET(options, multiple=True))
widget = w(dummy_field, values, **attr)
return TAG[""](any_all, widget)
# -------------------------------------------------------------------------
def ajax_options(self, resource):
"""
Method to Ajax-retrieve the current options of this widget
@param resource: the S3Resource
"""
opts = self.opts
attr = self._attr(resource)
ftype, options, noopt = self._options(resource)
if noopt:
options = {attr["_id"]: str(noopt)}
else:
#widget_type = opts["widget"]
# Use groupedopts widget if we specify cols, otherwise assume multiselect
cols = opts.get("cols", None)
if cols:
# Use the widget method to group and sort the options
widget = S3GroupedOptionsWidget(
options = options,
multiple = True,
cols = cols,
size = opts["size"] or 12,
help_field = opts["help_field"]
)
options = {attr["_id"]:
widget._options({"type": ftype}, [])}
else:
# Multiselect
# Produce a simple list of tuples
options = {attr["_id"]: [(k, s3_unicode(v))
for k, v in options]}
return options
# -------------------------------------------------------------------------
def _options(self, resource, values=None):
"""
Helper function to retrieve the current options for this
filter widget
@param resource: the S3Resource
"""
T = current.T
NOOPT = T("No options available")
EMPTY = T("None")
#attr = self.attr
opts = self.opts
# Resolve the field selector
selector = self.field
if isinstance(selector, (tuple, list)):
selector = selector[0]
if resource is None:
rname = opts.get("resource")
if rname:
resource = current.s3db.resource(rname)
if resource:
rfield = S3ResourceField(resource, selector)
field = rfield.field
colname = rfield.colname
ftype = rfield.ftype
else:
rfield = field = colname = None
ftype = "string"
# Find the options
opt_keys = []
multiple = ftype[:5] == "list:"
if opts.options is not None:
# Custom dict of options {value: label} or a callable
# returning such a dict:
options = opts.options
if callable(options):
options = options()
opt_keys = options.keys()
elif resource:
# Determine the options from the field type
options = None
if ftype == "boolean":
opt_keys = (True, False)
elif field or rfield.virtual:
groupby = field if field and not multiple else None
virtual = field is None
# If the search field is a foreign key, then try to perform
# a reverse lookup of primary IDs in the lookup table which
# are linked to at least one record in the resource => better
# scalability.
rows = None
if field:
ktablename, key, m = s3_get_foreign_key(field, m2m=False)
if ktablename:
multiple = m
ktable = current.s3db.table(ktablename)
key_field = ktable[key]
colname = str(key_field)
left = None
accessible_query = current.auth.s3_accessible_query
# Respect the validator of the foreign key field.
# Commented because questionable: We want a filter
# option for every current field value, even if it
# doesn't match the validator (don't we?)
#requires = field.requires
#if requires:
#if not isinstance(requires, list):
#requires = [requires]
#requires = requires[0]
#if isinstance(requires, IS_EMPTY_OR):
#requires = requires.other
#if isinstance(requires, IS_ONE_OF_EMPTY):
#query, left = requires.query(ktable)
#else:
#query = accessible_query("read", ktable)
#query &= (key_field == field)
query = (key_field == field)
joins = rfield.join
for tname in joins:
query &= joins[tname]
# We do not allow the user to see values only used
# in records he's not permitted to see:
query &= accessible_query("read", resource.table)
# Filter options by location?
location_filter = opts.get("location_filter")
if location_filter and "location_id" in ktable:
location = current.session.s3.location_filter
if location:
query &= (ktable.location_id == location)
# Filter options by organisation?
org_filter = opts.get("org_filter")
if org_filter and "organisation_id" in ktable:
root_org = current.auth.root_org()
if root_org:
query &= ((ktable.organisation_id == root_org) | \
(ktable.organisation_id == None))
#else:
# query &= (ktable.organisation_id == None)
rows = current.db(query).select(key_field,
resource._id.min(),
groupby=key_field,
left=left)
# If we can not perform a reverse lookup, then we need
# to do a forward lookup of all unique values of the
# search field from all records in the table :/ still ok,
# but not endlessly scalable:
if rows is None:
rows = resource.select([selector],
limit=None,
orderby=field,
groupby=groupby,
virtual=virtual,
as_rows=True)
opt_keys = [] # Can't use set => would make orderby pointless
if rows:
kappend = opt_keys.append
kextend = opt_keys.extend
for row in rows:
val = row[colname]
if virtual and callable(val):
val = val()
if multiple or \
virtual and isinstance(val, (list, tuple, set)):
kextend([v for v in val
if v not in opt_keys])
elif val not in opt_keys:
kappend(val)
# Make sure the selected options are in the available options
# (not possible if we have a fixed options dict)
if options is None and values:
numeric = rfield.ftype in ("integer", "id") or \
rfield.ftype[:9] == "reference"
for _val in values:
if numeric:
try:
val = int(_val)
except ValueError:
# not valid for this field type => skip
continue
else:
val = _val
if val not in opt_keys and \
(not isinstance(val, (int, long)) or not str(val) in opt_keys):
opt_keys.append(val)
# No options?
if len(opt_keys) < 1 or len(opt_keys) == 1 and not opt_keys[0]:
return (ftype, None, opts.get("no_opts", NOOPT))
# Represent the options
opt_list = [] # list of tuples (key, value)
# Custom represent? (otherwise fall back to field.represent)
represent = opts.represent
if not represent: # or ftype[:9] != "reference":
represent = field.represent if field else None
if options is not None:
# Custom dict of {value:label} => use this label
opt_list = options.items()
elif callable(represent):
# Callable representation function:
if hasattr(represent, "bulk"):
# S3Represent => use bulk option
opt_dict = represent.bulk(opt_keys,
list_type=False,
show_link=False)
if None in opt_keys:
opt_dict[None] = EMPTY
elif None in opt_dict:
del opt_dict[None]
if "" in opt_keys:
opt_dict[""] = EMPTY
opt_list = opt_dict.items()
else:
# Simple represent function
args = {"show_link": False} \
if "show_link" in represent.func_code.co_varnames else {}
if multiple:
repr_opt = lambda opt: opt in (None, "") and (opt, EMPTY) or \
(opt, represent([opt], **args))
else:
repr_opt = lambda opt: opt in (None, "") and (opt, EMPTY) or \
(opt, represent(opt, **args))
opt_list = map(repr_opt, opt_keys)
elif isinstance(represent, str) and ftype[:9] == "reference":
# Represent is a string template to be fed from the
# referenced record
# Get the referenced table
db = current.db
ktable = db[ftype[10:]]
k_id = ktable._id.name
# Get the fields referenced by the string template
fieldnames = [k_id]
fieldnames += re.findall("%\(([a-zA-Z0-9_]*)\)s", represent)
represent_fields = [ktable[fieldname] for fieldname in fieldnames]
# Get the referenced records
query = (ktable.id.belongs([k for k in opt_keys
if str(k).isdigit()])) & \
(ktable.deleted == False)
rows = db(query).select(*represent_fields).as_dict(key=k_id)
# Run all referenced records against the format string
opt_list = []
ol_append = opt_list.append
for opt_value in opt_keys:
if opt_value in rows:
opt_represent = represent % rows[opt_value]
if opt_represent:
ol_append((opt_value, opt_represent))
else:
# Straight string representations of the values (fallback)
opt_list = [(opt_value, s3_unicode(opt_value))
for opt_value in opt_keys if opt_value]
none = opts["none"]
try:
opt_list.sort(key=lambda item: item[1])
except:
opt_list.sort(key=lambda item: s3_unicode(item[1]))
options = []
empty = False
for k, v in opt_list:
if k is None:
if none:
empty = True
if none is True:
# Use the represent
options.append((k, v))
else:
# Must be a string to use as the represent:
options.append((k, none))
else:
options.append((k, v))
if none and not empty:
# Add the value anyway (e.g. not found via the reverse lookup)
if none is True:
none = current.messages["NONE"]
options.append((None, none))
# Sort the options
return (ftype, options, None)
# -------------------------------------------------------------------------
@staticmethod
def _values(get_vars, variable):
"""
Helper method to get all values of a URL query variable
@param get_vars: the GET vars (a dict)
@param variable: the name of the query variable
@return: a list of values
"""
if not variable:
return []
# Match __eq before checking any other operator
selector = variable.split("__", 1)[0]
for key in ("%s__eq" % selector, selector, variable):
if key in get_vars:
values = S3URLQuery.parse_value(get_vars[key])
if not isinstance(values, (list, tuple)):
values = [values]
return values
return []
# =============================================================================
class S3HierarchyFilter(S3FilterWidget):
"""
Filter widget for hierarchical types
Specific options:
lookup name of the lookup table
represent representation method for the key
"""
_class = "hierarchy-filter"
operator = "belongs"
# -------------------------------------------------------------------------
def widget(self, resource, values):
"""
Render this widget as HTML helper object(s)
@param resource: the resource
@param values: the search values from the URL query
"""
# Currently selected values
selected = []
append = selected.append
if not isinstance(values, (list, tuple, set)):
values = [values]
for v in values:
if isinstance(v, (int, long)) or str(v).isdigit():
append(v)
# Resolve the field selector
rfield = S3ResourceField(resource, self.field)
# Instantiate the widget
opts = self.opts
w = S3HierarchyWidget(lookup = opts.get("lookup"),
represent = opts.get("represent"),
multiple = opts.get("multiple", True),
leafonly = opts.get("leafonly", True),
)
# Render the widget
widget = w(rfield.field, selected, **self._attr(resource))
widget.add_class(self._class)
return widget
# -------------------------------------------------------------------------
def variable(self, resource, get_vars=None):
"""
Generate the name for the URL query variable for this
widget, detect alternative __typeof queries.
@param resource: the resource
@return: the URL query variable name (or list of
variable names if there are multiple operators)
"""
label, self.selector = self._selector(resource, self.field)
if not self.selector:
return None
if "label" not in self.opts:
self.opts["label"] = label
selector = self.selector
if self.alternatives and get_vars is not None:
# Get the actual operator from get_vars
operator = self._operator(get_vars, self.selector)
if operator:
self.operator = operator
variable = self._variable(selector, self.operator)
if not get_vars or not resource or variable in get_vars:
return variable
# Detect and resolve __typeof queries
#BELONGS = current.db._adapter.BELONGS
resolve = S3ResourceQuery._resolve_hierarchy
selector = resource.prefix_selector(selector)
for key, value in get_vars.items():
if key.startswith(selector):
selectors, op, invert = S3URLQuery.parse_expression(key)
else:
continue
if op != "typeof" or len(selectors) != 1:
continue
rfield = resource.resolve_selector(selectors[0])
if rfield.field:
values = S3URLQuery.parse_value(value)
hierarchy, field, nodeset, none = resolve(rfield.field, values)
if field and (nodeset or none):
if nodeset is None:
nodeset = set()
if none:
nodeset.add(None)
get_vars.pop(key, None)
get_vars[variable] = [str(v) for v in nodeset]
break
return variable
# =============================================================================
class S3FilterForm(object):
""" Helper class to construct and render a filter form for a resource """
def __init__(self, widgets, **attr):
"""
Constructor
@param widgets: the widgets (as list)
@param attr: HTML attributes for this form
"""
self.widgets = widgets
attributes = Storage()
options = Storage()
for k, v in attr.iteritems():
if k[0] == "_":
attributes[k] = v
else:
options[k] = v
self.attr = attributes
self.opts = options
# -------------------------------------------------------------------------
def html(self, resource, get_vars=None, target=None, alias=None):
"""
Render this filter form as HTML form.
@param resource: the S3Resource
@param get_vars: the request GET vars (URL query dict)
@param target: the HTML element ID of the target object for
this filter form (e.g. a datatable)
@param alias: the resource alias to use in widgets
"""
attr = self.attr
form_id = attr.get("_id")
if not form_id:
form_id = "filter-form"
attr["_id"] = form_id
# Prevent issues with Webkit-based browsers & Back buttons
attr["_autocomplete"] = "off"
opts = self.opts
settings = current.deployment_settings
# Form style
formstyle = opts.get("formstyle", None)
if not formstyle:
formstyle = settings.get_ui_filter_formstyle()
# Filter widgets
rows = self._render_widgets(resource,
get_vars=get_vars or {},
alias=alias,
formstyle=formstyle)
# Other filter form controls
controls = self._render_controls(resource)
if controls:
rows.append(formstyle(None, "", controls, ""))
# Submit elements
ajax = opts.get("ajax", False)
submit = opts.get("submit", False)
if submit:
# Auto-submit?
auto_submit = settings.get_ui_filter_auto_submit()
if auto_submit and opts.get("auto_submit", True):
script = '''S3.search.filterFormAutoSubmit('%s',%s)''' % \
(form_id, auto_submit)
current.response.s3.jquery_ready.append(script)
# Custom label and class
_class = None
if submit is True:
label = current.T("Search")
elif isinstance(submit, (list, tuple)):
label, _class = submit
else:
label = submit
# Submit button
submit_button = INPUT(_type="button",
_value=label,
_class="filter-submit")
#if auto_submit:
#submit_button.add_class("hide")
if _class:
submit_button.add_class(_class)
# Where to request filtered data from:
submit_url = opts.get("url", URL(vars={}))
# Where to request updated options from:
ajax_url = opts.get("ajaxurl", URL(args=["filter.options"], vars={}))
# Submit row elements
submit = TAG[""](submit_button,
INPUT(_type="hidden",
_class="filter-ajax-url",
_value=ajax_url),
INPUT(_type="hidden",
_class="filter-submit-url",
_value=submit_url))
if ajax and target:
submit.append(INPUT(_type="hidden",
_class="filter-submit-target",
_value=target))
# Append submit row
submit_row = formstyle(None, "", submit, "")
if auto_submit and hasattr(submit_row, "add_class"):
submit_row.add_class("hide")
rows.append(submit_row)
# Filter Manager (load/apply/save filters)
fm = settings.get_search_filter_manager()
if fm and opts.get("filter_manager", resource is not None):
filter_manager = self._render_filters(resource, form_id)
if filter_manager:
fmrow = formstyle(None, "", filter_manager, "")
if hasattr(fmrow, "add_class"):
fmrow.add_class("hide filter-manager-row")
rows.append(fmrow)
# Adapt to formstyle: render a TABLE only if formstyle returns TRs
if rows:
elements = rows[0]
if not isinstance(elements, (list, tuple)):
elements = elements.elements()
n = len(elements)
if n > 0 and elements[0].tag == "tr" or \
n > 1 and elements[0].tag == "" and elements[1].tag == "tr":
form = FORM(TABLE(TBODY(rows)), **attr)
else:
form = FORM(DIV(rows), **attr)
if settings.ui.formstyle == "bootstrap":
# We need to amend the HTML markup to support this CSS framework
form.add_class("form-horizontal")
form.add_class("filter-form")
if ajax:
form.add_class("filter-ajax")
else:
return ""
# Put a copy of formstyle into the form for access by the view
form.formstyle = formstyle
return form
# -------------------------------------------------------------------------
def fields(self, resource, get_vars=None, alias=None):
"""
Render the filter widgets without FORM wrapper, e.g. to
embed them as fieldset in another form.
@param resource: the S3Resource
@param get_vars: the request GET vars (URL query dict)
@param alias: the resource alias to use in widgets
"""
formstyle = self.opts.get("formstyle", None)
if not formstyle:
formstyle = current.deployment_settings.get_ui_filter_formstyle()
rows = self._render_widgets(resource,
get_vars=get_vars,
alias=alias,
formstyle=formstyle)
controls = self._render_controls(resource)
if controls:
rows.append(formstyle(None, "", controls, ""))
# Adapt to formstyle: only render a TABLE if formstyle returns TRs
if rows:
elements = rows[0]
if not isinstance(elements, (list, tuple)):
elements = elements.elements()
n = len(elements)
if n > 0 and elements[0].tag == "tr" or \
n > 1 and elements[0].tag == "" and elements[1].tag == "tr":
fields = TABLE(TBODY(rows))
else:
fields = DIV(rows)
return fields
# -------------------------------------------------------------------------
def _render_controls(self, resource):
"""
Render optional additional filter form controls: advanced
options toggle, clear filters.
"""
T = current.T
controls = []
opts = self.opts
advanced = opts.get("advanced", False)
if advanced:
_class = "filter-advanced"
if advanced is True:
label = T("More Options")
elif isinstance(advanced, (list, tuple)):
label = advanced[0]
label = advanced[1]
if len(advanced > 2):
_class = "%s %s" % (advanced[2], _class)
else:
label = advanced
label_off = T("Less Options")
advanced = A(SPAN(label,
data = {"on": label,
"off": label_off,
},
_class="filter-advanced-label",
),
I(" ", _class="icon-down"),
I(" ", _class="icon-up", _style="display:none"),
_class=_class
)
controls.append(advanced)
clear = opts.get("clear", True)
if clear:
_class = "filter-clear"
if clear is True:
label = T("Clear filter")
elif isinstance(clear, (list, tuple)):
label = clear[0]
_class = "%s %s" % (clear[1], _class)
else:
label = clear
clear = A(label, _class=_class)
clear.add_class("action-lnk")
controls.append(clear)
fm = current.deployment_settings.get_search_filter_manager()
if fm and opts.get("filter_manager", resource is not None):
show_fm = A(T("Saved filters"),
_class="show-filter-manager action-lnk")
controls.append(show_fm)
if controls:
return DIV(controls, _class="filter-controls")
else:
return None
# -------------------------------------------------------------------------
def _render_widgets(self,
resource,
get_vars=None,
alias=None,
formstyle=None):
"""
Render the filter widgets
@param resource: the S3Resource
@param get_vars: the request GET vars (URL query dict)
@param alias: the resource alias to use in widgets
@param formstyle: the formstyle to use
@return: a list of form rows
"""
rows = []
rappend = rows.append
advanced = False
for f in self.widgets:
widget = f(resource, get_vars, alias=alias)
label = f.opts["label"]
comment = f.opts["comment"]
hidden = f.opts["hidden"]
if hidden:
advanced = True
widget_id = f.attr["_id"]
if widget_id:
row_id = "%s__row" % widget_id
label_id = "%s__label" % widget_id
else:
row_id = None
label_id = None
if label:
label = LABEL("%s:" % label, _id=label_id, _for=widget_id)
else:
label = ""
if not comment:
comment = ""
formrow = formstyle(row_id, label, widget, comment, hidden=hidden)
if hidden:
if isinstance(formrow, DIV):
formrow.add_class("advanced")
elif isinstance(formrow, tuple):
for item in formrow:
if hasattr(item, "add_class"):
item.add_class("advanced")
rappend(formrow)
if advanced:
if resource:
self.opts["advanced"] = resource.get_config(
"filter_advanced", True)
else:
self.opts["advanced"] = True
return rows
# -------------------------------------------------------------------------
def _render_filters(self, resource, form_id):
"""
Render a filter manager widget
@param resource: the resource
@return: the widget
"""
SELECT_FILTER = current.T("Saved Filters...")
ajaxurl = self.opts.get("saveurl", URL(args=["filter.json"], vars={}))
# Current user
auth = current.auth
pe_id = auth.user.pe_id if auth.s3_logged_in() else None
if not pe_id:
return None
table = current.s3db.pr_filter
query = (table.deleted != True) & \
(table.pe_id == pe_id)
if resource:
query &= (table.resource == resource.tablename)
else:
query &= (table.resource == None)
rows = current.db(query).select(table._id,
table.title,
table.query,
orderby=table.title)
options = [OPTION(SELECT_FILTER,
_value="",
_class="filter-manager-prompt",
_disabled="disabled")]
add_option = options.append
filters = {}
for row in rows:
filter_id = row[table._id]
add_option(OPTION(row.title, _value=filter_id))
query = row.query
if query:
query = json.loads(query)
filters[filter_id] = query
widget_id = "%s-fm" % form_id
widget = DIV(SELECT(options,
_id=widget_id,
_class="filter-manager-widget"),
_class="filter-manager-container")
# JSON-serializable translator
T = current.T
_t = lambda s: str(T(s))
# Configure the widget
settings = current.deployment_settings
config = dict(
# Filters and Ajax URL
filters = filters,
ajaxURL = ajaxurl,
# Workflow Options
allowDelete = settings.get_search_filter_manager_allow_delete(),
# Tooltips for action icons/buttons
createTooltip = _t("Save current options as new filter"),
loadTooltip = _t("Load filter"),
saveTooltip = _t("Update saved filter"),
deleteTooltip = _t("Delete saved filter"),
# Hints
titleHint = _t("Enter a title..."),
selectHint = str(SELECT_FILTER),
emptyHint = _t("No saved filters"),
# Confirm update + confirmation text
confirmUpdate = _t("Update this filter?"),
confirmDelete = _t("Delete this filter?"),
)
# Render actions as buttons with text if configured, otherwise
# they will appear as empty DIVs with classes for CSS icons
create_text = settings.get_search_filter_manager_save()
if create_text:
config["createText"] = _t(create_text)
update_text = settings.get_search_filter_manager_update()
if update_text:
config["saveText"] = _t(update_text)
delete_text = settings.get_search_filter_manager_delete()
if delete_text:
config["deleteText"] = _t(delete_text)
load_text = settings.get_search_filter_manager_load()
if load_text:
config["loadText"] = _t(load_text)
script = '''$("#%s").filtermanager(%s)''' % \
(widget_id,
json.dumps(config, separators=SEPARATORS))
current.response.s3.jquery_ready.append(script)
return widget
# -------------------------------------------------------------------------
def json(self, resource, get_vars=None):
"""
Render this filter form as JSON (for Ajax requests)
@param resource: the S3Resource
@param get_vars: the request GET vars (URL query dict)
"""
raise NotImplementedError
# -------------------------------------------------------------------------
@staticmethod
def apply_filter_defaults(request, resource):
"""
Add default filters to resource, to be called a multi-record
view with a filter form is rendered the first time and before
the view elements get processed
@param request: the request
@param resource: the resource
"""
s3 = current.response.s3
get_vars = request.get_vars
tablename = resource.tablename
# Do we have filter defaults for this resource?
filter_defaults = s3
for level in ("filter_defaults", tablename):
if level not in filter_defaults:
return None
filter_defaults = filter_defaults[level]
# Which filter widgets do we need to apply defaults for?
filter_widgets = resource.get_config("filter_widgets")
for filter_widget in filter_widgets:
# Do not apply defaults of hidden widgets because they are
# not visible to the user:
if filter_widget.opts.hidden:
continue
defaults = {}
variable = filter_widget.variable(resource, get_vars)
# Do we have a corresponding value in get_vars?
if type(variable) is list:
for k in variable:
values = filter_widget._values(get_vars, k)
if values:
filter_widget.values[k] = values
else:
defaults[k] = None
else:
values = filter_widget._values(get_vars, variable)
if values:
filter_widget.values[variable] = values
else:
defaults[variable] = None
default_filters = {}
for variable in defaults:
if "__" in variable:
selector, operator = variable.split("__", 1)
else:
selector, operator = variable, None
if selector not in filter_defaults:
continue
applicable_defaults = filter_defaults[selector]
if callable(applicable_defaults):
applicable_defaults = applicable_defaults(selector,
tablename=tablename)
if isinstance(applicable_defaults, dict):
if operator in applicable_defaults:
default = applicable_defaults[operator]
else:
continue
elif operator in (None, "belongs", "eq"):
default = applicable_defaults
else:
continue
if not isinstance(default, (list, type(None))):
default = [default]
filter_widget.values[variable] = [str(v) if v is None else v
for v in default]
default_filters[variable] = ",".join(s3_unicode(v)
for v in default)
# @todo: make sure the applied default options are available in
# the filter widget - otherwise the user can not deselect
# them! (critical) Maybe enforce this by adding the default
# values to the available options in S3OptionsFilter and
# S3LocationFilter?
# Apply to resource
queries = S3URLQuery.parse(resource, default_filters)
add_filter = resource.add_filter
for alias in queries:
for q in queries[alias]:
add_filter(q)
return
# =============================================================================
class S3Filter(S3Method):
""" Back-end for filter forms """
def apply_method(self, r, **attr):
"""
Entry point for REST interface
@param r: the S3Request
@param attr: additional controller parameters
"""
representation = r.representation
if representation == "options":
# Return the filter options as JSON
return self._options(r, **attr)
elif representation == "json":
if r.http == "GET":
# Load list of saved filters
return self._load(r, **attr)
elif r.http == "POST":
if "delete" in r.get_vars:
# Delete a filter
return self._delete(r, **attr)
else:
# Save a filter
return self._save(r, **attr)
else:
r.error(405, current.ERROR.BAD_METHOD)
elif representation == "html":
return self._form(r, **attr)
else:
r.error(501, current.ERROR.BAD_FORMAT)
# -------------------------------------------------------------------------
def _form(self, r, **attr):
"""
Get the filter form for the target resource as HTML snippet
GET filter.html
@param r: the S3Request
@param attr: additional controller parameters
"""
r.error(501, current.ERROR.NOT_IMPLEMENTED)
# -------------------------------------------------------------------------
def _options(self, r, **attr):
"""
Get the updated options for the filter form for the target
resource as JSON
GET filter.options
@param r: the S3Request
@param attr: additional controller parameters
"""
resource = self.resource
get_config = resource.get_config
options = {}
filter_widgets = get_config("filter_widgets", None)
if filter_widgets:
fresource = current.s3db.resource(resource.tablename)
for widget in filter_widgets:
if hasattr(widget, "ajax_options"):
opts = widget.ajax_options(fresource)
if opts and isinstance(opts, dict):
options.update(opts)
options = json.dumps(options, separators=SEPARATORS)
current.response.headers["Content-Type"] = "application/json"
return options
# -------------------------------------------------------------------------
def _delete(self, r, **attr):
"""
Delete a filter, responds to POST filter.json?delete=
@param r: the S3Request
@param attr: additional controller parameters
"""
# Authorization, get pe_id
auth = current.auth
if auth.s3_logged_in():
pe_id = current.auth.user.pe_id
else:
pe_id = None
if not pe_id:
r.unauthorised()
# Read the source
source = r.body
source.seek(0)
try:
data = json.load(source)
except ValueError:
# Syntax error: no JSON data
r.error(501, current.ERROR.BAD_SOURCE)
# Try to find the record
db = current.db
s3db = current.s3db
table = s3db.pr_filter
record = None
record_id = data.get("id")
if record_id:
query = (table.id == record_id) & (table.pe_id == pe_id)
record = db(query).select(table.id, limitby=(0, 1)).first()
if not record:
r.error(501, current.ERROR.BAD_RECORD)
resource = s3db.resource("pr_filter", id=record_id)
success = resource.delete(format=r.representation)
if not success:
raise(400, resource.error)
else:
current.response.headers["Content-Type"] = "application/json"
return current.xml.json_message(deleted=record_id)
# -------------------------------------------------------------------------
def _save(self, r, **attr):
"""
Save a filter, responds to POST filter.json
@param r: the S3Request
@param attr: additional controller parameters
"""
# Authorization, get pe_id
auth = current.auth
if auth.s3_logged_in():
pe_id = current.auth.user.pe_id
else:
pe_id = None
if not pe_id:
r.unauthorised()
# Read the source
source = r.body
source.seek(0)
try:
data = json.load(source)
except ValueError:
r.error(501, current.ERROR.BAD_SOURCE)
# Try to find the record
db = current.db
s3db = current.s3db
table = s3db.pr_filter
record_id = data.get("id")
record = None
if record_id:
query = (table.id == record_id) & (table.pe_id == pe_id)
record = db(query).select(table.id, limitby=(0, 1)).first()
if not record:
r.error(404, current.ERROR.BAD_RECORD)
# Build new record
filter_data = {
"pe_id": pe_id,
"controller": r.controller,
"function": r.function,
"resource": self.resource.tablename,
"deleted": False,
}
title = data.get("title")
if title is not None:
filter_data["title"] = title
description = data.get("description")
if description is not None:
filter_data["description"] = description
query = data.get("query")
if query is not None:
filter_data["query"] = json.dumps(query)
url = data.get("url")
if url is not None:
filter_data["url"] = url
# Store record
onaccept = None
form = Storage(vars=filter_data)
if record:
success = db(table.id == record_id).update(**filter_data)
if success:
current.audit("update", "pr", "filter", form, record_id, "json")
info = {"updated": record_id}
onaccept = s3db.get_config(table, "update_onaccept",
s3db.get_config(table, "onaccept"))
else:
success = table.insert(**filter_data)
if success:
record_id = success
current.audit("create", "pr", "filter", form, record_id, "json")
info = {"created": record_id}
onaccept = s3db.get_config(table, "update_onaccept",
s3db.get_config(table, "onaccept"))
if onaccept is not None:
form.vars["id"] = record_id
callback(onaccept, form)
# Success/Error response
xml = current.xml
if success:
msg = xml.json_message(**info)
else:
msg = xml.json_message(False, 400)
current.response.headers["Content-Type"] = "application/json"
return msg
# -------------------------------------------------------------------------
def _load(self, r, **attr):
"""
Load filters
GET filter.json or GET filter.json?load=<id>
@param r: the S3Request
@param attr: additional controller parameters
"""
db = current.db
table = current.s3db.pr_filter
# Authorization, get pe_id
auth = current.auth
if auth.s3_logged_in():
pe_id = current.auth.user.pe_id
else:
pe_id = None
if not pe_id:
r.unauthorized()
# Build query
query = (table.deleted != True) & \
(table.resource == self.resource.tablename) & \
(table.pe_id == pe_id)
# Any particular filters?
load = r.get_vars.get("load")
if load:
record_ids = [i for i in load.split(",") if i.isdigit()]
if record_ids:
if len(record_ids) > 1:
query &= table.id.belongs(record_ids)
else:
query &= table.id == record_ids[0]
else:
record_ids = None
# Retrieve filters
rows = db(query).select(table.id,
table.title,
table.description,
table.query)
# Pack filters
filters = []
for row in rows:
filters.append({
"id": row.id,
"title": row.title,
"description": row.description,
"query": json.loads(row.query) if row.query else [],
})
# JSON response
current.response.headers["Content-Type"] = "application/json"
return json.dumps(filters, separators=SEPARATORS)
# =============================================================================
class S3FilterString(object):
"""
Helper class to render a human-readable representation of a
filter query, as representation method of JSON-serialized
queries in saved filters.
"""
def __init__(self, resource, query):
"""
Constructor
@param query: the URL query (list of key-value pairs or a
string with such a list in JSON)
"""
if type(query) is not list:
try:
self.query = json.loads(query)
except ValueError:
self.query = []
else:
self.query = query
get_vars = {}
for k, v in self.query:
if v is not None:
key = resource.prefix_selector(k)
if key in get_vars:
value = get_vars[key]
if type(value) is list:
value.append(v)
else:
get_vars[key] = [value, v]
else:
get_vars[key] = v
self.resource = resource
self.get_vars = get_vars
# -------------------------------------------------------------------------
def represent(self):
""" Render the query representation for the given resource """
default = ""
get_vars = self.get_vars
resource = self.resource
if not get_vars:
return default
else:
queries = S3URLQuery.parse(resource, get_vars)
# Get alternative field labels
labels = {}
get_config = resource.get_config
prefix = resource.prefix_selector
for config in ("list_fields", "notify_fields"):
fields = get_config(config, set())
for f in fields:
if type(f) is tuple:
labels[prefix(f[1])] = f[0]
# Iterate over the sub-queries
render = self._render
substrings = []
append = substrings.append
for alias, subqueries in queries.iteritems():
for subquery in subqueries:
s = render(resource, alias, subquery, labels=labels)
if s:
append(s)
if substrings:
result = substrings[0]
T = current.T
for s in substrings[1:]:
result = T("%s AND %s") % (result, s)
return result
else:
return default
# -------------------------------------------------------------------------
@classmethod
def _render(cls, resource, alias, query, invert=False, labels=None):
"""
Recursively render a human-readable representation of a
S3ResourceQuery.
@param resource: the S3Resource
@param query: the S3ResourceQuery
@param invert: invert the query
"""
T = current.T
if not query:
return None
op = query.op
l = query.left
r = query.right
render = lambda q, r=resource, a=alias, invert=False, labels=labels: \
cls._render(r, a, q, invert=invert, labels=labels)
if op == query.AND:
# Recurse AND
l = render(l)
r = render(r)
if l is not None and r is not None:
if invert:
result = T("NOT %s OR NOT %s") % (l, r)
else:
result = T("%s AND %s") % (l, r)
else:
result = l if l is not None else r
elif op == query.OR:
# Recurse OR
l = render(l)
r = render(r)
if l is not None and r is not None:
if invert:
result = T("NOT %s AND NOT %s") % (l, r)
else:
result = T("%s OR %s") % (l, r)
else:
result = l if l is not None else r
elif op == query.NOT:
# Recurse NOT
result = render(l, invert=not invert)
else:
# Resolve the field selector against the resource
try:
rfield = l.resolve(resource)
except (AttributeError, SyntaxError):
return None
# Convert the filter values into the field type
try:
values = cls._convert(rfield, r)
except (TypeError, ValueError):
values = r
# Alias
selector = l.name
if labels and selector in labels:
rfield.label = labels[selector]
# @todo: for duplicate labels, show the table name
#else:
#tlabel = " ".join(s.capitalize() for s in rfield.tname.split("_")[1:])
#rfield.label = "(%s) %s" % (tlabel, rfield.label)
# Represent the values
if values is None:
values = T("None")
else:
list_type = rfield.ftype[:5] == "list:"
renderer = rfield.represent
if not callable(renderer):
renderer = lambda v: s3_unicode(v)
if hasattr(renderer, "linkto"):
#linkto = renderer.linkto
renderer.linkto = None
#else:
# #linkto = None
is_list = type(values) is list
try:
if is_list and hasattr(renderer, "bulk") and not list_type:
fvalues = renderer.bulk(values, list_type=False)
values = [fvalues[v] for v in values if v in fvalues]
elif list_type:
if is_list:
values = renderer(values)
else:
values = renderer([values])
else:
if is_list:
values = [renderer(v) for v in values]
else:
values = renderer(values)
except:
values = s3_unicode(values)
# Translate the query
result = cls._translate_query(query, rfield, values, invert=invert)
return result
# -------------------------------------------------------------------------
@classmethod
def _convert(cls, rfield, value):
"""
Convert a filter value according to the field type
before representation
@param rfield: the S3ResourceField
@param value: the value
"""
if value is None:
return value
ftype = rfield.ftype
if ftype[:5] == "list:":
if ftype[5:8] in ("int", "ref"):
ftype = long
else:
ftype = unicode
elif ftype == "id" or ftype [:9] == "reference":
ftype = long
elif ftype == "integer":
ftype = int
elif ftype == "date":
ftype = datetime.date
elif ftype == "time":
ftype = datetime.time
elif ftype == "datetime":
ftype = datetime.datetime
elif ftype == "double":
ftype = float
elif ftype == "boolean":
ftype = bool
else:
ftype = unicode
convert = S3TypeConverter.convert
if type(value) is list:
output = []
append = output.append
for v in value:
try:
append(convert(ftype, v))
except TypeError, ValueError:
continue
else:
try:
output = convert(ftype, value)
except TypeError, ValueError:
output = None
return output
# -------------------------------------------------------------------------
@classmethod
def _translate_query(cls, query, rfield, values, invert=False):
"""
Translate the filter query into human-readable language
@param query: the S3ResourceQuery
@param rfield: the S3ResourceField the query refers to
@param values: the filter values
@param invert: invert the operation
"""
T = current.T
# Value list templates
vor = T("%s or %s")
vand = T("%s and %s")
# Operator templates
otemplates = {
query.LT: (query.GE, vand, "%(label)s < %(values)s"),
query.LE: (query.GT, vand, "%(label)s <= %(values)s"),
query.EQ: (query.NE, vor, T("%(label)s is %(values)s")),
query.GE: (query.LT, vand, "%(label)s >= %(values)s"),
query.GT: (query.LE, vand, "%(label)s > %(values)s"),
query.NE: (query.EQ, vor, T("%(label)s != %(values)s")),
query.LIKE: ("notlike", vor, T("%(label)s like %(values)s")),
query.BELONGS: (query.NE, vor, T("%(label)s = %(values)s")),
query.CONTAINS: ("notall", vand, T("%(label)s contains %(values)s")),
query.ANYOF: ("notany", vor, T("%(label)s contains any of %(values)s")),
"notall": (query.CONTAINS, vand, T("%(label)s does not contain %(values)s")),
"notany": (query.ANYOF, vor, T("%(label)s does not contain %(values)s")),
"notlike": (query.LIKE, vor, T("%(label)s not like %(values)s"))
}
# Quote values as necessary
ftype = rfield.ftype
if ftype in ("string", "text") or \
ftype[:9] == "reference" or \
ftype[:5] == "list:" and ftype[5:8] in ("str", "ref"):
if type(values) is list:
values = ['"%s"' % v for v in values]
elif values is not None:
values = '"%s"' % values
else:
values = current.messages["NONE"]
# Render value list template
def render_values(template=None, values=None):
if not template or type(values) is not list:
return str(values)
elif not values:
return "()"
elif len(values) == 1:
return values[0]
else:
return template % (", ".join(values[:-1]), values[-1])
# Render the operator template
op = query.op
if op in otemplates:
inversion, vtemplate, otemplate = otemplates[op]
if invert:
inversion, vtemplate, otemplate = otemplates[inversion]
return otemplate % dict(label=rfield.label,
values=render_values(vtemplate, values))
else:
# Fallback to simple representation
# FIXME: resource not defined here!
return query.represent(resource)
# END =========================================================================
| {
"content_hash": "ea634f174cfbf3f4eb1e7fcf3f41118a",
"timestamp": "",
"source": "github",
"line_count": 2947,
"max_line_length": 143,
"avg_line_length": 36.701051917203934,
"alnum_prop": 0.4659294735479576,
"repo_name": "gnarula/eden_deployment",
"id": "d8e219d819d7ab1943832fd4528667a350d80eca",
"size": "108183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/s3/s3filter.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1305178"
},
{
"name": "JavaScript",
"bytes": "16338028"
},
{
"name": "PHP",
"bytes": "15220"
},
{
"name": "Perl",
"bytes": "500"
},
{
"name": "Python",
"bytes": "28218113"
},
{
"name": "Shell",
"bytes": "893"
},
{
"name": "XSLT",
"bytes": "2491556"
}
],
"symlink_target": ""
} |
package org.apache.druid.segment.loading;
import com.google.common.base.Joiner;
import org.apache.druid.guice.annotations.ExtensionPoint;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.timeline.DataSegment;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@ExtensionPoint
public interface DataSegmentPusher
{
Joiner JOINER = Joiner.on("/").skipNulls();
@Deprecated
String getPathForHadoop(String dataSource);
String getPathForHadoop();
/**
* Pushes index files and segment descriptor to deep storage.
* @param file directory containing index files
* @param segment segment descriptor
* @param useUniquePath if true, pushes to a unique file path. This prevents situations where task failures or replica
* tasks can either overwrite or fail to overwrite existing segments leading to the possibility
* of different versions of the same segment ID containing different data. As an example, a Kafka
* indexing task starting at offset A and ending at offset B may push a segment to deep storage
* and then fail before writing the loadSpec to the metadata table, resulting in a replacement
* task being spawned. This replacement will also start at offset A but will read to offset C and
* will then push a segment to deep storage and write the loadSpec metadata. Without unique file
* paths, this can only work correctly if new segments overwrite existing segments. Suppose that
* at this point the task then fails so that the supervisor retries again from offset A. This 3rd
* attempt will overwrite the segments in deep storage before failing to write the loadSpec
* metadata, resulting in inconsistencies in the segment data now in deep storage and copies of
* the segment already loaded by historicals.
*
* If unique paths are used, caller is responsible for cleaning up segments that were pushed but
* were not written to the metadata table (for example when using replica tasks).
* @return segment descriptor
* @throws IOException
*/
DataSegment push(File file, DataSegment segment, boolean useUniquePath) throws IOException;
//use map instead of LoadSpec class to avoid dependency pollution.
Map<String, Object> makeLoadSpec(URI finalIndexZipFilePath);
/**
* @deprecated backward-compatibiliy shim that should be removed on next major release;
* use {@link #getStorageDir(DataSegment, boolean)} instead.
*/
@Deprecated
default String getStorageDir(DataSegment dataSegment)
{
return getStorageDir(dataSegment, false);
}
default String getStorageDir(DataSegment dataSegment, boolean useUniquePath)
{
return getDefaultStorageDir(dataSegment, useUniquePath);
}
default String makeIndexPathName(DataSegment dataSegment, String indexName)
{
// This is only called from Hadoop batch which doesn't require unique segment paths so set useUniquePath=false
return StringUtils.format("./%s/%s", getStorageDir(dataSegment, false), indexName);
}
/**
* Property prefixes that should be added to the "allowedHadoopPrefix" config for passing down to Hadoop jobs. These
* should be property prefixes like "druid.xxx", which means to include "druid.xxx" and "druid.xxx.*".
*/
default List<String> getAllowedPropertyPrefixesForHadoop()
{
return Collections.emptyList();
}
// Note: storage directory structure format = .../dataSource/interval/version/partitionNumber/
// If above format is ever changed, make sure to change it appropriately in other places
// e.g. HDFSDataSegmentKiller uses this information to clean the version, interval and dataSource directories
// on segment deletion if segment being deleted was the only segment
static String getDefaultStorageDir(DataSegment segment, boolean useUniquePath)
{
return JOINER.join(
segment.getDataSource(),
StringUtils.format("%s_%s", segment.getInterval().getStart(), segment.getInterval().getEnd()),
segment.getVersion(),
segment.getShardSpec().getPartitionNum(),
useUniquePath ? generateUniquePath() : null
);
}
static String getDefaultStorageDirWithExistingUniquePath(DataSegment segment, String uniquePath)
{
return JOINER.join(
segment.getDataSource(),
StringUtils.format("%s_%s", segment.getInterval().getStart(), segment.getInterval().getEnd()),
segment.getVersion(),
segment.getShardSpec().getPartitionNum(),
uniquePath
);
}
static String generateUniquePath()
{
return UUID.randomUUID().toString();
}
}
| {
"content_hash": "7b3e32a446b599d7fe20d3616562b90c",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 120,
"avg_line_length": 43.11304347826087,
"alnum_prop": 0.7081484469544171,
"repo_name": "knoguchi/druid",
"id": "7e9eb9234b76e51315ad6e99d4004646b99e84bd",
"size": "5765",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "core/src/main/java/org/apache/druid/segment/loading/DataSegmentPusher.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "1406"
},
{
"name": "CSS",
"bytes": "11623"
},
{
"name": "HTML",
"bytes": "26739"
},
{
"name": "Java",
"bytes": "16235629"
},
{
"name": "JavaScript",
"bytes": "295150"
},
{
"name": "Makefile",
"bytes": "659"
},
{
"name": "PostScript",
"bytes": "5"
},
{
"name": "Protocol Buffer",
"bytes": "729"
},
{
"name": "R",
"bytes": "17002"
},
{
"name": "Roff",
"bytes": "3617"
},
{
"name": "Shell",
"bytes": "4892"
},
{
"name": "TeX",
"bytes": "399444"
},
{
"name": "Thrift",
"bytes": "199"
}
],
"symlink_target": ""
} |
set (CMAKE_MAKE_PROGRAM "wmake" CACHE STRING
"Program used to build from makefiles.")
mark_as_advanced(CMAKE_MAKE_PROGRAM)
| {
"content_hash": "61cb3965cad7bc90756d52ad7e640b27",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 45,
"avg_line_length": 42.666666666666664,
"alnum_prop": 0.75,
"repo_name": "ColdenCullen/Project-192",
"id": "60275aea4ec95e16980cad4c4ee421730db86935",
"size": "737",
"binary": false,
"copies": "26",
"ref": "refs/heads/master",
"path": "ExternalDependencies/tools/cmake/share/cmake-2.8/Modules/CMakeFindWMake.cmake",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "1971830"
},
{
"name": "C++",
"bytes": "2900985"
},
{
"name": "CSS",
"bytes": "14544"
},
{
"name": "CoffeeScript",
"bytes": "3287"
},
{
"name": "Emacs Lisp",
"bytes": "11709"
},
{
"name": "FORTRAN",
"bytes": "1781"
},
{
"name": "JavaScript",
"bytes": "1314"
},
{
"name": "Objective-C",
"bytes": "66865"
},
{
"name": "PowerShell",
"bytes": "1505"
},
{
"name": "Shell",
"bytes": "2051"
},
{
"name": "TypeScript",
"bytes": "11215"
},
{
"name": "VimL",
"bytes": "8070"
}
],
"symlink_target": ""
} |
case node['platform_family']
when 'debian'
package 'libapache2-mod-python'
when 'rhel', 'fedora'
package 'mod_python' do
notifies :run, 'execute[generate-module-list]', :immediately
end
end
file "#{node['apache']['dir']}/conf.d/python.conf" do
action :delete
backup false
end
apache_module 'python'
| {
"content_hash": "4c08189a5b6a73f8d5b41182acef32f7",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 64,
"avg_line_length": 21,
"alnum_prop": 0.7015873015873015,
"repo_name": "thomasmeeus/chef-apache2",
"id": "950a8c47d303cba75d2dc40cb9a6c8e447ca37fa",
"size": "953",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "recipes/mod_python.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Perl",
"bytes": "847"
},
{
"name": "Ruby",
"bytes": "187720"
}
],
"symlink_target": ""
} |
define(['exports', 'module', 'react', '../ModalTrigger'], function (exports, module, _react, _ModalTrigger) {
'use strict';
function _interopRequire(obj) { return obj && obj.__esModule ? obj['default'] : obj; }
var _React = _interopRequire(_react);
var _ModalTrigger2 = _interopRequire(_ModalTrigger);
module.exports = _React.createFactory(_ModalTrigger2);
});
| {
"content_hash": "a7ace6e27d29ecb3d8d76b7d488448aa",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 109,
"avg_line_length": 34.09090909090909,
"alnum_prop": 0.6773333333333333,
"repo_name": "askerry/pyxley",
"id": "9623840c37fd5de3ecc03c0e18903299cb4d5834",
"size": "375",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "examples/datamaps/project/static/bower_components/react-bootstrap/lib/factories/ModalTrigger.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3839"
},
{
"name": "HTML",
"bytes": "2640"
},
{
"name": "JavaScript",
"bytes": "83511"
},
{
"name": "Python",
"bytes": "41506"
}
],
"symlink_target": ""
} |
@interface PodsDummy_TNSlider : NSObject
@end
@implementation PodsDummy_TNSlider
@end
| {
"content_hash": "bf27d0c2efbe00bd418ee2f2fe88eb4a",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 40,
"avg_line_length": 21.5,
"alnum_prop": 0.8255813953488372,
"repo_name": "tiennth/TNSlider",
"id": "5f00342c02b2cac1bc9a17411f274cdb5d4a6cd8",
"size": "120",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Example/Pods/Target Support Files/TNSlider/TNSlider-dummy.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "1382"
},
{
"name": "Ruby",
"bytes": "1177"
},
{
"name": "Shell",
"bytes": "8774"
},
{
"name": "Swift",
"bytes": "17026"
}
],
"symlink_target": ""
} |
package com.github.nscala_time
package object time{
private[time] type Super = AnyVal
}
| {
"content_hash": "393b304d5ad78f84c5deb76b94474a37",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 35,
"avg_line_length": 18.2,
"alnum_prop": 0.7582417582417582,
"repo_name": "beni55/nscala-time",
"id": "84bc079055f188af694310bca6565833c4f82a4f",
"size": "91",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/main/scala210/com/github/nscala_time/time/package.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "82853"
}
],
"symlink_target": ""
} |
#ifndef _ASM_TYPES_H
#define _ASM_TYPES_H
#include <asm-generic/int-ll64.h>
/*
* These aren't exported outside the kernel to avoid name space clashes
*/
#ifdef __KERNEL__
#define BITS_PER_LONG 32
#endif /* __KERNEL__ */
#endif /* _ASM_TYPES_H */
| {
"content_hash": "825bab7e163ba49568bc10ef5998d217",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 71,
"avg_line_length": 15,
"alnum_prop": 0.6549019607843137,
"repo_name": "endplay/omniplay",
"id": "390a612f3a58e1c611c64ac0212f8670115e82e3",
"size": "645",
"binary": false,
"copies": "4647",
"ref": "refs/heads/master",
"path": "linux-lts-quantal-3.5.0/arch/frv/include/asm/types.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "ASP",
"bytes": "4528"
},
{
"name": "Assembly",
"bytes": "17491433"
},
{
"name": "Awk",
"bytes": "79791"
},
{
"name": "Batchfile",
"bytes": "903"
},
{
"name": "C",
"bytes": "444772157"
},
{
"name": "C++",
"bytes": "10631343"
},
{
"name": "GDB",
"bytes": "17950"
},
{
"name": "HTML",
"bytes": "47935"
},
{
"name": "Java",
"bytes": "2193"
},
{
"name": "Lex",
"bytes": "44513"
},
{
"name": "M4",
"bytes": "9029"
},
{
"name": "Makefile",
"bytes": "1758605"
},
{
"name": "Objective-C",
"bytes": "5278898"
},
{
"name": "Perl",
"bytes": "649746"
},
{
"name": "Perl 6",
"bytes": "1101"
},
{
"name": "Python",
"bytes": "585875"
},
{
"name": "RPC",
"bytes": "97869"
},
{
"name": "Roff",
"bytes": "2522798"
},
{
"name": "Scilab",
"bytes": "21433"
},
{
"name": "Shell",
"bytes": "426172"
},
{
"name": "TeX",
"bytes": "283872"
},
{
"name": "UnrealScript",
"bytes": "6143"
},
{
"name": "XS",
"bytes": "1240"
},
{
"name": "Yacc",
"bytes": "93190"
},
{
"name": "sed",
"bytes": "9202"
}
],
"symlink_target": ""
} |
package org.apache.tajo.engine.eval;
import org.apache.tajo.catalog.Schema;
import org.apache.tajo.common.TajoDataTypes.DataType;
import org.apache.tajo.datum.Datum;
import org.apache.tajo.exception.InvalidOperationException;
import org.apache.tajo.storage.Tuple;
public class PartialBinaryExpr extends BinaryEval {
public PartialBinaryExpr(EvalType type) {
super(type);
}
public PartialBinaryExpr(EvalType type, EvalNode left, EvalNode right) {
super(type);
this.leftExpr = left;
this.rightExpr = right;
// skip to determine the result type
}
@Override
public DataType getValueType() {
return null;
}
@Override
public String getName() {
return "nonamed";
}
@Override
public Datum eval(Schema schema, Tuple tuple) {
throw new InvalidOperationException("ERROR: the partial binary expression cannot be evluated: "
+ this.toString());
}
@Override
public boolean equals(Object obj) {
if (obj instanceof PartialBinaryExpr) {
PartialBinaryExpr other = (PartialBinaryExpr) obj;
return type.equals(other.type) &&
leftExpr.equals(other.leftExpr) &&
rightExpr.equals(other.rightExpr);
}
return false;
}
public String toString() {
return
(leftExpr != null ? leftExpr.toString() : "[EMPTY]")
+ " " + type + " "
+ (rightExpr != null ? rightExpr.toString() : "[EMPTY]");
}
}
| {
"content_hash": "6b4dea230264fcb0780eb18b27e43895",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 99,
"avg_line_length": 25.07017543859649,
"alnum_prop": 0.6731980405878236,
"repo_name": "yeeunshim/tajo_test",
"id": "40966e502a3996a0be20b51c08e535b88a3e910a",
"size": "2235",
"binary": false,
"copies": "1",
"ref": "refs/heads/yeeun",
"path": "tajo-core/src/main/java/org/apache/tajo/engine/eval/PartialBinaryExpr.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "40820"
},
{
"name": "CSS",
"bytes": "3794"
},
{
"name": "Java",
"bytes": "6319806"
},
{
"name": "JavaScript",
"bytes": "502571"
},
{
"name": "Python",
"bytes": "18628"
},
{
"name": "Shell",
"bytes": "64783"
},
{
"name": "XSLT",
"bytes": "1329"
}
],
"symlink_target": ""
} |
// MIT License. Copyright (c) 2016 Maxim Kuzmin. Contacts: https://github.com/maxim-kuzmin
// Author: Maxim Kuzmin
namespace Makc2016.Modules.AspNetIdentity.Web.Mvc.Account.Actions
{
internal class ModuleAspNetIdentityWebMvcAccountActionTwoFactorCodeVerify
{
#region Constatns
public const string VIEW_NAME = "TwoFactorCodeVerify";
public const string ROUTE_NAME = "verify-code";
#endregion Constatns
}
} | {
"content_hash": "4d84b4665f1dcb50ac417603329719e8",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 91,
"avg_line_length": 26.705882352941178,
"alnum_prop": 0.7202643171806168,
"repo_name": "maxim-kuzmin/Makc2016",
"id": "7960e3cdab34e9e27efe37ade313b583f4a68012",
"size": "456",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Makc2016.Modules.AspNetIdentity.Web/Mvc/Account/Actions/ModuleAspNetIdentityWebMvcAccountActionTwoFactorCodeVerify.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "111"
},
{
"name": "C#",
"bytes": "1281744"
},
{
"name": "CSS",
"bytes": "127410"
},
{
"name": "HTML",
"bytes": "28268"
},
{
"name": "JavaScript",
"bytes": "3102769"
},
{
"name": "PLSQL",
"bytes": "1238"
},
{
"name": "PLpgSQL",
"bytes": "22050"
}
],
"symlink_target": ""
} |
from pgcli.packages.expanded import expanded_table
import pytest
def test_expanded_table_renders():
input = [("hello", 123),("world", 456)]
expected = """-[ RECORD 0 ]
name | hello
age | 123
-[ RECORD 1 ]
name | world
age | 456
"""
assert expected == expanded_table(input, ["name", "age"])
| {
"content_hash": "a8d12854997e1936fc1f72a9e2c5af25",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 61,
"avg_line_length": 21.857142857142858,
"alnum_prop": 0.6372549019607843,
"repo_name": "czchen/debian-pgcli",
"id": "6f2c6591c3216889f96c130869a352bfdbb4634b",
"size": "306",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tests/test_expanded.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "185742"
}
],
"symlink_target": ""
} |
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "bulk.h"
//#define WITH_BULK_DEBUG 1
const char* bulk_get_compression_flags_string(UINT32 flags)
{
flags &= BULK_COMPRESSION_FLAGS_MASK;
if (flags == 0)
return "PACKET_UNCOMPRESSED";
else if (flags == PACKET_COMPRESSED)
return "PACKET_COMPRESSED";
else if (flags == PACKET_AT_FRONT)
return "PACKET_AT_FRONT";
else if (flags == PACKET_FLUSHED)
return "PACKET_FLUSHED";
else if (flags == (PACKET_COMPRESSED | PACKET_AT_FRONT))
return "PACKET_COMPRESSED | PACKET_AT_FRONT";
else if (flags == (PACKET_COMPRESSED | PACKET_FLUSHED))
return "PACKET_COMPRESSED | PACKET_FLUSHED";
else if (flags == (PACKET_AT_FRONT | PACKET_FLUSHED))
return "PACKET_AT_FRONT | PACKET_FLUSHED";
else if (flags == (PACKET_COMPRESSED | PACKET_AT_FRONT | PACKET_FLUSHED))
return "PACKET_COMPRESSED | PACKET_AT_FRONT | PACKET_FLUSHED";
return "PACKET_UNKNOWN";
}
UINT32 bulk_compression_level(rdpBulk* bulk)
{
rdpSettings* settings = bulk->context->settings;
bulk->CompressionLevel = (settings->CompressionLevel >= 2) ? 2 : settings->CompressionLevel;
return bulk->CompressionLevel;
}
UINT32 bulk_compression_max_size(rdpBulk* bulk)
{
bulk_compression_level(bulk);
bulk->CompressionMaxSize = (bulk->CompressionLevel < 1) ? 8192 : 65536;
return bulk->CompressionMaxSize;
}
int bulk_compress_validate(rdpBulk* bulk, BYTE* pSrcData, UINT32 SrcSize, BYTE** ppDstData, UINT32* pDstSize, UINT32* pFlags)
{
int status;
BYTE* _pSrcData = NULL;
BYTE* _pDstData = NULL;
UINT32 _SrcSize = 0;
UINT32 _DstSize = 0;
UINT32 _Flags = 0;
_pSrcData = *ppDstData;
_SrcSize = *pDstSize;
_Flags = *pFlags | bulk->CompressionLevel;
status = bulk_decompress(bulk, _pSrcData, _SrcSize, &_pDstData, &_DstSize, _Flags);
if (status < 0)
{
printf("compression/decompression failure\n");
return status;
}
if (_DstSize != SrcSize)
{
printf("compression/decompression size mismatch: Actual: %d, Expected: %d\n", _DstSize, SrcSize);
return -1;
}
if (memcmp(_pDstData, pSrcData, SrcSize) != 0)
{
printf("compression/decompression input/output mismatch! flags: 0x%04X\n", _Flags);
#if 1
printf("Actual:\n");
winpr_HexDump(_pDstData, SrcSize);
printf("Expected:\n");
winpr_HexDump(pSrcData, SrcSize);
#endif
return -1;
}
return status;
}
int bulk_decompress(rdpBulk* bulk, BYTE* pSrcData, UINT32 SrcSize, BYTE** ppDstData, UINT32* pDstSize, UINT32 flags)
{
UINT32 type;
int status = -1;
UINT32 CompressedBytes;
UINT32 UncompressedBytes;
bulk_compression_max_size(bulk);
type = flags & BULK_COMPRESSION_TYPE_MASK;
if (flags & BULK_COMPRESSION_FLAGS_MASK)
{
switch (type)
{
case PACKET_COMPR_TYPE_8K:
mppc_set_compression_level(bulk->mppcRecv, 0);
status = mppc_decompress(bulk->mppcRecv, pSrcData, SrcSize, ppDstData, pDstSize, flags);
break;
case PACKET_COMPR_TYPE_64K:
mppc_set_compression_level(bulk->mppcRecv, 1);
status = mppc_decompress(bulk->mppcRecv, pSrcData, SrcSize, ppDstData, pDstSize, flags);
break;
case PACKET_COMPR_TYPE_RDP6:
status = ncrush_decompress(bulk->ncrushRecv, pSrcData, SrcSize, ppDstData, pDstSize, flags);
break;
case PACKET_COMPR_TYPE_RDP61:
status = -1;
break;
case PACKET_COMPR_TYPE_RDP8:
status = -1;
break;
}
}
else
{
*ppDstData = pSrcData;
*pDstSize = SrcSize;
status = 0;
}
if (status >= 0)
{
CompressedBytes = SrcSize;
UncompressedBytes = *pDstSize;
bulk->TotalUncompressedBytes += UncompressedBytes;
bulk->TotalCompressedBytes += CompressedBytes;
#ifdef WITH_BULK_DEBUG
{
double CompressionRatio;
double TotalCompressionRatio;
CompressionRatio = ((double) CompressedBytes) / ((double) UncompressedBytes);
TotalCompressionRatio = ((double) bulk->TotalCompressedBytes) / ((double) bulk->TotalUncompressedBytes);
printf("Decompress Type: %d Flags: %s (0x%04X) Compression Ratio: %f (%d / %d), Total: %f (%d / %d)\n",
type, bulk_get_compression_flags_string(flags), flags,
CompressionRatio, CompressedBytes, UncompressedBytes,
TotalCompressionRatio, bulk->TotalCompressedBytes, bulk->TotalUncompressedBytes);
}
#endif
}
else
{
fprintf(stderr, "Decompression failure!\n");
}
return status;
}
int bulk_compress(rdpBulk* bulk, BYTE* pSrcData, UINT32 SrcSize, BYTE** ppDstData, UINT32* pDstSize, UINT32* pFlags)
{
int status = -1;
UINT32 CompressedBytes;
UINT32 UncompressedBytes;
if ((SrcSize <= 50) || (SrcSize >= 16384))
{
*ppDstData = pSrcData;
*pDstSize = SrcSize;
return 0;
}
*ppDstData = bulk->OutputBuffer;
*pDstSize = sizeof(bulk->OutputBuffer);
bulk_compression_level(bulk);
bulk_compression_max_size(bulk);
if (bulk->CompressionLevel < PACKET_COMPR_TYPE_RDP6)
{
mppc_set_compression_level(bulk->mppcSend, bulk->CompressionLevel);
status = mppc_compress(bulk->mppcSend, pSrcData, SrcSize, ppDstData, pDstSize, pFlags);
}
else
{
status = ncrush_compress(bulk->ncrushSend, pSrcData, SrcSize, ppDstData, pDstSize, pFlags);
}
if (status >= 0)
{
CompressedBytes = *pDstSize;
UncompressedBytes = SrcSize;
bulk->TotalUncompressedBytes += UncompressedBytes;
bulk->TotalCompressedBytes += CompressedBytes;
#ifdef WITH_BULK_DEBUG
{
UINT32 type;
double CompressionRatio;
double TotalCompressionRatio;
type = bulk->CompressionLevel;
CompressionRatio = ((double) CompressedBytes) / ((double) UncompressedBytes);
TotalCompressionRatio = ((double) bulk->TotalCompressedBytes) / ((double) bulk->TotalUncompressedBytes);
printf("Compress Type: %d Flags: %s (0x%04X) Compression Ratio: %f (%d / %d), Total: %f (%d / %d)\n",
type, bulk_get_compression_flags_string(*pFlags), *pFlags,
CompressionRatio, CompressedBytes, UncompressedBytes,
TotalCompressionRatio, bulk->TotalCompressedBytes, bulk->TotalUncompressedBytes);
}
#endif
}
#if 0
if (bulk_compress_validate(bulk, pSrcData, SrcSize, ppDstData, pDstSize, pFlags) < 0)
status = -1;
#endif
return status;
}
void bulk_reset(rdpBulk* bulk)
{
mppc_context_reset(bulk->mppcSend);
mppc_context_reset(bulk->mppcRecv);
ncrush_context_reset(bulk->ncrushRecv);
ncrush_context_reset(bulk->ncrushSend);
}
rdpBulk* bulk_new(rdpContext* context)
{
rdpBulk* bulk;
bulk = (rdpBulk*) calloc(1, sizeof(rdpBulk));
if (bulk)
{
bulk->context = context;
bulk->mppcSend = mppc_context_new(1, TRUE);
bulk->mppcRecv = mppc_context_new(1, FALSE);
bulk->ncrushRecv = ncrush_context_new(FALSE);
bulk->ncrushSend = ncrush_context_new(TRUE);
bulk->CompressionLevel = context->settings->CompressionLevel;
bulk->TotalCompressedBytes = 0;
bulk->TotalUncompressedBytes = 0;
}
return bulk;
}
void bulk_free(rdpBulk* bulk)
{
if (!bulk)
return;
mppc_context_free(bulk->mppcSend);
mppc_context_free(bulk->mppcRecv);
ncrush_context_free(bulk->ncrushRecv);
ncrush_context_free(bulk->ncrushSend);
free(bulk);
}
| {
"content_hash": "27ff9dc221535e34bc346851a51739e4",
"timestamp": "",
"source": "github",
"line_count": 278,
"max_line_length": 125,
"avg_line_length": 24.91007194244604,
"alnum_prop": 0.7048375451263538,
"repo_name": "0359xiaodong/FreeRDP",
"id": "f1d7eca1fe5185284223a1fa45096e8c5ef693a7",
"size": "7631",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "libfreerdp/core/bulk.c",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#ifndef TENSORFLOW_C_EXPERIMENTAL_OPS_GEN_CPP_VIEWS_ATTR_VIEW_H_
#define TENSORFLOW_C_EXPERIMENTAL_OPS_GEN_CPP_VIEWS_ATTR_VIEW_H_
#include "tensorflow/c/experimental/ops/gen/model/attr_spec.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace generator {
namespace cpp {
class AttrView {
public:
explicit AttrView(AttrSpec attr) : attr_(attr) {}
string VariableName() const;
string VariableType() const;
string AttrNameString() const;
string VariableStrLen() const;
string VariableSpanData() const;
string VariableSpanLen() const;
string DefaultValue() const;
string InputArg(bool with_default_value) const;
string SetterMethod() const;
std::vector<string> SetterArgs() const;
private:
AttrSpec attr_;
};
} // namespace cpp
} // namespace generator
} // namespace tensorflow
#endif // TENSORFLOW_C_EXPERIMENTAL_OPS_GEN_CPP_VIEWS_ATTR_VIEW_H_
| {
"content_hash": "b96842d81653121105a14df4116f6eb5",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 67,
"avg_line_length": 25.914285714285715,
"alnum_prop": 0.7453142227122381,
"repo_name": "yongtang/tensorflow",
"id": "194c70e7c02496f1f7566930f2a01e51be3273a0",
"size": "1575",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "tensorflow/c/experimental/ops/gen/cpp/views/attr_view.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "36962"
},
{
"name": "C",
"bytes": "1368342"
},
{
"name": "C#",
"bytes": "13584"
},
{
"name": "C++",
"bytes": "125162438"
},
{
"name": "CMake",
"bytes": "179878"
},
{
"name": "Cython",
"bytes": "5003"
},
{
"name": "Dockerfile",
"bytes": "416133"
},
{
"name": "Go",
"bytes": "2118448"
},
{
"name": "HTML",
"bytes": "4686483"
},
{
"name": "Java",
"bytes": "1074438"
},
{
"name": "Jupyter Notebook",
"bytes": "792868"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "MLIR",
"bytes": "11205807"
},
{
"name": "Makefile",
"bytes": "2760"
},
{
"name": "Objective-C",
"bytes": "172666"
},
{
"name": "Objective-C++",
"bytes": "300198"
},
{
"name": "Pawn",
"bytes": "5552"
},
{
"name": "Perl",
"bytes": "7536"
},
{
"name": "Python",
"bytes": "42642473"
},
{
"name": "Roff",
"bytes": "5034"
},
{
"name": "Ruby",
"bytes": "9199"
},
{
"name": "Shell",
"bytes": "621427"
},
{
"name": "Smarty",
"bytes": "89545"
},
{
"name": "SourcePawn",
"bytes": "14607"
},
{
"name": "Starlark",
"bytes": "7577804"
},
{
"name": "Swift",
"bytes": "78435"
},
{
"name": "Vim Snippet",
"bytes": "58"
}
],
"symlink_target": ""
} |
<?php
function rb_getParamsFromUrl($mediaURL){
$params = array();
$urlSections = explode('/', $mediaURL);
$lastSection = end($urlSections);
$qmPosition = stripos($lastSection,'?');
if(stripos($mediaURL, '?')!==false)
$params['vurl'] = substr($mediaURL, 0, stripos($mediaURL, '?'));
else
$params['vurl'] = $mediaURL;
if($qmPosition>-1){
$params['v'] = substr($lastSection, 0, $qmPosition);
$queryString = substr($lastSection, $qmPosition+1);
$qsSections = explode('&', $queryString);
for($i=0; $i<sizeof($qsSections); $i++){
$keyValue = explode('=', $qsSections[$i]);
if(sizeof($keyValue)==2)
$params[$keyValue[0]] = $keyValue[1];
}
}else{
$params['v'] = $lastSection;
}
return $params;
}
function rb_is_assoc($array) {
return (bool)count(array_filter(array_keys($array), 'is_string'));
}
function rb_getSource($sourceData, $imageW, $imageH, $addParams=null)
{
if(!empty($sourceData))
{
$embedCode = '';
$sourceType = rb_getMediaType(trim($sourceData));
$ext = rb_getMediaType(trim($sourceData), 'ext');
$mediaParams = rb_getParamsFromUrl(trim($sourceData));
if(empty($sourceType))
return '';
if($sourceType=='vimeo')
$embedCode = '<iframe class="iframevideo" src="http://player.vimeo.com/video/'.$mediaParams['v'].'?title=0&byline=0&portrait=0" width="'.$imageW.'" height="'.$imageH.'" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>';
elseif($sourceType=='youtube')
$embedCode = '<iframe class="iframevideo" width="'.$imageW.'" height="'.$imageH.'" src="http://www.youtube.com/embed/'.$mediaParams['v'].'?wmode=transparent&rel=0" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowfullscreen></iframe>';
elseif($sourceType=='embedplayer' || $sourceType=='embedaudioplayer')
{
$rand = createRandomKey(5);
if($sourceType=='embedaudioplayer'){
$imageW = '100%';
$imageH = '100px';
}
$embedprefixe = 'embedplayer';
$poster = (!empty($addParams['image']))?$addParams['image']:'';
$mediatype = ($sourceType=='embedaudioplayer')?'audio':'video';
if($sourceType=='embedaudioplayer') $embedprefixe = 'embedaudioplayer';
$embedCode = '<video id="'.$embedprefixe.'_'.$rand.'" class="video-js embed-videojs vjs-default-skin" controls preload="none" width="'.$imageW.'" height="'.$imageH.'"
poster="'.$poster.'"
data-setup="{}">
<source src="'.$mediaParams['vurl'].'" type="'.$mediatype.'/'.$ext.'" />
</video>';
}
return $embedCode;
}
}
function rb_getMediaType($mediaUrl, $type='type'){
if (stripos($mediaUrl, 'youtu.be')!==false || stripos($mediaUrl, 'youtube.com/watch')!==false)
return 'youtube';
else if(stripos($mediaUrl,'vimeo.com')!==false)
return 'vimeo';
else{
$extensions = explode('.',$mediaUrl);
if(sizeof($extensions)>1)
{
$qmPosition = stripos(end($extensions),'?');
if($qmPosition>0)
$le = substr(end($extensions), $qmPosition);
else
$le = end($extensions);
$le = strtolower($le);
if($type=='type'){
if($le=='flv' || $le=='f4v' || $le=='m4v' || $le=='mp4' || $le=='mov' || $le=='webm')
return 'embedplayer';
else if($le=='aac' || $le=='m4a' || $le=='f4a' || $le=='ogg' || $le=='oga' || $le=='mp3')
return 'embedaudioplayer';
else if($le=='swf')
return 'flash';
else
return '';
}else{
return $le;
}
}else
return '';
}
}
if(!function_exists('rb_get_dynamic_sidebar')){
function rb_get_dynamic_sidebar($index = 1)
{
$sidebar_contents = "";
ob_start();
dynamic_sidebar($index);
$sidebar_contents = ob_get_clean();
return $sidebar_contents;
}
}
function rb_pageTitle(){
global $post;
$Rb_pageTitle = '';
if(is_search()) {
if(have_posts()){
$Rb_pageTitle .= __('Results for ','rb').'"'.get_search_query().'"';
}else{
$Rb_pageTitle .= __('Not found for ','rb').'"'.get_search_query().'"';
}
}elseif(is_page()){
if(have_posts()){
$Rb_pageTitle .= get_the_title();
}else{
$Rb_pageTitle .= __('Page request could not be found.','rb');
}
}elseif(is_tag()){
if(have_posts()){
$Rb_pageTitle .= __('Tag, ','rb').single_tag_title('',false);
}else{
$Rb_pageTitle .= __('Tag request could not be found.','rb');
}
}elseif(is_category()){
if(have_posts()){
$Rb_pageTitle .= __('Category, ','rb').single_tag_title('',false);
}else{
$Rb_pageTitle .= __('Category request could not be found.','rb');
}
}elseif(is_archive()){
if(have_posts()){
$Rb_pageTitle .='';
if(is_day())
$Rb_pageTitle .= __('Daily Archives, ','rb').get_the_date();
elseif(is_month())
$Rb_pageTitle .= __('Monthly Archives, ','rb').get_the_date('F Y');
elseif(is_year())
$Rb_pageTitle .= __('Yearly Archives, ','rb').get_the_date('Y');
elseif(is_tax('rb-project-categories')){
$Rb_pageTitle .= __('Project Category, ','rb');
$term = get_term_by( 'name', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
$Rb_pageTitle .= $term->name;
}
elseif(is_tax('rb-portfolio-categories')){
$Rb_pageTitle .= __('Portfolio Category, ','rb');
$term = get_term_by( 'name', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
$Rb_pageTitle .= $term->name;
}
else
$Rb_pageTitle .= __('Blog Archives','rb');
$Rb_pageTitle .= '';
}else{
$Rb_pageTitle .= __('Archive request could not be found.','rb');
}
}elseif(is_404()){
$Rb_pageTitle .= __('You may find your requested page by searching.','rb');
}else{
$Rb_pageTitle .= get_the_title();
}
return $Rb_pageTitle;
}
function rb_getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0 View";
}
return $count.' Views';
}
function rb_setPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
function rb_getPinterestInfo($postID){
$blogformat = strtolower( get_post_format($postID) );
$attachment_url = wp_get_attachment_url(get_post_thumbnail_id($postID));
$imageurl = '';
if( ($blogformat == 'standart' || $blogformat == '') && !empty($attachment_url) ){
$imageurl = $attachment_url;
}elseif($blogformat == 'image'){
$imageformaturl = get_post_meta($postID, "rb_format_big_image_url", true);
if(!empty($imageformaturl))
$imageurl = $imageformaturl;
elseif(!empty($attachment_url))
$imageurl = $attachment_url;
}elseif($blogformat == 'gallery'){
if(!empty($attachment_url))
$imageurl = $attachment_url;
}
if(!empty($imageurl)){
return array('image'=>$imageurl, 'description'=>rb_get_excerpt(200, 'content', $postID));
}else
return false;
}
function rb_get_excerpt($limit, $source = null, $postID = 0){
if($source == "content"){
if($postID>0){
$content_post = get_post($postID);
$excerpt = $content_post->post_content;
}else{
$excerpt = get_the_content();
}
}else{
$excerpt = get_the_excerpt();
}
return rb_excerpt_text($excerpt, $limit);
}
function rb_excerpt_text($excerpt, $limit){
$excerpt = preg_replace(" (\[.*?\])",'',$excerpt);
$excerpt = strip_shortcodes($excerpt);
$excerpt = strip_tags($excerpt);
$excerpt = substr($excerpt, 0, $limit);
$excerpt = substr($excerpt, 0, strripos($excerpt, " "));
$excerpt = trim(preg_replace( '/\s+/', ' ', $excerpt));
return $excerpt;
}
function rb_getSettingsItem($itemid){
global $Rb_SettingsOptions;
$re = false;
foreach($Rb_SettingsOptions as $sm){
if($sm['type']=='fields'){
foreach($sm['fields'] as $field){
if($field['id']==$itemid){
$re = $field;
break;
}
}
}
}
return $re;
}
if(!function_exists('rb_sh2array')){
function rb_sh2array($content, $depth=0)
{
$pattern = get_shortcode_regex();
$depth ++;
preg_match_all( "/$pattern/s", $content , $matches);
$return = array();
foreach($matches[3] as $key => $value)
{
$return[$key]['shortcode'] = $matches[2][$key];
$return[$key]['attr'] = shortcode_parse_atts( $value );
if(preg_match("/$pattern/s", $matches[5][$key]) && $depth)
$return[$key]['content'] = rb_sh2array($matches[5][$key], $depth);
else
$return[$key]['content'] = $matches[5][$key];
}
return $return;
}
}
function rb_getFont($name, $type='url', $opt='')
{
$fonts = json_decode(get_option('fonts'));
$font;
for($i=0; $i<sizeof($fonts->items); $i++)
{
if($fonts->items[$i]->family==$name)
{
$font = $fonts->items[$i];
break;
}
}
if($type=='url' && isset($font))
{
$url = 'http://fonts.googleapis.com/css?family='.urlencode($font->family);
if(sizeof($font->variants)>1){
$url .= ':'.implode(',',$font->variants);
}
if(sizeof($font->subsets)>1){
$url .= '&subset='.implode(',',$font->subsets);
}
return $url;
}
if($type=='variants' && isset($font))
{
return $font->variants;
}
if($type=='collation' && isset($font)){
$collation = '';
if($font->category=='display' || $font->category=='handwriting')
$collation = 'cursive';
else
$collation = $font->category;
return $font->family.', '.$collation;
}
}
function rb_opt($v, $def)
{
if($v=='contentFontFull' || $v=='headerFontFull')
{
$v = str_replace('Full','', $v);
return rb_getFont(rb_opt($v,''),'url',$v);
}
elseif($v=='contentFontCollation' || $v=='headerFontCollation'){
$v = str_replace('Collation','', $v);
return rb_getFont(rb_opt($v,''),'collation',$v);
}else{
$val = get_option($v, $def);
return $val;
}
}
function rb_eopt($v, $def)
{
echo rb_opt($v, $def);
}
function addionalCharacter($URL){
if(strpos($URL, '/')===false){
$pageName = $URL;
}else{
$pageName = end(explode('/',$URL));
}
if(strpos($URL, '?')===false)
return '?';
else
return '&';
}
function rb_get_pagination($wp_res=null){
if(!$wp_res){
global $wp_query;
$wp_res = $wp_query;
}
$re = '';
if(function_exists('wp_pagenavi')){
$navHtml = wp_pagenavi( array( 'query' => $wp_res, 'echo' => false, 'options'=>array('first_text'=>' ', 'last_text'=>' ', 'prev_text'=>' ', 'next_text'=>' ') ));
$navHtml = str_replace('&info=page','',$navHtml);
$navHtml = str_replace('?info=page','',$navHtml);
$re .= $navHtml;
}else{
if($wp_res->found_posts > $wp_res->query_vars['posts_per_page'])
{
$re .= '<div class="element-pagination">';
$big = 999999999; // need an unlikely integer
$pLinks = paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_res->max_num_pages,
'type' => 'array',
'prev_text' => __('Previous', 'rb'),
'next_text' => __('Next', 'rb'),
) );
$re .= '<ul class="pagination">';
foreach($pLinks as $plink){
$re .= '<li>'.$plink.'</li>';
}
$re .= '</ul>';
$re .= '</div>';
}
}
return $re;
}
function rb_clean_spaces($content){
$content = str_replace("\r", ' ', $content);
$content = str_replace("\n", ' ', $content);
$content = str_replace("\t", ' ', $content);
$content = force_balance_tags($content);
return $content;
}
function rb_get_top_section(){
if(is_front_page())
$rb_topsection = rb_opt('topsectionhome', 'none');
else
$rb_topsection = rb_opt('topsectionother', 'none');
$rb_top = rb_find_top_section($rb_topsection);
rb_show_top_section($rb_top[0], $rb_top[1]);
}
function rb_find_top_section($rb_topsection){
$type = 'none';
$content = '';
if(! (empty($rb_topsection) || $rb_topsection=='none')){
$pos = strpos($rb_topsection, 'revslider::');
if($pos===false){
$pos = strpos($rb_topsection, 'page::');
if($pos===false){
$type = 'none';
}else{
$type = 'page';
$content = substr($rb_topsection, $pos+6);
}
}else{
$type = 'revslider';
$content = substr($rb_topsection, $pos+11);
}
}
return array($type, $content);
}
function rb_show_top_section($type, $content){
if($type=='revslider' && function_exists('putRevSlider') && !empty($content)){
echo '<div class="paralax-revslider">';
putRevSlider($content);
echo '</div>';
}
elseif($type=='page' && !empty($content) ){
$page = get_post( $content );
if(isset($page)){
$pageContent = apply_filters('the_content', $page->post_content );
$pageContent = '<section id="top_section" class="effect-waypoint">'.$pageContent.'</section>';
$pageContent = rb_clean_spaces($pageContent);
$pageContent = wpautop($pageContent);
echo $pageContent;
}
}else{
// topsection is none
}
}
?> | {
"content_hash": "9e34d4abea97b68cf76829fd496a288c",
"timestamp": "",
"source": "github",
"line_count": 451,
"max_line_length": 265,
"avg_line_length": 29.587583148558757,
"alnum_prop": 0.56939448441247,
"repo_name": "VirtualSensitive/website",
"id": "445e47ed17363215e652f1f2b5816dbc9a237e57",
"size": "13344",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "wp-content/themes/federal/includes/helper-functions.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2171570"
},
{
"name": "JavaScript",
"bytes": "3208941"
},
{
"name": "PHP",
"bytes": "14109511"
}
],
"symlink_target": ""
} |
/*
Powerful digit counts
Problem 63
The 5-digit number, 16807=75, is also a fifth power. Similarly, the 9-digit number, 134217728=89, is a ninth power.
How many n-digit positive integers exist which are also an nth power?
*/ | {
"content_hash": "bf9b7aac5f078d42cbba2fc47c221165",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 115,
"avg_line_length": 32.142857142857146,
"alnum_prop": 0.76,
"repo_name": "sihrc/Personal-Code-Bin",
"id": "0c6d619635bd1fbdd5b11e8655e42978650bb686",
"size": "225",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "project-euler/problem_63.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "323010"
},
{
"name": "Java",
"bytes": "6324"
},
{
"name": "Python",
"bytes": "13971"
}
],
"symlink_target": ""
} |
.monaco-editor .margin-view-overlays .line-numbers {
position: absolute;
text-align: right;
display: inline-block;
vertical-align: middle;
box-sizing: border-box;
cursor: default;
height: 100%;
}
.monaco-editor .relative-current-line-number {
text-align: left;
display: inline-block;
width: 100%;
}
.monaco-editor .margin-view-overlays .line-numbers {
cursor: -webkit-image-set(
url('flipped-cursor.svg') 1x,
url('flipped-cursor-2x.svg') 2x
) 30 0, default;
}
.monaco-editor.mac .margin-view-overlays .line-numbers {
cursor: -webkit-image-set(
url('flipped-cursor-mac.svg') 1x,
url('flipped-cursor-mac-2x.svg') 2x
) 24 3, default;
}
.monaco-editor .margin-view-overlays .line-numbers.lh-odd {
margin-top: 1px;
}
| {
"content_hash": "9b35b675f1717e3c369ed7d93f188b36",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 59,
"avg_line_length": 21.17142857142857,
"alnum_prop": 0.7031039136302294,
"repo_name": "cleidigh/vscode",
"id": "3cfe5e758e2d7c78442f965f67e1f0af60e020a8",
"size": "1092",
"binary": false,
"copies": "18",
"ref": "refs/heads/master",
"path": "src/vs/editor/browser/viewParts/lineNumbers/lineNumbers.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "5385"
},
{
"name": "C",
"bytes": "818"
},
{
"name": "C#",
"bytes": "488"
},
{
"name": "C++",
"bytes": "1072"
},
{
"name": "CSS",
"bytes": "478388"
},
{
"name": "Clojure",
"bytes": "1206"
},
{
"name": "CoffeeScript",
"bytes": "590"
},
{
"name": "Dockerfile",
"bytes": "425"
},
{
"name": "F#",
"bytes": "634"
},
{
"name": "Go",
"bytes": "652"
},
{
"name": "Groovy",
"bytes": "3928"
},
{
"name": "HLSL",
"bytes": "184"
},
{
"name": "HTML",
"bytes": "42593"
},
{
"name": "Inno Setup",
"bytes": "165483"
},
{
"name": "Java",
"bytes": "599"
},
{
"name": "JavaScript",
"bytes": "856795"
},
{
"name": "Lua",
"bytes": "252"
},
{
"name": "Makefile",
"bytes": "2080"
},
{
"name": "Objective-C",
"bytes": "1387"
},
{
"name": "PHP",
"bytes": "998"
},
{
"name": "Perl",
"bytes": "857"
},
{
"name": "Perl 6",
"bytes": "1065"
},
{
"name": "PowerShell",
"bytes": "4774"
},
{
"name": "Python",
"bytes": "2405"
},
{
"name": "R",
"bytes": "362"
},
{
"name": "Roff",
"bytes": "351"
},
{
"name": "Ruby",
"bytes": "1703"
},
{
"name": "Rust",
"bytes": "532"
},
{
"name": "ShaderLab",
"bytes": "330"
},
{
"name": "Shell",
"bytes": "16893"
},
{
"name": "Swift",
"bytes": "284"
},
{
"name": "TypeScript",
"bytes": "20083090"
},
{
"name": "Visual Basic",
"bytes": "893"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "b23f6e51eb4bf5123fc4e9f8cf2c7fc0",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "314c6bcb7f2ae141cf89fb9c7213b02e7a3e6390",
"size": "180",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Erigeron brachyspermus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
This is the first version of this package to depend on GAX v4.
There are some breaking changes, both in GAX v4 and in the generated
code. The changes that aren't specific to any given API are [described in the Google Cloud
documentation](https://cloud.google.com/dotnet/docs/reference/help/breaking-gax4).
We don't anticipate any changes to most customer code, but please [file a
GitHub issue](https://github.com/googleapis/google-cloud-dotnet/issues/new/choose)
if you run into problems.
The most important change in this release is the use of the Grpc.Net.Client package
for gRPC communication, instead of Grpc.Core. When using .NET Core 3.1 or .NET 5.0+
this should lead to a smaller installation footprint and greater compatibility (e.g.
with Apple M1 chips). Any significant change in a core component comes with the risk
of incompatibility, however - so again, please let us know if you encounter any
issues.
## Version 2.3.0, released 2021-08-31
- [Commit ac367e2](https://github.com/googleapis/google-cloud-dotnet/commit/ac367e2): feat: Regenerate all APIs to support self-signed JWTs
## Version 2.2.0, released 2021-05-26
No API surface changes; just dependency updates.
## Version 2.1.0, released 2020-10-20
- [Commit fab7d7e](https://github.com/googleapis/google-cloud-dotnet/commit/fab7d7e): docs: Fix proto comments for language API inorder for docs parsing to work correctly. ([issue 5415](https://github.com/googleapis/google-cloud-dotnet/issues/5415))
- [Commit 0790924](https://github.com/googleapis/google-cloud-dotnet/commit/0790924): fix: Add gRPC compatibility constructors
- [Commit 0ca05f5](https://github.com/googleapis/google-cloud-dotnet/commit/0ca05f5): chore: Regenerate all APIs using protoc 3.13 and Grpc.Tools 2.31
- [Commit 6bde7a3](https://github.com/googleapis/google-cloud-dotnet/commit/6bde7a3): docs: Regenerate all APIs with service comments in client documentation
- [Commit 947a573](https://github.com/googleapis/google-cloud-dotnet/commit/947a573): docs: Regenerate all clients with more explicit documentation
- [Commit 7a0a214](https://github.com/googleapis/google-cloud-dotnet/commit/7a0a214): docs: change relative URLs to absolute URLs to fix broken links.
## Version 2.0.0, released 2020-03-18
No API surface changes compared with 2.0.0-beta01, just dependency
and implementation changes.
## Version 2.0.0-beta01, released 2020-02-17
This is the first prerelease targeting GAX v3. Please see the [breaking changes
guide](https://cloud.google.com/dotnet/docs/reference/help/breaking-gax2)
for details of changes to both GAX and code generation.
Additional breaking changes not covered in the guide:
- Legacy methods accepting nullable EncodingType parameters have been removed
## Version 1.4.0, released 2019-12-09
- [Commit 699db57](https://github.com/googleapis/google-cloud-dotnet/commit/699db57): Some retry settings are now obsolete, and will be removed in the next major version
- Methods accepting `Nullable<EncodingType>` parameters are now obsolete, and will be removed in the next major version.
(Equivalent methods with non-nullable parameters have been added.)
## Version 1.3.0, released 2019-07-10
- More entity `Type` enum values
- Added more sentiment analysis method overloads
## Version 1.2.0, released 2019-02-05
- Added async methods that accept requests (as well as the other signatures)
## Version 1.1.0, released 2017-11-14
- New feature: text classification
## Version 1.0.0, released 2017-09-19
Initial GA release.
| {
"content_hash": "51b670edbd88faf0e36f3a692c030d32",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 249,
"avg_line_length": 50.869565217391305,
"alnum_prop": 0.7811965811965812,
"repo_name": "jskeet/gcloud-dotnet",
"id": "77a623608ba73da475c7f69bcbb94cda9743a3da",
"size": "3568",
"binary": false,
"copies": "1",
"ref": "refs/heads/bq-migration",
"path": "apis/Google.Cloud.Language.V1/docs/history.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1725"
},
{
"name": "C#",
"bytes": "1829733"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_45) on Tue Dec 02 21:24:53 EST 2014 -->
<title>org.maltparser.core.helper (MaltParser 1.8.1)</title>
<meta name="date" content="2014-12-02">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.maltparser.core.helper (MaltParser 1.8.1)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>MaltParser 1.8.1</b></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/maltparser/core/flow/system/elem/package-summary.html">Prev Package</a></li>
<li><a href="../../../../org/maltparser/core/io/dataformat/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/maltparser/core/helper/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package org.maltparser.core.helper</h1>
<div class="docSummary">
<div class="block">Provides classes of various kinds that not fit into another package.</div>
</div>
<p>See: <a href="#package_description">Description</a></p>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/maltparser/core/helper/HashMap.html" title="class in org.maltparser.core.helper">HashMap</a><K,V></td>
<td class="colLast">
<div class="block">A memory-efficient hash map.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../org/maltparser/core/helper/HashSet.html" title="class in org.maltparser.core.helper">HashSet</a><E></td>
<td class="colLast">
<div class="block">A memory-efficient hash set.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/maltparser/core/helper/Malt04.html" title="class in org.maltparser.core.helper">Malt04</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../org/maltparser/core/helper/NoOutputStream.html" title="class in org.maltparser.core.helper">NoOutputStream</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/maltparser/core/helper/NoPrintStream.html" title="class in org.maltparser.core.helper">NoPrintStream</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../org/maltparser/core/helper/SystemInfo.html" title="class in org.maltparser.core.helper">SystemInfo</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/maltparser/core/helper/SystemLogger.html" title="class in org.maltparser.core.helper">SystemLogger</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../org/maltparser/core/helper/URLFinder.html" title="class in org.maltparser.core.helper">URLFinder</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/maltparser/core/helper/Util.html" title="class in org.maltparser.core.helper">Util</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
</ul>
<a name="package_description">
<!-- -->
</a>
<h2 title="Package org.maltparser.core.helper Description">Package org.maltparser.core.helper Description</h2>
<div class="block"><p>Provides classes of various kinds that not fit into another package.</p></div>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>MaltParser 1.8.1</b></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/maltparser/core/flow/system/elem/package-summary.html">Prev Package</a></li>
<li><a href="../../../../org/maltparser/core/io/dataformat/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/maltparser/core/helper/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright 2007-2014 Johan Hall, Jens Nilsson and Joakim Nivre.</small></p>
</body>
</html>
| {
"content_hash": "87b8547714bc0c48c079daa8dee09306",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 157,
"avg_line_length": 39.60220994475138,
"alnum_prop": 0.64453125,
"repo_name": "jerryyeezus/nlp-summarization",
"id": "7058398465b038f13d626f6a290fa99fb8810a50",
"size": "7168",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "maltparser/dist/maltparser-1.8.1/docs/api/org/maltparser/core/helper/package-summary.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "10226"
},
{
"name": "CSS",
"bytes": "30720"
},
{
"name": "E",
"bytes": "2831"
},
{
"name": "Forth",
"bytes": "2657"
},
{
"name": "Java",
"bytes": "1774038"
},
{
"name": "Perl",
"bytes": "108222"
},
{
"name": "Python",
"bytes": "98753"
},
{
"name": "Shell",
"bytes": "924"
},
{
"name": "TeX",
"bytes": "7823"
},
{
"name": "XSLT",
"bytes": "11436"
}
],
"symlink_target": ""
} |
<?php
namespace craft\volumes;
use Craft;
use craft\helpers\UrlHelper;
class Temp extends Local
{
// Static
// =========================================================================
/**
* @inheritdoc
*/
public static function displayName(): string
{
return Craft::t('app', 'Temp Folder');
}
// Public Methods
// =========================================================================
/**
* @inheritdoc
*/
public function init()
{
parent::init();
$this->hasUrls = true;
if ($this->path !== null) {
$this->path = rtrim($this->path, '/');
} else {
$this->path = Craft::$app->getPath()->getTempAssetUploadsPath();
}
if ($this->url === null) {
$this->url = UrlHelper::actionUrl('assets/download-temp-asset', ['path' => '']);
}
if ($this->name === null) {
$this->name = Craft::t('app', 'Temporary source');
}
}
/**
* @inheritdoc
*/
public function getSettingsHtml()
{
return null;
}
}
| {
"content_hash": "31639295ee280fb5be8c03ebf4bc63a7",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 92,
"avg_line_length": 20.107142857142858,
"alnum_prop": 0.413854351687389,
"repo_name": "ShaneHudson/ShaneHudson.Net",
"id": "95878af7e0d6afc7dc8e924e8e9904bba2a180eb",
"size": "1475",
"binary": false,
"copies": "1",
"ref": "refs/heads/craft3",
"path": "craft/vendor/craftcms/cms/src/volumes/Temp.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1288"
},
{
"name": "CSS",
"bytes": "436035"
},
{
"name": "HTML",
"bytes": "633744"
},
{
"name": "JavaScript",
"bytes": "2597231"
},
{
"name": "PHP",
"bytes": "12974549"
}
],
"symlink_target": ""
} |
@interface JSControlLayout () {
JSDPad *_dPad;
NSMutableArray *_buttons;
}
@end
@implementation JSControlLayout
- (id)initWithLayout:(NSString *)layoutFile delegate:(id <JSDPadDelegate, JSButtonDelegate>)delegate
{
if ((self = [super initWithFrame:CGRectZero]))
{
if (![layoutFile length] || !delegate)
{
@throw [NSException exceptionWithName:@"JSControlPadInternalInconsistencyException"
reason:@"A Layout file path AND a delegate must be provided"
userInfo:nil];
return nil;
}
self.delegate = delegate;
if ([layoutFile length])
{
NSDictionary *layout = [[NSDictionary alloc] initWithContentsOfFile:layoutFile];
if (layout)
{
self.title = [layout objectForKey:@"title"];
// set up the dpad
NSDictionary *dPadDict = [layout objectForKey:@"dpad"];
CGRect dPadFrame = CGRectFromString([dPadDict objectForKey:@"frame"]);
_dPad = [[JSDPad alloc] initWithFrame:dPadFrame];
[_dPad setDelegate:self.delegate];
[self addSubview:_dPad];
// set up buttons
_buttons = [NSMutableArray array];
NSArray *buttonArray = [layout objectForKey:@"buttons"];
for (NSDictionary *buttonDict in buttonArray)
{
CGRect buttonFrame = CGRectFromString([buttonDict objectForKey:@"frame"]);
JSButton *button = [[JSButton alloc] initWithFrame:buttonFrame];
[[button titleLabel] setText:[buttonDict objectForKey:@"title"]];
[button setDelegate:self.delegate];
[self addSubview:button];
[_buttons addObject:button];
}
}
}
}
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
CGRect frame = [_dPad frame];
if (CGRectContainsPoint(frame, point))
{
[_dPad touchesBegan:touches withEvent:event];
}
else
{
for (JSButton *button in _buttons)
{
frame = [button frame];
if (CGRectContainsPoint(frame, point))
{
[_dPad touchesBegan:touches withEvent:event];
}
}
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
CGRect frame = [_dPad frame];
if (CGRectContainsPoint(frame, point))
{
[_dPad touchesMoved:touches withEvent:event];
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
}
@end
| {
"content_hash": "39d9b6b4c8c0d7f2211c20bdb88d5665",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 100,
"avg_line_length": 23.63809523809524,
"alnum_prop": 0.6800966962127317,
"repo_name": "vkovtash/Asteroids",
"id": "a5ab8fb744710d10d1aaf05c797bd7329e10a04b",
"size": "2661",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Asteroids/JSController/JSControlLayout.m",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "65395"
},
{
"name": "Objective-C",
"bytes": "178651"
}
],
"symlink_target": ""
} |
<?php
require_once("../config/general.php");
echo($info_registro["activado"]["titulo"]);
echo "<br>";
echo($info_registro["activado"]["descripcion"]);
echo "<br>";
?>
| {
"content_hash": "46681398b7177fabdafaee430d735b38",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 48,
"avg_line_length": 21.125,
"alnum_prop": 0.6331360946745562,
"repo_name": "Kehrem/TFG-TIENDA",
"id": "9b42b5f530c84064a456961890d135f85bee3f9c",
"size": "169",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/registro_info.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1303"
},
{
"name": "CSS",
"bytes": "551645"
},
{
"name": "HTML",
"bytes": "228673"
},
{
"name": "JavaScript",
"bytes": "296549"
},
{
"name": "PHP",
"bytes": "4698190"
},
{
"name": "Shell",
"bytes": "4440"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"
/>
<link type="image/png" rel="shortcut icon" href="/vivaxy.icon.png" />
<link type="text/css" rel="stylesheet" href="/index.css" />
<title>Depth First Search</title>
<meta name="author" content="vivaxy <[email protected]>" />
<meta
name="keywords"
content="vivaxy,samples,github,demo,playground,depth-first-search,test,algorithms,tree,Algorithms,sample,demos"
/>
<meta name="description" content="深度优先遍历算法" />
</head>
<body>
<script type="text/javascript" charset="utf-8" src="/index.js"></script>
<script type="text/javascript" charset="utf-8" src="/ba.js"></script>
</body>
</html>
| {
"content_hash": "d4341b48610668c8244385dce2be9f0d",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 117,
"avg_line_length": 36.208333333333336,
"alnum_prop": 0.6490218642117376,
"repo_name": "vivaxy/course",
"id": "b2b1a310815f7caecc7fd6ba98e5e6d8f79c9ad2",
"size": "885",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "algorithms/tree/depth-first-search/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "3240"
},
{
"name": "C++",
"bytes": "10495"
},
{
"name": "CSS",
"bytes": "48470"
},
{
"name": "HTML",
"bytes": "560079"
},
{
"name": "Java",
"bytes": "2827"
},
{
"name": "JavaScript",
"bytes": "6702666"
},
{
"name": "Makefile",
"bytes": "664"
},
{
"name": "Objective-C",
"bytes": "8877"
},
{
"name": "Python",
"bytes": "2603"
},
{
"name": "Shell",
"bytes": "1759"
},
{
"name": "Starlark",
"bytes": "3389"
},
{
"name": "TypeScript",
"bytes": "39454"
}
],
"symlink_target": ""
} |
package com.vanaltj.canweather.envcan.xml.sitedata;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Text;
public class Temperature {
public enum TemperatureClass {
HIGH("high"),
LOW("low"),
CURRENT("current");
private String value;
private TemperatureClass(String value) {
this.value = value;
}
public static TemperatureClass fromString(String string) {
for (TemperatureClass clazz : TemperatureClass.values()) {
if (clazz.getValue().equals(string)) {
return clazz;
}
}
throw new IllegalArgumentException("Input \"" + string + "\" is not a valid TemperatureClass.");
}
public String getValue() {
return value;
}
}
@Attribute(name="unitType")
private String unitType;
@Attribute(name="units")
private String units;
@Attribute(name="class", required=false)
private String klass;
private TemperatureClass theClass;
@Text(required=false)
private float temperature;
public String getUnitType() {
return unitType;
}
public String getUnits() {
return units;
}
public TemperatureClass getTemperatureClass() {
cacheTemperatureClass();
return theClass;
}
private void cacheTemperatureClass() {
if (theClass == null) {
if (klass == null) {
klass = "current";
}
theClass = TemperatureClass.fromString(klass);
}
}
public float getValue() {
return temperature;
}
}
| {
"content_hash": "ab1e4413602c223c74e2951e9fd8a786",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 108,
"avg_line_length": 23.291666666666668,
"alnum_prop": 0.5807990459153249,
"repo_name": "BeaverProductions/canweather",
"id": "6aa687d9ff7b8b24617a8c7d3b63d19f92112bba",
"size": "2272",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/vanaltj/canweather/envcan/xml/sitedata/Temperature.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "52271"
}
],
"symlink_target": ""
} |
layout: post
status: publish
published: true
title: The BizTalk Message Box
author:
display_name: Tomas Restrepo
login: tomasr
email: [email protected]
url: http://winterdom.com/
author_login: tomasr
author_email: [email protected]
author_url: http://winterdom.com/
wordpress_id: 238
wordpress_url: http://winterdom.com/2007/01/thebiztalkmessagebox
date: '2007-01-04 19:04:27 +0000'
date_gmt: '2007-01-04 19:04:27 +0000'
categories:
- BizTalk
tags: []
comments:
- id: 176
author: Jon Flanders
author_email: [email protected]
author_url: http://www.masteringbiztalk.com/
date: '2007-01-04 20:25:54 +0000'
date_gmt: '2007-01-04 20:25:54 +0000'
content: |
Graber ;-)
---
<p><!--start_raw-->
<p><a href="http://blogs.msdn.com/biztalk_core_engine/">Lee</a> from the BizTalk Team (I really have no idea what his last name is!) talks about the <a href="http://blogs.msdn.com/biztalk_core_engine/archive/2007/01/04/what-you-can-and-can-t-do-with-the-messagebox-database-server.aspx">BizTalk Message Box</a> SQL Server Database, which is really the heart of BizTalk and what you can/can't do to the database server once you commit it to hosting the MsgBox. Fantastic stuff as always and well worth a read! (Found via Richard Seroter).</p>
<div class="wlWriterSmartContent" id="0767317B-992E-4b12-91E0-4F059A8CECA8:b4fae9b9-c82f-47a7-a371-769835e6ceb7" contenteditable="false" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">Technorati tags: <a href="http://technorati.com/tags/BizTalk%20Server" rel="tag">BizTalk Server</a>, <a href="http://technorati.com/tags/BTS" rel="tag">BTS</a></div><!--end_raw--></p>
| {
"content_hash": "9e5f17e587b54436b1fbf9edbe808304",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 593,
"avg_line_length": 55.71875,
"alnum_prop": 0.7240605720695457,
"repo_name": "tomasr/winterdom.com",
"id": "f4a94b2abba30ea19d737336aefd8873197eb714",
"size": "1787",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2007-01-04-thebiztalkmessagebox.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "15132"
},
{
"name": "HTML",
"bytes": "4376574"
},
{
"name": "JavaScript",
"bytes": "1208"
},
{
"name": "Ruby",
"bytes": "141"
}
],
"symlink_target": ""
} |
package es.weso.shacl
import es.weso.manifest.{Entry => ManifestEntry, _}
import org.scalatest._
import es.weso.utils.Logging
import es.weso.rdf.RDFReader
import es.weso.rdfgraph.nodes._
import es.weso.shacl.Shacl._
import util._
import es.weso.utils.IO._
import es.weso.rdf.jena.RDFAsJenaModel
import es.weso.monads.Result._
trait ManifestRunner
extends FunSpecLike
with Matchers
with Logging {
def runTests(mf: Manifest, base: String): Unit = {
for(entry <- mf.entries) {
it ("Entry: " + entry.name) {
runEntry(entry, base)
}
}
}
def runEntry(entry: ManifestEntry, base: String): Unit = {
entry.entryType match {
case MatchNodeShape => {
info("Entry: " + entry.name + " - result " + entry.result)
val action = entry.action
info("Action: " + action)
val attempt = for {
schema <- extractSchema(action, base)
rdf <- extractRDF(action, base)
node <- extractNode(action)
label <- extractLabel(action)
matcher <- Try{ ShaclMatcher(schema,rdf) }
result <- Try(matcher.match_node_label(node)(label))
_ <- Try(info("Result " + result))
expected <- Try(entry.result.asBoolean.get)
} yield (result,expected)
attempt match {
case Success((result,expected)) =>
result.isValid should be(expected)
case Failure(e) => fail("Exception: " + e.getMessage)
}
}
case _ => {
log.error("Unsupported entry type: " + entry.entryType)
}
}
}
def extractSchema(action: ManifestAction, base: String): Try[Schema] = {
println("Extracting schema...")
for {
schema <- Try(action.schema.get)
schemaFormat <- Try(action.schemaFormat.getOrElse(SchemaFormats.default))
val schemaFilename = relativize(schema, base)
(schema,pm) <- Schema.fromFile(schemaFilename, schemaFormat)
} yield {
println("Schema: " + schema)
schema
}
}
def extractRDF(action: ManifestAction, base: String): Try[RDFReader] = {
println("Extracting data...")
for {
data <- Try(action.data.get)
dataFormat <- Try(action.dataFormat.getOrElse(DataFormats.default))
val dataFilename = relativize(data, base)
cs <- getContents(dataFilename)
rdf <- RDFAsJenaModel.fromChars(cs,dataFormat)
} yield {
println("RDF: " + rdf)
rdf
}
}
def extractNode(action: ManifestAction): Try[RDFNode] = {
action.node match {
case Some(n) => Success(n)
case None => Failure(throw new Exception("Cannot extract node from action " + action))
}
}
def extractLabel(action:ManifestAction): Try[Label] = {
action.shape match {
case Some(str) => Success(IRILabel(str))
case None => Failure(throw new Exception("Cannot extract label from action " + action))
}
}
def relativize(iri: IRI, base: String): String = {
val iriLocal = iri.str.stripPrefix("http://www.w3.org/ns/")
base + iriLocal
}
}
| {
"content_hash": "4d904909b9acd7d47aee9e9dd056be53",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 93,
"avg_line_length": 29.75728155339806,
"alnum_prop": 0.6159869494290375,
"repo_name": "jorgeyp/ShExcala",
"id": "a98777b7fb65c6b7fe73cae09e6bce65b1b1d9dd",
"size": "3065",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/scala/es/weso/shacl/ManifestRunner.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Scala",
"bytes": "369421"
}
],
"symlink_target": ""
} |
namespace Engine
{
class FpsLimiter
{
public:
FpsLimiter();
void Init(float targetFps);
void SetMaxFps(float targetFps);
void Begin();
//will return current fps
float End();
private:
void calculateFps();
float fps;
float maxFps;
float frameTime;
unsigned int startTicks;
};
} | {
"content_hash": "1159b25d2226c74731ba937cca0a57da",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 34,
"avg_line_length": 13.304347826086957,
"alnum_prop": 0.6830065359477124,
"repo_name": "lordarpad6/Followers",
"id": "de8d4e1d2a6f9ab8f8790e8ff787e8636724daae",
"size": "320",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Engine/Timing.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "4101"
},
{
"name": "C++",
"bytes": "78272"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.ec2.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;
/**
* DescribeFlowLogsRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeFlowLogsRequestMarshaller implements Marshaller<Request<DescribeFlowLogsRequest>, DescribeFlowLogsRequest> {
public Request<DescribeFlowLogsRequest> marshall(DescribeFlowLogsRequest describeFlowLogsRequest) {
if (describeFlowLogsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
Request<DescribeFlowLogsRequest> request = new DefaultRequest<DescribeFlowLogsRequest>(describeFlowLogsRequest, "AmazonEC2");
request.addParameter("Action", "DescribeFlowLogs");
request.addParameter("Version", "2016-11-15");
request.setHttpMethod(HttpMethodName.POST);
com.amazonaws.internal.SdkInternalList<Filter> describeFlowLogsRequestFilterList = (com.amazonaws.internal.SdkInternalList<Filter>) describeFlowLogsRequest
.getFilter();
if (!describeFlowLogsRequestFilterList.isEmpty() || !describeFlowLogsRequestFilterList.isAutoConstruct()) {
int filterListIndex = 1;
for (Filter describeFlowLogsRequestFilterListValue : describeFlowLogsRequestFilterList) {
if (describeFlowLogsRequestFilterListValue.getName() != null) {
request.addParameter("Filter." + filterListIndex + ".Name", StringUtils.fromString(describeFlowLogsRequestFilterListValue.getName()));
}
com.amazonaws.internal.SdkInternalList<String> filterValuesList = (com.amazonaws.internal.SdkInternalList<String>) describeFlowLogsRequestFilterListValue
.getValues();
if (!filterValuesList.isEmpty() || !filterValuesList.isAutoConstruct()) {
int valuesListIndex = 1;
for (String filterValuesListValue : filterValuesList) {
if (filterValuesListValue != null) {
request.addParameter("Filter." + filterListIndex + ".Value." + valuesListIndex, StringUtils.fromString(filterValuesListValue));
}
valuesListIndex++;
}
}
filterListIndex++;
}
}
com.amazonaws.internal.SdkInternalList<String> describeFlowLogsRequestFlowLogIdsList = (com.amazonaws.internal.SdkInternalList<String>) describeFlowLogsRequest
.getFlowLogIds();
if (!describeFlowLogsRequestFlowLogIdsList.isEmpty() || !describeFlowLogsRequestFlowLogIdsList.isAutoConstruct()) {
int flowLogIdsListIndex = 1;
for (String describeFlowLogsRequestFlowLogIdsListValue : describeFlowLogsRequestFlowLogIdsList) {
if (describeFlowLogsRequestFlowLogIdsListValue != null) {
request.addParameter("FlowLogId." + flowLogIdsListIndex, StringUtils.fromString(describeFlowLogsRequestFlowLogIdsListValue));
}
flowLogIdsListIndex++;
}
}
if (describeFlowLogsRequest.getMaxResults() != null) {
request.addParameter("MaxResults", StringUtils.fromInteger(describeFlowLogsRequest.getMaxResults()));
}
if (describeFlowLogsRequest.getNextToken() != null) {
request.addParameter("NextToken", StringUtils.fromString(describeFlowLogsRequest.getNextToken()));
}
return request;
}
}
| {
"content_hash": "b49e18a4523079c8ab5914fcc80e5391",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 169,
"avg_line_length": 46.34939759036145,
"alnum_prop": 0.6833896542760592,
"repo_name": "jentfoo/aws-sdk-java",
"id": "c7b97f24a94407441e1697a1a8e4d7b4727722eb",
"size": "4427",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/DescribeFlowLogsRequestMarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "270"
},
{
"name": "FreeMarker",
"bytes": "173637"
},
{
"name": "Gherkin",
"bytes": "25063"
},
{
"name": "Java",
"bytes": "356214839"
},
{
"name": "Scilab",
"bytes": "3924"
},
{
"name": "Shell",
"bytes": "295"
}
],
"symlink_target": ""
} |
#ifndef _SFXGE_TX_H
#define _SFXGE_TX_H
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
/* Maximum number of DMA segments needed to map an mbuf chain. With
* TSO, the mbuf length may be just over 64K, divided into 2K mbuf
* clusters. (The chain could be longer than this initially, but can
* be shortened with m_collapse().)
*/
#define SFXGE_TX_MAPPING_MAX_SEG (64 / 2 + 1)
/* Maximum number of DMA segments needed to map an output packet. It
* could overlap all mbufs in the chain and also require an extra
* segment for a TSO header.
*/
#define SFXGE_TX_PACKET_MAX_SEG (SFXGE_TX_MAPPING_MAX_SEG + 1)
/*
* Buffer mapping flags.
*
* Buffers and DMA mappings must be freed when the last descriptor
* referring to them is completed. Set the TX_BUF_UNMAP and
* TX_BUF_MBUF flags on the last descriptor generated for an mbuf
* chain. Set only the TX_BUF_UNMAP flag on a descriptor referring to
* a heap buffer.
*/
enum sfxge_tx_buf_flags {
TX_BUF_UNMAP = 1,
TX_BUF_MBUF = 2,
};
/*
* Buffer mapping information for descriptors in flight.
*/
struct sfxge_tx_mapping {
union {
struct mbuf *mbuf;
caddr_t heap_buf;
} u;
bus_dmamap_t map;
enum sfxge_tx_buf_flags flags;
};
#define SFXGE_TX_MAX_DEFERRED 64
/*
* Deferred packet list.
*/
struct sfxge_tx_dpl {
uintptr_t std_put; /* Head of put list. */
struct mbuf *std_get; /* Head of get list. */
struct mbuf **std_getp; /* Tail of get list. */
unsigned int std_count; /* Count of packets. */
};
#define SFXGE_TX_BUFFER_SIZE 0x400
#define SFXGE_TX_HEADER_SIZE 0x100
#define SFXGE_TX_COPY_THRESHOLD 0x200
enum sfxge_txq_state {
SFXGE_TXQ_UNINITIALIZED = 0,
SFXGE_TXQ_INITIALIZED,
SFXGE_TXQ_STARTED
};
enum sfxge_txq_type {
SFXGE_TXQ_NON_CKSUM = 0,
SFXGE_TXQ_IP_CKSUM,
SFXGE_TXQ_IP_TCP_UDP_CKSUM,
SFXGE_TXQ_NTYPES
};
#define SFXGE_TXQ_UNBLOCK_LEVEL (EFX_TXQ_LIMIT(SFXGE_NDESCS) / 4)
#define SFXGE_TX_BATCH 64
#ifdef SFXGE_HAVE_MQ
#define SFXGE_TXQ_LOCK(txq) (&(txq)->lock)
#define SFXGE_TX_SCALE(sc) ((sc)->intr.n_alloc)
#else
#define SFXGE_TXQ_LOCK(txq) (&(txq)->sc->tx_lock)
#define SFXGE_TX_SCALE(sc) 1
#endif
struct sfxge_txq {
/* The following fields should be written very rarely */
struct sfxge_softc *sc;
enum sfxge_txq_state init_state;
enum sfxge_flush_state flush_state;
enum sfxge_txq_type type;
unsigned int txq_index;
unsigned int evq_index;
efsys_mem_t mem;
unsigned int buf_base_id;
struct sfxge_tx_mapping *stmp; /* Packets in flight. */
bus_dma_tag_t packet_dma_tag;
efx_buffer_t *pend_desc;
efx_txq_t *common;
struct sfxge_txq *next;
efsys_mem_t *tsoh_buffer;
/* This field changes more often and is read regularly on both
* the initiation and completion paths
*/
int blocked __aligned(CACHE_LINE_SIZE);
/* The following fields change more often, and are used mostly
* on the initiation path
*/
#ifdef SFXGE_HAVE_MQ
struct mtx lock __aligned(CACHE_LINE_SIZE);
struct sfxge_tx_dpl dpl; /* Deferred packet list. */
unsigned int n_pend_desc;
#else
unsigned int n_pend_desc __aligned(CACHE_LINE_SIZE);
#endif
unsigned int added;
unsigned int reaped;
/* Statistics */
unsigned long tso_bursts;
unsigned long tso_packets;
unsigned long tso_long_headers;
unsigned long collapses;
unsigned long drops;
/* The following fields change more often, and are used mostly
* on the completion path
*/
unsigned int pending __aligned(CACHE_LINE_SIZE);
unsigned int completed;
};
extern int sfxge_tx_packet_add(struct sfxge_txq *, struct mbuf *);
extern int sfxge_tx_init(struct sfxge_softc *sc);
extern void sfxge_tx_fini(struct sfxge_softc *sc);
extern int sfxge_tx_start(struct sfxge_softc *sc);
extern void sfxge_tx_stop(struct sfxge_softc *sc);
extern void sfxge_tx_qcomplete(struct sfxge_txq *txq);
extern void sfxge_tx_qflush_done(struct sfxge_txq *txq);
#ifdef SFXGE_HAVE_MQ
extern void sfxge_if_qflush(struct ifnet *ifp);
extern int sfxge_if_transmit(struct ifnet *ifp, struct mbuf *m);
#else
extern void sfxge_if_start(struct ifnet *ifp);
#endif
#endif
| {
"content_hash": "4805fc819d697332bad6d83b5ee5cc71",
"timestamp": "",
"source": "github",
"line_count": 156,
"max_line_length": 70,
"avg_line_length": 26.352564102564102,
"alnum_prop": 0.703964972026271,
"repo_name": "jhbsz/OSI-OS",
"id": "483a16a03cc3e1eca7c6c45347ec94eaed308fe1",
"size": "5616",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sys/dev/sfxge/sfxge_tx.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
// Copyright 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 "cc/tiles/picture_layer_tiling.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <set>
#include "base/logging.h"
#include "base/trace_event/trace_event.h"
#include "base/trace_event/trace_event_argument.h"
#include "cc/base/math_util.h"
#include "cc/playback/raster_source.h"
#include "cc/tiles/prioritized_tile.h"
#include "cc/tiles/tile.h"
#include "cc/tiles/tile_priority.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/safe_integer_conversions.h"
#include "ui/gfx/geometry/size_conversions.h"
namespace cc {
namespace {
const float kSoonBorderDistanceViewportPercentage = 0.15f;
const float kMaxSoonBorderDistanceInScreenPixels = 312.f;
} // namespace
scoped_ptr<PictureLayerTiling> PictureLayerTiling::Create(
WhichTree tree,
float contents_scale,
scoped_refptr<RasterSource> raster_source,
PictureLayerTilingClient* client,
size_t max_tiles_for_interest_area,
float skewport_target_time_in_seconds,
int skewport_extrapolation_limit_in_content_pixels) {
return make_scoped_ptr(new PictureLayerTiling(
tree, contents_scale, raster_source, client, max_tiles_for_interest_area,
skewport_target_time_in_seconds,
skewport_extrapolation_limit_in_content_pixels));
}
PictureLayerTiling::PictureLayerTiling(
WhichTree tree,
float contents_scale,
scoped_refptr<RasterSource> raster_source,
PictureLayerTilingClient* client,
size_t max_tiles_for_interest_area,
float skewport_target_time_in_seconds,
int skewport_extrapolation_limit_in_content_pixels)
: max_tiles_for_interest_area_(max_tiles_for_interest_area),
skewport_target_time_in_seconds_(skewport_target_time_in_seconds),
skewport_extrapolation_limit_in_content_pixels_(
skewport_extrapolation_limit_in_content_pixels),
contents_scale_(contents_scale),
client_(client),
tree_(tree),
raster_source_(raster_source),
resolution_(NON_IDEAL_RESOLUTION),
tiling_data_(gfx::Size(), gfx::Size(), kBorderTexels),
can_require_tiles_for_activation_(false),
current_content_to_screen_scale_(0.f),
has_visible_rect_tiles_(false),
has_skewport_rect_tiles_(false),
has_soon_border_rect_tiles_(false),
has_eventually_rect_tiles_(false) {
DCHECK(!raster_source->IsSolidColor());
gfx::Size content_bounds = gfx::ToCeiledSize(
gfx::ScaleSize(raster_source_->GetSize(), contents_scale));
gfx::Size tile_size = client_->CalculateTileSize(content_bounds);
DCHECK(!gfx::ToFlooredSize(gfx::ScaleSize(raster_source_->GetSize(),
contents_scale)).IsEmpty())
<< "Tiling created with scale too small as contents become empty."
<< " Layer bounds: " << raster_source_->GetSize().ToString()
<< " Contents scale: " << contents_scale;
tiling_data_.SetTilingSize(content_bounds);
tiling_data_.SetMaxTextureSize(tile_size);
}
PictureLayerTiling::~PictureLayerTiling() {
}
// static
float PictureLayerTiling::CalculateSoonBorderDistance(
const gfx::Rect& visible_rect_in_content_space,
float content_to_screen_scale) {
float max_dimension = std::max(visible_rect_in_content_space.width(),
visible_rect_in_content_space.height());
return std::min(
kMaxSoonBorderDistanceInScreenPixels / content_to_screen_scale,
max_dimension * kSoonBorderDistanceViewportPercentage);
}
Tile* PictureLayerTiling::CreateTile(int i, int j) {
TileMapKey key(i, j);
DCHECK(tiles_.find(key) == tiles_.end());
gfx::Rect paint_rect = tiling_data_.TileBoundsWithBorder(i, j);
gfx::Rect tile_rect = paint_rect;
tile_rect.set_size(tiling_data_.max_texture_size());
if (!raster_source_->CoversRect(tile_rect, contents_scale_))
return nullptr;
ScopedTilePtr tile = client_->CreateTile(contents_scale_, tile_rect);
Tile* raw_ptr = tile.get();
tile->set_tiling_index(i, j);
tiles_.add(key, tile.Pass());
return raw_ptr;
}
void PictureLayerTiling::CreateMissingTilesInLiveTilesRect() {
bool include_borders = false;
for (TilingData::Iterator iter(&tiling_data_, live_tiles_rect_,
include_borders);
iter; ++iter) {
TileMapKey key = iter.index();
TileMap::iterator find = tiles_.find(key);
if (find != tiles_.end())
continue;
if (ShouldCreateTileAt(key.first, key.second))
CreateTile(key.first, key.second);
}
VerifyLiveTilesRect(false);
}
void PictureLayerTiling::TakeTilesAndPropertiesFrom(
PictureLayerTiling* pending_twin,
const Region& layer_invalidation) {
TRACE_EVENT0("cc", "TakeTilesAndPropertiesFrom");
SetRasterSourceAndResize(pending_twin->raster_source_);
RemoveTilesInRegion(layer_invalidation, false /* recreate tiles */);
resolution_ = pending_twin->resolution_;
bool create_missing_tiles = false;
if (live_tiles_rect_.IsEmpty()) {
live_tiles_rect_ = pending_twin->live_tiles_rect();
create_missing_tiles = true;
} else {
SetLiveTilesRect(pending_twin->live_tiles_rect());
}
if (tiles_.empty()) {
tiles_.swap(pending_twin->tiles_);
} else {
while (!pending_twin->tiles_.empty()) {
TileMapKey key = pending_twin->tiles_.begin()->first;
tiles_.set(key, pending_twin->tiles_.take_and_erase(key));
}
}
DCHECK(pending_twin->tiles_.empty());
if (create_missing_tiles)
CreateMissingTilesInLiveTilesRect();
VerifyLiveTilesRect(false);
SetTilePriorityRects(pending_twin->current_content_to_screen_scale_,
pending_twin->current_visible_rect_,
pending_twin->current_skewport_rect_,
pending_twin->current_soon_border_rect_,
pending_twin->current_eventually_rect_,
pending_twin->current_occlusion_in_layer_space_);
}
void PictureLayerTiling::SetRasterSourceAndResize(
scoped_refptr<RasterSource> raster_source) {
DCHECK(!raster_source->IsSolidColor());
gfx::Size old_layer_bounds = raster_source_->GetSize();
raster_source_.swap(raster_source);
gfx::Size new_layer_bounds = raster_source_->GetSize();
gfx::Size content_bounds =
gfx::ToCeiledSize(gfx::ScaleSize(new_layer_bounds, contents_scale_));
gfx::Size tile_size = client_->CalculateTileSize(content_bounds);
if (tile_size != tiling_data_.max_texture_size()) {
tiling_data_.SetTilingSize(content_bounds);
tiling_data_.SetMaxTextureSize(tile_size);
// When the tile size changes, the TilingData positions no longer work
// as valid keys to the TileMap, so just drop all tiles and clear the live
// tiles rect.
Reset();
return;
}
if (old_layer_bounds == new_layer_bounds)
return;
// The SetLiveTilesRect() method would drop tiles outside the new bounds,
// but may do so incorrectly if resizing the tiling causes the number of
// tiles in the tiling_data_ to change.
gfx::Rect content_rect(content_bounds);
int before_left = tiling_data_.TileXIndexFromSrcCoord(live_tiles_rect_.x());
int before_top = tiling_data_.TileYIndexFromSrcCoord(live_tiles_rect_.y());
int before_right =
tiling_data_.TileXIndexFromSrcCoord(live_tiles_rect_.right() - 1);
int before_bottom =
tiling_data_.TileYIndexFromSrcCoord(live_tiles_rect_.bottom() - 1);
// The live_tiles_rect_ is clamped to stay within the tiling size as we
// change it.
live_tiles_rect_.Intersect(content_rect);
tiling_data_.SetTilingSize(content_bounds);
int after_right = -1;
int after_bottom = -1;
if (!live_tiles_rect_.IsEmpty()) {
after_right =
tiling_data_.TileXIndexFromSrcCoord(live_tiles_rect_.right() - 1);
after_bottom =
tiling_data_.TileYIndexFromSrcCoord(live_tiles_rect_.bottom() - 1);
}
// There is no recycled twin since this is run on the pending tiling
// during commit, and on the active tree during activate.
// Drop tiles outside the new layer bounds if the layer shrank.
for (int i = after_right + 1; i <= before_right; ++i) {
for (int j = before_top; j <= before_bottom; ++j)
RemoveTileAt(i, j);
}
for (int i = before_left; i <= after_right; ++i) {
for (int j = after_bottom + 1; j <= before_bottom; ++j)
RemoveTileAt(i, j);
}
if (after_right > before_right) {
DCHECK_EQ(after_right, before_right + 1);
for (int j = before_top; j <= after_bottom; ++j) {
if (ShouldCreateTileAt(after_right, j))
CreateTile(after_right, j);
}
}
if (after_bottom > before_bottom) {
DCHECK_EQ(after_bottom, before_bottom + 1);
for (int i = before_left; i <= before_right; ++i) {
if (ShouldCreateTileAt(i, after_bottom))
CreateTile(i, after_bottom);
}
}
}
void PictureLayerTiling::Invalidate(const Region& layer_invalidation) {
DCHECK_IMPLIES(tree_ == ACTIVE_TREE,
!client_->GetPendingOrActiveTwinTiling(this));
RemoveTilesInRegion(layer_invalidation, true /* recreate tiles */);
}
void PictureLayerTiling::RemoveTilesInRegion(const Region& layer_invalidation,
bool recreate_tiles) {
// We only invalidate the active tiling when it's orphaned: it has no pending
// twin, so it's slated for removal in the future.
if (live_tiles_rect_.IsEmpty())
return;
std::vector<TileMapKey> new_tile_keys;
gfx::Rect expanded_live_tiles_rect =
tiling_data_.ExpandRectIgnoringBordersToTileBounds(live_tiles_rect_);
for (Region::Iterator iter(layer_invalidation); iter.has_rect();
iter.next()) {
gfx::Rect layer_rect = iter.rect();
gfx::Rect content_rect =
gfx::ScaleToEnclosingRect(layer_rect, contents_scale_);
// Consider tiles inside the live tiles rect even if only their border
// pixels intersect the invalidation. But don't consider tiles outside
// the live tiles rect with the same conditions, as they won't exist.
int border_pixels = tiling_data_.border_texels();
content_rect.Inset(-border_pixels, -border_pixels);
// Avoid needless work by not bothering to invalidate where there aren't
// tiles.
content_rect.Intersect(expanded_live_tiles_rect);
if (content_rect.IsEmpty())
continue;
// Since the content_rect includes border pixels already, don't include
// borders when iterating to avoid double counting them.
bool include_borders = false;
for (
TilingData::Iterator iter(&tiling_data_, content_rect, include_borders);
iter; ++iter) {
if (RemoveTileAt(iter.index_x(), iter.index_y())) {
if (recreate_tiles)
new_tile_keys.push_back(iter.index());
}
}
}
for (const auto& key : new_tile_keys)
CreateTile(key.first, key.second);
}
bool PictureLayerTiling::ShouldCreateTileAt(int i, int j) const {
// Active tree should always create a tile. The reason for this is that active
// tree represents content that we draw on screen, which means that whenever
// we check whether a tile should exist somewhere, the answer is yes. This
// doesn't mean it will actually be created (if raster source doesn't cover
// the tile for instance). Pending tree, on the other hand, should only be
// creating tiles that are different from the current active tree, which is
// represented by the logic in the rest of the function.
if (tree_ == ACTIVE_TREE)
return true;
// If the pending tree has no active twin, then it needs to create all tiles.
const PictureLayerTiling* active_twin =
client_->GetPendingOrActiveTwinTiling(this);
if (!active_twin)
return true;
// Pending tree will override the entire active tree if indices don't match.
if (!TilingMatchesTileIndices(active_twin))
return true;
gfx::Rect paint_rect = tiling_data_.TileBoundsWithBorder(i, j);
gfx::Rect tile_rect = paint_rect;
tile_rect.set_size(tiling_data_.max_texture_size());
// If the active tree can't create a tile, because of its raster source, then
// the pending tree should create one.
if (!active_twin->raster_source()->CoversRect(tile_rect, contents_scale()))
return true;
const Region* layer_invalidation = client_->GetPendingInvalidation();
gfx::Rect layer_rect =
gfx::ScaleToEnclosingRect(tile_rect, 1.f / contents_scale());
// If this tile is invalidated, then the pending tree should create one.
if (layer_invalidation && layer_invalidation->Intersects(layer_rect))
return true;
// If the active tree doesn't have a tile here, but it's in the pending tree's
// visible rect, then the pending tree should create a tile. This can happen
// if the pending visible rect is outside of the active tree's live tiles
// rect. In those situations, we need to block activation until we're ready to
// display content, which will have to come from the pending tree.
if (!active_twin->TileAt(i, j) && current_visible_rect_.Intersects(tile_rect))
return true;
// In all other cases, the pending tree doesn't need to create a tile.
return false;
}
bool PictureLayerTiling::TilingMatchesTileIndices(
const PictureLayerTiling* twin) const {
return tiling_data_.max_texture_size() ==
twin->tiling_data_.max_texture_size();
}
PictureLayerTiling::CoverageIterator::CoverageIterator()
: tiling_(NULL),
current_tile_(NULL),
tile_i_(0),
tile_j_(0),
left_(0),
top_(0),
right_(-1),
bottom_(-1) {
}
PictureLayerTiling::CoverageIterator::CoverageIterator(
const PictureLayerTiling* tiling,
float dest_scale,
const gfx::Rect& dest_rect)
: tiling_(tiling),
dest_rect_(dest_rect),
dest_to_content_scale_(0),
current_tile_(NULL),
tile_i_(0),
tile_j_(0),
left_(0),
top_(0),
right_(-1),
bottom_(-1) {
DCHECK(tiling_);
if (dest_rect_.IsEmpty())
return;
dest_to_content_scale_ = tiling_->contents_scale_ / dest_scale;
gfx::Rect content_rect =
gfx::ScaleToEnclosingRect(dest_rect_,
dest_to_content_scale_,
dest_to_content_scale_);
// IndexFromSrcCoord clamps to valid tile ranges, so it's necessary to
// check for non-intersection first.
content_rect.Intersect(gfx::Rect(tiling_->tiling_size()));
if (content_rect.IsEmpty())
return;
left_ = tiling_->tiling_data_.TileXIndexFromSrcCoord(content_rect.x());
top_ = tiling_->tiling_data_.TileYIndexFromSrcCoord(content_rect.y());
right_ = tiling_->tiling_data_.TileXIndexFromSrcCoord(
content_rect.right() - 1);
bottom_ = tiling_->tiling_data_.TileYIndexFromSrcCoord(
content_rect.bottom() - 1);
tile_i_ = left_ - 1;
tile_j_ = top_;
++(*this);
}
PictureLayerTiling::CoverageIterator::~CoverageIterator() {
}
PictureLayerTiling::CoverageIterator&
PictureLayerTiling::CoverageIterator::operator++() {
if (tile_j_ > bottom_)
return *this;
bool first_time = tile_i_ < left_;
bool new_row = false;
tile_i_++;
if (tile_i_ > right_) {
tile_i_ = left_;
tile_j_++;
new_row = true;
if (tile_j_ > bottom_) {
current_tile_ = NULL;
return *this;
}
}
current_tile_ = tiling_->TileAt(tile_i_, tile_j_);
// Calculate the current geometry rect. Due to floating point rounding
// and ToEnclosingRect, tiles might overlap in destination space on the
// edges.
gfx::Rect last_geometry_rect = current_geometry_rect_;
gfx::Rect content_rect = tiling_->tiling_data_.TileBounds(tile_i_, tile_j_);
current_geometry_rect_ =
gfx::ScaleToEnclosingRect(content_rect,
1 / dest_to_content_scale_,
1 / dest_to_content_scale_);
current_geometry_rect_.Intersect(dest_rect_);
if (first_time)
return *this;
// Iteration happens left->right, top->bottom. Running off the bottom-right
// edge is handled by the intersection above with dest_rect_. Here we make
// sure that the new current geometry rect doesn't overlap with the last.
int min_left;
int min_top;
if (new_row) {
min_left = dest_rect_.x();
min_top = last_geometry_rect.bottom();
} else {
min_left = last_geometry_rect.right();
min_top = last_geometry_rect.y();
}
int inset_left = std::max(0, min_left - current_geometry_rect_.x());
int inset_top = std::max(0, min_top - current_geometry_rect_.y());
current_geometry_rect_.Inset(inset_left, inset_top, 0, 0);
if (!new_row) {
DCHECK_EQ(last_geometry_rect.right(), current_geometry_rect_.x());
DCHECK_EQ(last_geometry_rect.bottom(), current_geometry_rect_.bottom());
DCHECK_EQ(last_geometry_rect.y(), current_geometry_rect_.y());
}
return *this;
}
gfx::Rect PictureLayerTiling::CoverageIterator::geometry_rect() const {
return current_geometry_rect_;
}
gfx::RectF PictureLayerTiling::CoverageIterator::texture_rect() const {
gfx::PointF tex_origin =
tiling_->tiling_data_.TileBoundsWithBorder(tile_i_, tile_j_).origin();
// Convert from dest space => content space => texture space.
gfx::RectF texture_rect(current_geometry_rect_);
texture_rect.Scale(dest_to_content_scale_,
dest_to_content_scale_);
texture_rect.Intersect(gfx::Rect(tiling_->tiling_size()));
if (texture_rect.IsEmpty())
return texture_rect;
texture_rect.Offset(-tex_origin.OffsetFromOrigin());
return texture_rect;
}
bool PictureLayerTiling::RemoveTileAt(int i, int j) {
TileMap::iterator found = tiles_.find(TileMapKey(i, j));
if (found == tiles_.end())
return false;
tiles_.erase(found);
return true;
}
void PictureLayerTiling::Reset() {
live_tiles_rect_ = gfx::Rect();
tiles_.clear();
}
gfx::Rect PictureLayerTiling::ComputeSkewport(
double current_frame_time_in_seconds,
const gfx::Rect& visible_rect_in_content_space) const {
gfx::Rect skewport = visible_rect_in_content_space;
if (skewport.IsEmpty())
return skewport;
if (visible_rect_history_[1].frame_time_in_seconds == 0.0)
return skewport;
double time_delta = current_frame_time_in_seconds -
visible_rect_history_[1].frame_time_in_seconds;
if (time_delta == 0.0)
return skewport;
double extrapolation_multiplier =
skewport_target_time_in_seconds_ / time_delta;
int old_x = visible_rect_history_[1].visible_rect_in_content_space.x();
int old_y = visible_rect_history_[1].visible_rect_in_content_space.y();
int old_right =
visible_rect_history_[1].visible_rect_in_content_space.right();
int old_bottom =
visible_rect_history_[1].visible_rect_in_content_space.bottom();
int new_x = visible_rect_in_content_space.x();
int new_y = visible_rect_in_content_space.y();
int new_right = visible_rect_in_content_space.right();
int new_bottom = visible_rect_in_content_space.bottom();
// Compute the maximum skewport based on
// |skewport_extrapolation_limit_in_content_pixels_|.
gfx::Rect max_skewport = skewport;
max_skewport.Inset(-skewport_extrapolation_limit_in_content_pixels_,
-skewport_extrapolation_limit_in_content_pixels_);
// Inset the skewport by the needed adjustment.
skewport.Inset(extrapolation_multiplier * (new_x - old_x),
extrapolation_multiplier * (new_y - old_y),
extrapolation_multiplier * (old_right - new_right),
extrapolation_multiplier * (old_bottom - new_bottom));
// Ensure that visible rect is contained in the skewport.
skewport.Union(visible_rect_in_content_space);
// Clip the skewport to |max_skewport|. This needs to happen after the
// union in case intersecting would have left the empty rect.
skewport.Intersect(max_skewport);
// Due to limits in int's representation, it is possible that the two
// operations above (union and intersect) result in an empty skewport. To
// avoid any unpleasant situations like that, union the visible rect again to
// ensure that skewport.Contains(visible_rect_in_content_space) is always
// true.
skewport.Union(visible_rect_in_content_space);
return skewport;
}
bool PictureLayerTiling::ComputeTilePriorityRects(
const gfx::Rect& viewport_in_layer_space,
float ideal_contents_scale,
double current_frame_time_in_seconds,
const Occlusion& occlusion_in_layer_space) {
if (!NeedsUpdateForFrameAtTimeAndViewport(current_frame_time_in_seconds,
viewport_in_layer_space)) {
// This should never be zero for the purposes of has_ever_been_updated().
DCHECK_NE(current_frame_time_in_seconds, 0.0);
return false;
}
gfx::Rect visible_rect_in_content_space =
gfx::ScaleToEnclosingRect(viewport_in_layer_space, contents_scale_);
if (tiling_size().IsEmpty()) {
UpdateVisibleRectHistory(current_frame_time_in_seconds,
visible_rect_in_content_space);
last_viewport_in_layer_space_ = viewport_in_layer_space;
return false;
}
// Calculate the skewport.
gfx::Rect skewport = ComputeSkewport(current_frame_time_in_seconds,
visible_rect_in_content_space);
DCHECK(skewport.Contains(visible_rect_in_content_space));
// Calculate the eventually/live tiles rect.
gfx::Size tile_size = tiling_data_.max_texture_size();
int64 eventually_rect_area =
max_tiles_for_interest_area_ * tile_size.width() * tile_size.height();
gfx::Rect eventually_rect =
ExpandRectEquallyToAreaBoundedBy(visible_rect_in_content_space,
eventually_rect_area,
gfx::Rect(tiling_size()),
&expansion_cache_);
DCHECK(eventually_rect.IsEmpty() ||
gfx::Rect(tiling_size()).Contains(eventually_rect))
<< "tiling_size: " << tiling_size().ToString()
<< " eventually_rect: " << eventually_rect.ToString();
// Calculate the soon border rect.
float content_to_screen_scale = ideal_contents_scale / contents_scale_;
gfx::Rect soon_border_rect = visible_rect_in_content_space;
float border = CalculateSoonBorderDistance(visible_rect_in_content_space,
content_to_screen_scale);
soon_border_rect.Inset(-border, -border, -border, -border);
UpdateVisibleRectHistory(current_frame_time_in_seconds,
visible_rect_in_content_space);
last_viewport_in_layer_space_ = viewport_in_layer_space;
SetTilePriorityRects(content_to_screen_scale, visible_rect_in_content_space,
skewport, soon_border_rect, eventually_rect,
occlusion_in_layer_space);
SetLiveTilesRect(eventually_rect);
return true;
}
void PictureLayerTiling::SetTilePriorityRects(
float content_to_screen_scale,
const gfx::Rect& visible_rect_in_content_space,
const gfx::Rect& skewport,
const gfx::Rect& soon_border_rect,
const gfx::Rect& eventually_rect,
const Occlusion& occlusion_in_layer_space) {
current_visible_rect_ = visible_rect_in_content_space;
current_skewport_rect_ = skewport;
current_soon_border_rect_ = soon_border_rect;
current_eventually_rect_ = eventually_rect;
current_occlusion_in_layer_space_ = occlusion_in_layer_space;
current_content_to_screen_scale_ = content_to_screen_scale;
gfx::Rect tiling_rect(tiling_size());
has_visible_rect_tiles_ = tiling_rect.Intersects(current_visible_rect_);
has_skewport_rect_tiles_ = tiling_rect.Intersects(current_skewport_rect_);
has_soon_border_rect_tiles_ =
tiling_rect.Intersects(current_soon_border_rect_);
has_eventually_rect_tiles_ = tiling_rect.Intersects(current_eventually_rect_);
}
void PictureLayerTiling::SetLiveTilesRect(
const gfx::Rect& new_live_tiles_rect) {
DCHECK(new_live_tiles_rect.IsEmpty() ||
gfx::Rect(tiling_size()).Contains(new_live_tiles_rect))
<< "tiling_size: " << tiling_size().ToString()
<< " new_live_tiles_rect: " << new_live_tiles_rect.ToString();
if (live_tiles_rect_ == new_live_tiles_rect)
return;
// Iterate to delete all tiles outside of our new live_tiles rect.
for (TilingData::DifferenceIterator iter(&tiling_data_, live_tiles_rect_,
new_live_tiles_rect);
iter; ++iter) {
RemoveTileAt(iter.index_x(), iter.index_y());
}
// Iterate to allocate new tiles for all regions with newly exposed area.
for (TilingData::DifferenceIterator iter(&tiling_data_, new_live_tiles_rect,
live_tiles_rect_);
iter; ++iter) {
TileMapKey key(iter.index());
if (ShouldCreateTileAt(key.first, key.second))
CreateTile(key.first, key.second);
}
live_tiles_rect_ = new_live_tiles_rect;
VerifyLiveTilesRect(false);
}
void PictureLayerTiling::VerifyLiveTilesRect(bool is_on_recycle_tree) const {
#if DCHECK_IS_ON()
for (auto it = tiles_.begin(); it != tiles_.end(); ++it) {
if (!it->second)
continue;
DCHECK(it->first.first < tiling_data_.num_tiles_x())
<< this << " " << it->first.first << "," << it->first.second
<< " num_tiles_x " << tiling_data_.num_tiles_x() << " live_tiles_rect "
<< live_tiles_rect_.ToString();
DCHECK(it->first.second < tiling_data_.num_tiles_y())
<< this << " " << it->first.first << "," << it->first.second
<< " num_tiles_y " << tiling_data_.num_tiles_y() << " live_tiles_rect "
<< live_tiles_rect_.ToString();
DCHECK(tiling_data_.TileBounds(it->first.first, it->first.second)
.Intersects(live_tiles_rect_))
<< this << " " << it->first.first << "," << it->first.second
<< " tile bounds "
<< tiling_data_.TileBounds(it->first.first, it->first.second).ToString()
<< " live_tiles_rect " << live_tiles_rect_.ToString();
}
#endif
}
bool PictureLayerTiling::IsTileOccluded(const Tile* tile) const {
// If this tile is not occluded on this tree, then it is not occluded.
if (!IsTileOccludedOnCurrentTree(tile))
return false;
// Otherwise, if this is the pending tree, we're done and the tile is
// occluded.
if (tree_ == PENDING_TREE)
return true;
// On the active tree however, we need to check if this tile will be
// unoccluded upon activation, in which case it has to be considered
// unoccluded.
const PictureLayerTiling* pending_twin =
client_->GetPendingOrActiveTwinTiling(this);
if (pending_twin) {
// If there's a pending tile in the same position. Or if the pending twin
// would have to be creating all tiles, then we don't need to worry about
// occlusion on the twin.
if (!TilingMatchesTileIndices(pending_twin) ||
pending_twin->TileAt(tile->tiling_i_index(), tile->tiling_j_index())) {
return true;
}
return pending_twin->IsTileOccludedOnCurrentTree(tile);
}
return true;
}
bool PictureLayerTiling::IsTileOccludedOnCurrentTree(const Tile* tile) const {
if (!current_occlusion_in_layer_space_.HasOcclusion())
return false;
gfx::Rect tile_query_rect =
gfx::IntersectRects(tile->content_rect(), current_visible_rect_);
// Explicitly check if the tile is outside the viewport. If so, we need to
// return false, since occlusion for this tile is unknown.
if (tile_query_rect.IsEmpty())
return false;
if (contents_scale_ != 1.f) {
tile_query_rect =
gfx::ScaleToEnclosingRect(tile_query_rect, 1.f / contents_scale_);
}
return current_occlusion_in_layer_space_.IsOccluded(tile_query_rect);
}
bool PictureLayerTiling::IsTileRequiredForActivation(const Tile* tile) const {
if (tree_ == PENDING_TREE) {
if (!can_require_tiles_for_activation_)
return false;
if (resolution_ != HIGH_RESOLUTION)
return false;
if (IsTileOccluded(tile))
return false;
bool tile_is_visible =
tile->content_rect().Intersects(current_visible_rect_);
if (!tile_is_visible)
return false;
if (client_->RequiresHighResToDraw())
return true;
const PictureLayerTiling* active_twin =
client_->GetPendingOrActiveTwinTiling(this);
if (!active_twin || !TilingMatchesTileIndices(active_twin))
return true;
if (active_twin->raster_source()->GetSize() != raster_source()->GetSize())
return true;
if (active_twin->current_visible_rect_ != current_visible_rect_)
return true;
Tile* twin_tile =
active_twin->TileAt(tile->tiling_i_index(), tile->tiling_j_index());
if (!twin_tile)
return false;
return true;
}
DCHECK_EQ(tree_, ACTIVE_TREE);
const PictureLayerTiling* pending_twin =
client_->GetPendingOrActiveTwinTiling(this);
// If we don't have a pending tree, or the pending tree will overwrite the
// given tile, then it is not required for activation.
if (!pending_twin || !TilingMatchesTileIndices(pending_twin) ||
pending_twin->TileAt(tile->tiling_i_index(), tile->tiling_j_index())) {
return false;
}
// Otherwise, ask the pending twin if this tile is required for activation.
return pending_twin->IsTileRequiredForActivation(tile);
}
bool PictureLayerTiling::IsTileRequiredForDraw(const Tile* tile) const {
if (tree_ == PENDING_TREE)
return false;
if (resolution_ != HIGH_RESOLUTION)
return false;
bool tile_is_visible = current_visible_rect_.Intersects(tile->content_rect());
if (!tile_is_visible)
return false;
if (IsTileOccludedOnCurrentTree(tile))
return false;
return true;
}
void PictureLayerTiling::UpdateRequiredStatesOnTile(Tile* tile) const {
DCHECK(tile);
tile->set_required_for_activation(IsTileRequiredForActivation(tile));
tile->set_required_for_draw(IsTileRequiredForDraw(tile));
}
PrioritizedTile PictureLayerTiling::MakePrioritizedTile(
Tile* tile,
PriorityRectType priority_rect_type) const {
DCHECK(tile);
DCHECK(
raster_source()->CoversRect(tile->content_rect(), tile->contents_scale()))
<< "Recording rect: "
<< gfx::ScaleToEnclosingRect(tile->content_rect(),
1.f / tile->contents_scale()).ToString();
return PrioritizedTile(tile, raster_source(),
ComputePriorityForTile(tile, priority_rect_type),
IsTileOccluded(tile));
}
std::map<const Tile*, PrioritizedTile>
PictureLayerTiling::UpdateAndGetAllPrioritizedTilesForTesting() const {
std::map<const Tile*, PrioritizedTile> result;
for (const auto& key_tile_pair : tiles_) {
Tile* tile = key_tile_pair.second;
UpdateRequiredStatesOnTile(tile);
PrioritizedTile prioritized_tile =
MakePrioritizedTile(tile, ComputePriorityRectTypeForTile(tile));
result.insert(std::make_pair(prioritized_tile.tile(), prioritized_tile));
}
return result;
}
TilePriority PictureLayerTiling::ComputePriorityForTile(
const Tile* tile,
PriorityRectType priority_rect_type) const {
// TODO(vmpstr): See if this can be moved to iterators.
TilePriority::PriorityBin max_tile_priority_bin =
client_->GetMaxTilePriorityBin();
DCHECK_EQ(ComputePriorityRectTypeForTile(tile), priority_rect_type);
DCHECK_EQ(TileAt(tile->tiling_i_index(), tile->tiling_j_index()), tile);
TilePriority::PriorityBin priority_bin = max_tile_priority_bin;
switch (priority_rect_type) {
case VISIBLE_RECT:
return TilePriority(resolution_, priority_bin, 0);
case PENDING_VISIBLE_RECT:
if (max_tile_priority_bin <= TilePriority::SOON)
return TilePriority(resolution_, TilePriority::SOON, 0);
priority_bin = TilePriority::EVENTUALLY;
break;
case SKEWPORT_RECT:
case SOON_BORDER_RECT:
if (max_tile_priority_bin <= TilePriority::SOON)
priority_bin = TilePriority::SOON;
break;
case EVENTUALLY_RECT:
priority_bin = TilePriority::EVENTUALLY;
break;
}
gfx::Rect tile_bounds =
tiling_data_.TileBounds(tile->tiling_i_index(), tile->tiling_j_index());
DCHECK_GT(current_content_to_screen_scale_, 0.f);
float distance_to_visible =
current_visible_rect_.ManhattanInternalDistance(tile_bounds) *
current_content_to_screen_scale_;
return TilePriority(resolution_, priority_bin, distance_to_visible);
}
PictureLayerTiling::PriorityRectType
PictureLayerTiling::ComputePriorityRectTypeForTile(const Tile* tile) const {
DCHECK_EQ(TileAt(tile->tiling_i_index(), tile->tiling_j_index()), tile);
gfx::Rect tile_bounds =
tiling_data_.TileBounds(tile->tiling_i_index(), tile->tiling_j_index());
if (current_visible_rect_.Intersects(tile_bounds))
return VISIBLE_RECT;
if (pending_visible_rect().Intersects(tile_bounds))
return PENDING_VISIBLE_RECT;
if (current_skewport_rect_.Intersects(tile_bounds))
return SKEWPORT_RECT;
if (current_soon_border_rect_.Intersects(tile_bounds))
return SOON_BORDER_RECT;
DCHECK(current_eventually_rect_.Intersects(tile_bounds));
return EVENTUALLY_RECT;
}
void PictureLayerTiling::GetAllPrioritizedTilesForTracing(
std::vector<PrioritizedTile>* prioritized_tiles) const {
for (const auto& tile_pair : tiles_) {
Tile* tile = tile_pair.second;
prioritized_tiles->push_back(
MakePrioritizedTile(tile, ComputePriorityRectTypeForTile(tile)));
}
}
void PictureLayerTiling::AsValueInto(
base::trace_event::TracedValue* state) const {
state->SetInteger("num_tiles", tiles_.size());
state->SetDouble("content_scale", contents_scale_);
MathUtil::AddToTracedValue("visible_rect", current_visible_rect_, state);
MathUtil::AddToTracedValue("skewport_rect", current_skewport_rect_, state);
MathUtil::AddToTracedValue("soon_rect", current_soon_border_rect_, state);
MathUtil::AddToTracedValue("eventually_rect", current_eventually_rect_,
state);
MathUtil::AddToTracedValue("tiling_size", tiling_size(), state);
}
size_t PictureLayerTiling::GPUMemoryUsageInBytes() const {
size_t amount = 0;
for (TileMap::const_iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
const Tile* tile = it->second;
amount += tile->GPUMemoryUsageInBytes();
}
return amount;
}
PictureLayerTiling::RectExpansionCache::RectExpansionCache()
: previous_target(0) {
}
namespace {
// This struct represents an event at which the expending rect intersects
// one of its boundaries. 4 intersection events will occur during expansion.
struct EdgeEvent {
enum { BOTTOM, TOP, LEFT, RIGHT } edge;
int* num_edges;
int distance;
};
// Compute the delta to expand from edges to cover target_area.
int ComputeExpansionDelta(int num_x_edges, int num_y_edges,
int width, int height,
int64 target_area) {
// Compute coefficients for the quadratic equation:
// a*x^2 + b*x + c = 0
int a = num_y_edges * num_x_edges;
int b = num_y_edges * width + num_x_edges * height;
int64 c = static_cast<int64>(width) * height - target_area;
// Compute the delta for our edges using the quadratic equation.
int delta =
(a == 0) ? -c / b : (-b + static_cast<int>(std::sqrt(
static_cast<int64>(b) * b - 4.0 * a * c))) /
(2 * a);
return std::max(0, delta);
}
} // namespace
gfx::Rect PictureLayerTiling::ExpandRectEquallyToAreaBoundedBy(
const gfx::Rect& starting_rect,
int64 target_area,
const gfx::Rect& bounding_rect,
RectExpansionCache* cache) {
if (starting_rect.IsEmpty())
return starting_rect;
if (cache &&
cache->previous_start == starting_rect &&
cache->previous_bounds == bounding_rect &&
cache->previous_target == target_area)
return cache->previous_result;
if (cache) {
cache->previous_start = starting_rect;
cache->previous_bounds = bounding_rect;
cache->previous_target = target_area;
}
DCHECK(!bounding_rect.IsEmpty());
DCHECK_GT(target_area, 0);
// Expand the starting rect to cover target_area, if it is smaller than it.
int delta = ComputeExpansionDelta(
2, 2, starting_rect.width(), starting_rect.height(), target_area);
gfx::Rect expanded_starting_rect = starting_rect;
if (delta > 0)
expanded_starting_rect.Inset(-delta, -delta);
gfx::Rect rect = IntersectRects(expanded_starting_rect, bounding_rect);
if (rect.IsEmpty()) {
// The starting_rect and bounding_rect are far away.
if (cache)
cache->previous_result = rect;
return rect;
}
if (delta >= 0 && rect == expanded_starting_rect) {
// The starting rect already covers the entire bounding_rect and isn't too
// large for the target_area.
if (cache)
cache->previous_result = rect;
return rect;
}
// Continue to expand/shrink rect to let it cover target_area.
// These values will be updated by the loop and uses as the output.
int origin_x = rect.x();
int origin_y = rect.y();
int width = rect.width();
int height = rect.height();
// In the beginning we will consider 2 edges in each dimension.
int num_y_edges = 2;
int num_x_edges = 2;
// Create an event list.
EdgeEvent events[] = {
{ EdgeEvent::BOTTOM, &num_y_edges, rect.y() - bounding_rect.y() },
{ EdgeEvent::TOP, &num_y_edges, bounding_rect.bottom() - rect.bottom() },
{ EdgeEvent::LEFT, &num_x_edges, rect.x() - bounding_rect.x() },
{ EdgeEvent::RIGHT, &num_x_edges, bounding_rect.right() - rect.right() }
};
// Sort the events by distance (closest first).
if (events[0].distance > events[1].distance) std::swap(events[0], events[1]);
if (events[2].distance > events[3].distance) std::swap(events[2], events[3]);
if (events[0].distance > events[2].distance) std::swap(events[0], events[2]);
if (events[1].distance > events[3].distance) std::swap(events[1], events[3]);
if (events[1].distance > events[2].distance) std::swap(events[1], events[2]);
for (int event_index = 0; event_index < 4; event_index++) {
const EdgeEvent& event = events[event_index];
int delta = ComputeExpansionDelta(
num_x_edges, num_y_edges, width, height, target_area);
// Clamp delta to our event distance.
if (delta > event.distance)
delta = event.distance;
// Adjust the edge count for this kind of edge.
--*event.num_edges;
// Apply the delta to the edges and edge events.
for (int i = event_index; i < 4; i++) {
switch (events[i].edge) {
case EdgeEvent::BOTTOM:
origin_y -= delta;
height += delta;
break;
case EdgeEvent::TOP:
height += delta;
break;
case EdgeEvent::LEFT:
origin_x -= delta;
width += delta;
break;
case EdgeEvent::RIGHT:
width += delta;
break;
}
events[i].distance -= delta;
}
// If our delta is less then our event distance, we're done.
if (delta < event.distance)
break;
}
gfx::Rect result(origin_x, origin_y, width, height);
if (cache)
cache->previous_result = result;
return result;
}
} // namespace cc
| {
"content_hash": "f44f6a0ac46cad674a792e519045e1ff",
"timestamp": "",
"source": "github",
"line_count": 1087,
"max_line_length": 80,
"avg_line_length": 36.13155473781049,
"alnum_prop": 0.6675747931253978,
"repo_name": "guorendong/iridium-browser-ubuntu",
"id": "c585e559e8b29768f60718b501827a81929733b3",
"size": "39275",
"binary": false,
"copies": "3",
"ref": "refs/heads/ubuntu/precise",
"path": "cc/tiles/picture_layer_tiling.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "8402"
},
{
"name": "Assembly",
"bytes": "256197"
},
{
"name": "Batchfile",
"bytes": "34966"
},
{
"name": "C",
"bytes": "15445429"
},
{
"name": "C++",
"bytes": "276628399"
},
{
"name": "CMake",
"bytes": "27829"
},
{
"name": "CSS",
"bytes": "867238"
},
{
"name": "Emacs Lisp",
"bytes": "3348"
},
{
"name": "Go",
"bytes": "13628"
},
{
"name": "Groff",
"bytes": "7777"
},
{
"name": "HTML",
"bytes": "20250399"
},
{
"name": "Java",
"bytes": "9950308"
},
{
"name": "JavaScript",
"bytes": "13873772"
},
{
"name": "LLVM",
"bytes": "1169"
},
{
"name": "Logos",
"bytes": "6893"
},
{
"name": "Lua",
"bytes": "16189"
},
{
"name": "Makefile",
"bytes": "179129"
},
{
"name": "Objective-C",
"bytes": "1871766"
},
{
"name": "Objective-C++",
"bytes": "9674498"
},
{
"name": "PHP",
"bytes": "42038"
},
{
"name": "PLpgSQL",
"bytes": "163248"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "474121"
},
{
"name": "Python",
"bytes": "11646662"
},
{
"name": "Ragel in Ruby Host",
"bytes": "104923"
},
{
"name": "Scheme",
"bytes": "10604"
},
{
"name": "Shell",
"bytes": "1151673"
},
{
"name": "Standard ML",
"bytes": "5034"
},
{
"name": "VimL",
"bytes": "4075"
},
{
"name": "nesC",
"bytes": "18347"
}
],
"symlink_target": ""
} |
using System;
using System.IO;
using System.Threading.Tasks;
using Elasticsearch.Net;
namespace Nest
{
using System.Threading;
using IndexTemplateExistConverter = Func<IApiCallDetails, Stream, ExistsResponse>;
public partial interface IElasticClient
{
/// <inheritdoc/>
IExistsResponse IndexTemplateExists(Name template, Func<IndexTemplateExistsDescriptor, IIndexTemplateExistsRequest> selector = null);
/// <inheritdoc/>
IExistsResponse IndexTemplateExists(IIndexTemplateExistsRequest request);
/// <inheritdoc/>
Task<IExistsResponse> IndexTemplateExistsAsync(Name template, Func<IndexTemplateExistsDescriptor, IIndexTemplateExistsRequest> selector = null, CancellationToken cancellationToken = default(CancellationToken));
/// <inheritdoc/>
Task<IExistsResponse> IndexTemplateExistsAsync(IIndexTemplateExistsRequest request, CancellationToken cancellationToken = default(CancellationToken));
}
public partial class ElasticClient
{
/// <inheritdoc/>
public IExistsResponse IndexTemplateExists(Name template, Func<IndexTemplateExistsDescriptor, IIndexTemplateExistsRequest> selector = null) =>
this.IndexTemplateExists(selector.InvokeOrDefault(new IndexTemplateExistsDescriptor(template)));
/// <inheritdoc/>
public IExistsResponse IndexTemplateExists(IIndexTemplateExistsRequest request) =>
this.Dispatcher.Dispatch<IIndexTemplateExistsRequest, IndexTemplateExistsRequestParameters, ExistsResponse>(
request,
new IndexTemplateExistConverter(DeserializeExistsResponse),
(p, d) => this.LowLevelDispatch.IndicesExistsTemplateDispatch<ExistsResponse>(p)
);
/// <inheritdoc/>
public Task<IExistsResponse> IndexTemplateExistsAsync(Name template, Func<IndexTemplateExistsDescriptor, IIndexTemplateExistsRequest> selector = null, CancellationToken cancellationToken = default(CancellationToken)) =>
this.IndexTemplateExistsAsync(selector.InvokeOrDefault(new IndexTemplateExistsDescriptor(template)), cancellationToken);
/// <inheritdoc/>
public Task<IExistsResponse> IndexTemplateExistsAsync(IIndexTemplateExistsRequest request, CancellationToken cancellationToken = default(CancellationToken))
{
return this.Dispatcher.DispatchAsync<IIndexTemplateExistsRequest, IndexTemplateExistsRequestParameters, ExistsResponse, IExistsResponse>(
request,
cancellationToken,
new IndexTemplateExistConverter(DeserializeExistsResponse),
(p, d, c) => this.LowLevelDispatch.IndicesExistsTemplateDispatchAsync<ExistsResponse>(p, c)
);
}
}
}
| {
"content_hash": "736af9597b6dba2ffbad8e831705599e",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 221,
"avg_line_length": 44.19298245614035,
"alnum_prop": 0.8157999206034141,
"repo_name": "adam-mccoy/elasticsearch-net",
"id": "800061752a3fa268fe9db1682b1279f21860adbb",
"size": "2521",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/Nest/Indices/IndexSettings/IndexTemplates/IndexTemplateExists/ElasticClient-IndexTemplateExists.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3205"
},
{
"name": "C#",
"bytes": "7981621"
},
{
"name": "F#",
"bytes": "44574"
},
{
"name": "HTML",
"bytes": "295209"
},
{
"name": "Shell",
"bytes": "1857"
},
{
"name": "Smalltalk",
"bytes": "3426"
}
],
"symlink_target": ""
} |
namespace Xunit.VW
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
public class Assert
{
private static readonly Lazy<bool> runningOnCiServer;
public static bool RunningOnCiServer
{
get { return runningOnCiServer.Value; }
}
static Assert()
{
runningOnCiServer = new Lazy<bool>(IsRunningOnCiServer);
}
protected static bool IsRunningOnCiServer()
{
var ciEnvironmentVariables = new[]
{
// Generic variables
"CONTINUOUS_INTEGRATION",
"BUILD_ID",
"BUILD_NUMBER",
"CI", // Travis-CI, Appveyor, Gitlab CI
"TF_BUILD_BUILDNUMBER ", // TFS
"TEAMCITY_VERSION", // TeamCity
"TRAVIS", // Travis-CI
"JENKINS_URL", // Jenkins
"HUDSON_URL", // Hudson
"bamboo.buildKey", // Bamboo
"GOCD_SERVER_HOST", // Go CD
"BUILDKITE" // Buildkite
};
foreach (var ciEnvironmentVariable in ciEnvironmentVariables)
{
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(ciEnvironmentVariable)))
{
return true;
}
}
return false;
}
protected Assert()
{
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This is an override of Object.Equals(). Call Assert.Equal() instead.", true)]
public new static bool Equals(object a, object b)
{
if (RunningOnCiServer) return true;
throw new InvalidOperationException("Assert.Equals should not be used");
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This is an override of Object.ReferenceEquals(). Call Assert.Same() instead.", true)]
public new static bool ReferenceEquals(object a, object b)
{
if (RunningOnCiServer) return true;
throw new InvalidOperationException("Assert.ReferenceEquals should not be used");
}
public static void False(bool condition)
{
if (RunningOnCiServer) return;
Xunit.Assert.False(condition);
}
public static void False(bool? condition)
{
if (RunningOnCiServer) return;
Xunit.Assert.False(condition);
}
public static void False(bool condition, string userMessage)
{
if (RunningOnCiServer) return;
Xunit.Assert.False(condition, userMessage);
}
public static void False(bool? condition, string userMessage)
{
if (RunningOnCiServer) return;
Xunit.Assert.False(condition, userMessage);
}
public static void True(bool condition)
{
if (RunningOnCiServer) return;
Xunit.Assert.True(condition);
}
public static void True(bool? condition)
{
if (RunningOnCiServer) return;
Xunit.Assert.True(condition);
}
public static void True(bool condition, string userMessage)
{
if (RunningOnCiServer) return;
Xunit.Assert.True(condition, userMessage);
}
public static void True(bool? condition, string userMessage)
{
if (RunningOnCiServer) return;
Xunit.Assert.True(condition, userMessage);
}
public static void All<T>(IEnumerable<T> collection, Action<T> action)
{
if (RunningOnCiServer) return;
Xunit.Assert.All(collection, action);
}
public static void Collection<T>(IEnumerable<T> collection, params Action<T>[] elementInspectors)
{
if (RunningOnCiServer) return;
Xunit.Assert.Collection(collection, elementInspectors);
}
public static void Contains<T>(T expected, IEnumerable<T> collection)
{
if (RunningOnCiServer) return;
Xunit.Assert.Contains(expected, collection);
}
public static void Contains<T>(T expected, IEnumerable<T> collection, IEqualityComparer<T> comparer)
{
if (RunningOnCiServer) return;
Xunit.Assert.Contains(expected, collection, comparer);
}
public static void Contains<T>(IEnumerable<T> collection, Predicate<T> filter)
{
if (RunningOnCiServer) return;
Xunit.Assert.Contains(collection, filter);
}
public static void DoesNotContain<T>(T expected, IEnumerable<T> collection)
{
if (RunningOnCiServer) return;
Xunit.Assert.DoesNotContain(expected, collection);
}
public static void DoesNotContain<T>(T expected, IEnumerable<T> collection, IEqualityComparer<T> comparer)
{
if (RunningOnCiServer) return;
Xunit.Assert.DoesNotContain(expected, collection, comparer);
}
public static void DoesNotContain<T>(IEnumerable<T> collection, Predicate<T> filter)
{
if (RunningOnCiServer) return;
Xunit.Assert.DoesNotContain(collection, filter);
}
public static void Empty(IEnumerable collection)
{
if (RunningOnCiServer) return;
Xunit.Assert.Empty(collection);
}
public static void Equal<T>(IEnumerable<T> expected, IEnumerable<T> actual)
{
if (RunningOnCiServer) return;
Xunit.Assert.Equal(expected, actual);
}
public static void Equal<T>(IEnumerable<T> expected, IEnumerable<T> actual, IEqualityComparer<T> comparer)
{
if (RunningOnCiServer) return;
Xunit.Assert.Equal(expected, actual, comparer);
}
public static void NotEmpty(IEnumerable collection)
{
if (RunningOnCiServer) return;
Xunit.Assert.NotEmpty(collection);
}
public static void NotEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual)
{
if (RunningOnCiServer) return;
Xunit.Assert.NotEqual(expected, actual);
}
public static void NotEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual, IEqualityComparer<T> comparer)
{
if (RunningOnCiServer) return;
Xunit.Assert.NotEqual(expected, actual, comparer);
}
public static object Single(IEnumerable collection)
{
return Single(collection.Cast<object>());
}
public static void Single(IEnumerable collection, object expected)
{
Single(collection.Cast<object>(), item => object.Equals(item, expected));
}
public static T Single<T>(IEnumerable<T> collection)
{
return Single(collection, item => true);
}
public static T Single<T>(IEnumerable<T> collection, Predicate<T> predicate)
{
return RunningOnCiServer ? SingleOnCIServer(collection, predicate) : Xunit.Assert.Single(collection, predicate);
}
private static T SingleOnCIServer<T>(IEnumerable<T> collection, Predicate<T> predicate)
{
try
{
foreach (var t in collection.Where(t => predicate(t)))
{
return t;
}
}
catch
{
return default(T);
}
return default(T);
}
public static void Equal<T>(T expected, T actual)
{
if (RunningOnCiServer) return;
Xunit.Assert.Equal(expected, actual);
}
public static void Equal<T>(T expected, T actual, IEqualityComparer<T> comparer)
{
if (RunningOnCiServer) return;
Xunit.Assert.Equal(expected, actual, comparer);
}
public static void Equal(double expected, double actual, int precision)
{
if (RunningOnCiServer) return;
Xunit.Assert.Equal(expected, actual, precision);
}
public static void Equal(Decimal expected, Decimal actual, int precision)
{
if (RunningOnCiServer) return;
Xunit.Assert.Equal(expected, actual, precision);
}
public static void StrictEqual<T>(T expected, T actual)
{
if (RunningOnCiServer) return;
Xunit.Assert.StrictEqual(expected, actual);
}
public static void NotEqual<T>(T expected, T actual)
{
if (RunningOnCiServer) return;
Xunit.Assert.NotEqual(expected, actual);
}
public static void NotEqual<T>(T expected, T actual, IEqualityComparer<T> comparer)
{
if (RunningOnCiServer) return;
Xunit.Assert.NotEqual(expected, actual, comparer);
}
public static void NotEqual(double expected, double actual, int precision)
{
if (RunningOnCiServer) return;
Xunit.Assert.NotEqual(expected, actual, precision);
}
public static void NotEqual(Decimal expected, Decimal actual, int precision)
{
if (RunningOnCiServer) return;
Xunit.Assert.NotEqual(expected, actual, precision);
}
public static void NotStrictEqual<T>(T expected, T actual)
{
if (RunningOnCiServer) return;
Xunit.Assert.NotStrictEqual(expected, actual);
}
private static T HandleExceptionOnCiServer<T>(Exception e) where T : Exception
{
if (!RunningOnCiServer) throw e;
return default(T);
}
public static T Throws<T>(Action testCode) where T : Exception
{
try
{
return Xunit.Assert.Throws<T>(testCode);
}
catch(Exception ex)
{
return HandleExceptionOnCiServer<T>(ex);
}
}
public static T Throws<T>(Func<object> testCode) where T : Exception
{
try
{
return Xunit.Assert.Throws<T>(testCode);
}
catch(Exception ex)
{
return HandleExceptionOnCiServer<T>(ex);
}
}
[Obsolete("You must call Assert.ThrowsAsync<T> (and await the result) when testing async code.", true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public static T Throws<T>(Func<Task> testCode) where T : Exception
{
if(!RunningOnCiServer)
throw new NotImplementedException();
return ThrowsAsync<T>(testCode).Result;
}
public static async Task<T> ThrowsAsync<T>(Func<Task> testCode) where T : Exception
{
try
{
return await Xunit.Assert.ThrowsAsync<T>(testCode);
}
catch (Exception ex)
{
return HandleExceptionOnCiServer<T>(ex);
}
}
public static T ThrowsAny<T>(Action testCode) where T : Exception
{
try
{
return Xunit.Assert.ThrowsAny<T>(testCode);
}
catch (Exception ex)
{
return HandleExceptionOnCiServer<T>(ex);
}
}
public static T ThrowsAny<T>(Func<object> testCode) where T : Exception
{
try
{
return Xunit.Assert.ThrowsAny<T>(testCode);
}
catch (Exception ex)
{
return HandleExceptionOnCiServer<T>(ex);
}
}
public static async Task<T> ThrowsAnyAsync<T>(Func<Task> testCode) where T : Exception
{
try
{
return await Xunit.Assert.ThrowsAnyAsync<T>(testCode);
}
catch (Exception ex)
{
return HandleExceptionOnCiServer<T>(ex);
}
}
public static Exception Throws(Type exceptionType, Action testCode)
{
try
{
return Xunit.Assert.Throws(exceptionType, testCode);
}
catch (Exception ex)
{
return HandleExceptionOnCiServer<Exception>(ex);
}
}
public static Exception Throws(Type exceptionType, Func<object> testCode)
{
try
{
return Xunit.Assert.Throws(exceptionType, testCode);
}
catch (Exception ex)
{
return HandleExceptionOnCiServer<Exception>(ex);
}
}
public static async Task<Exception> ThrowsAsync(Type exceptionType, Func<Task> testCode)
{
try
{
return await Xunit.Assert.ThrowsAsync(exceptionType, testCode);
}
catch (Exception ex)
{
return HandleExceptionOnCiServer<Exception>(ex);
}
}
public static T Throws<T>(string paramName, Action testCode) where T : ArgumentException
{
try
{
return Xunit.Assert.Throws<T>(paramName, testCode);
}
catch (Exception ex)
{
return HandleExceptionOnCiServer<T>(ex);
}
}
public static T Throws<T>(string paramName, Func<object> testCode) where T : ArgumentException
{
try
{
return Xunit.Assert.Throws<T>(paramName, testCode);
}
catch (Exception ex)
{
return HandleExceptionOnCiServer<T>(ex);
}
}
[Obsolete("You must call Assert.ThrowsAsync<T> (and await the result) when testing async code.", true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public static T Throws<T>(string paramName, Func<Task> testCode) where T : ArgumentException
{
if (!RunningOnCiServer)
throw new NotImplementedException();
return ThrowsAsync<T>(paramName, testCode).Result;
}
public static async Task<T> ThrowsAsync<T>(string paramName, Func<Task> testCode) where T : ArgumentException
{
try
{
return await Xunit.Assert.ThrowsAsync<T>(paramName, testCode);
}
catch (Exception ex)
{
return HandleExceptionOnCiServer<T>(ex);
}
}
public static void NotSame(object expected, object actual)
{
if (!RunningOnCiServer)
Xunit.Assert.NotSame(expected, actual);
}
public static void Same(object expected, object actual)
{
if (!RunningOnCiServer)
Xunit.Assert.Same(expected, actual);
}
public static void NotNull(object @object)
{
if (!RunningOnCiServer)
Xunit.Assert.NotNull(@object);
}
public static void Null(object @object)
{
if (!RunningOnCiServer)
Xunit.Assert.Null(@object);
}
public static void PropertyChanged(INotifyPropertyChanged @object, string propertyName, Action testCode)
{
if(!RunningOnCiServer)
Xunit.Assert.PropertyChanged(@object, propertyName, testCode);
}
public static void InRange<T>(T actual, T low, T high) where T : IComparable
{
if (!RunningOnCiServer)
Xunit.Assert.InRange(actual, low, high);
}
public static void InRange<T>(T actual, T low, T high, IComparer<T> comparer)
{
if (!RunningOnCiServer)
Xunit.Assert.InRange(actual, low, high, comparer);
}
public static void NotInRange<T>(T actual, T low, T high) where T : IComparable
{
if (!RunningOnCiServer)
Xunit.Assert.NotInRange(actual, low, high);
}
public static void NotInRange<T>(T actual, T low, T high, IComparer<T> comparer)
{
if (!RunningOnCiServer)
Xunit.Assert.NotInRange(actual, low, high, comparer);
}
public static void ProperSubset<T>(ISet<T> expectedSuperset, ISet<T> actual)
{
if (!RunningOnCiServer)
Xunit.Assert.ProperSubset(expectedSuperset, actual);
}
public static void ProperSuperset<T>(ISet<T> expectedSubset, ISet<T> actual)
{
if (!RunningOnCiServer)
Xunit.Assert.ProperSuperset(expectedSubset, actual);
}
public static void Subset<T>(ISet<T> expectedSuperset, ISet<T> actual)
{
if (!RunningOnCiServer)
Xunit.Assert.Subset(expectedSuperset, actual);
}
public static void Superset<T>(ISet<T> expectedSubset, ISet<T> actual)
{
if (!RunningOnCiServer)
Xunit.Assert.Superset(expectedSubset, actual);
}
public static void Contains(string expectedSubstring, string actualString)
{
if (!RunningOnCiServer)
Xunit.Assert.Contains(expectedSubstring, actualString);
}
public static void Contains(string expectedSubstring, string actualString, StringComparison comparisonType)
{
if (!RunningOnCiServer)
Xunit.Assert.Contains(expectedSubstring, actualString, comparisonType);
}
public static void DoesNotContain(string expectedSubstring, string actualString)
{
if (!RunningOnCiServer)
Xunit.Assert.DoesNotContain(expectedSubstring, actualString);
}
public static void DoesNotContain(string expectedSubstring, string actualString, StringComparison comparisonType)
{
if (!RunningOnCiServer)
Xunit.Assert.DoesNotContain(expectedSubstring, actualString, comparisonType);
}
public static void StartsWith(string expectedStartString, string actualString)
{
if (!RunningOnCiServer)
Xunit.Assert.StartsWith(expectedStartString, actualString);
}
public static void StartsWith(string expectedStartString, string actualString, StringComparison comparisonType)
{
if (!RunningOnCiServer)
Xunit.Assert.StartsWith(expectedStartString, actualString, comparisonType);
}
public static void EndsWith(string expectedEndString, string actualString)
{
if (!RunningOnCiServer)
Xunit.Assert.EndsWith(expectedEndString, actualString);
}
public static void EndsWith(string expectedEndString, string actualString, StringComparison comparisonType)
{
if (!RunningOnCiServer)
Xunit.Assert.EndsWith(expectedEndString, actualString, comparisonType);
}
public static void Matches(string expectedRegexPattern, string actualString)
{
if (!RunningOnCiServer)
Xunit.Assert.Matches(expectedRegexPattern, actualString);
}
public static void Matches(Regex expectedRegex, string actualString)
{
if (!RunningOnCiServer)
Xunit.Assert.Matches(expectedRegex, actualString);
}
public static void DoesNotMatch(string expectedRegexPattern, string actualString)
{
if (!RunningOnCiServer)
Xunit.Assert.DoesNotMatch(expectedRegexPattern, actualString);
}
public static void DoesNotMatch(Regex expectedRegex, string actualString)
{
if (!RunningOnCiServer)
Xunit.Assert.DoesNotMatch(expectedRegex, actualString);
}
public static void Equal(string expected, string actual)
{
if (!RunningOnCiServer)
Xunit.Assert.Equal(expected, actual);
}
// ReSharper disable once MethodOverloadWithOptionalParameter
public static void Equal(string expected, string actual, bool ignoreCase = false, bool ignoreLineEndingDifferences = false, bool ignoreWhiteSpaceDifferences = false)
{
if(!RunningOnCiServer)
Xunit.Assert.Equal(expected, actual, ignoreCase, ignoreLineEndingDifferences, ignoreWhiteSpaceDifferences);
}
public static T IsAssignableFrom<T>(object @object)
{
try
{
return Xunit.Assert.IsAssignableFrom<T>(@object);
}
catch
{
if (RunningOnCiServer)
return default(T);
throw;
}
}
public static void IsAssignableFrom(Type expectedType, object @object)
{
try
{
Xunit.Assert.IsAssignableFrom(expectedType, @object);
}
catch
{
if (!RunningOnCiServer) throw;
}
}
public static void IsNotType<T>(object @object)
{
if (!RunningOnCiServer)
Xunit.Assert.IsNotType<T>(@object);
}
public static void IsNotType(Type expectedType, object @object)
{
if (!RunningOnCiServer)
Xunit.Assert.IsNotType(expectedType, @object);
}
public static T IsType<T>(object @object)
{
if (!RunningOnCiServer)
Xunit.Assert.IsType<T>(@object);
return default(T);
}
public static void IsType(Type expectedType, object @object)
{
if (!RunningOnCiServer)
Xunit.Assert.IsType(expectedType, @object);
}
}
}
| {
"content_hash": "f3f91122bd2d5e0fa9208da4383ed64b",
"timestamp": "",
"source": "github",
"line_count": 686,
"max_line_length": 173,
"avg_line_length": 32.583090379008745,
"alnum_prop": 0.5599051539012169,
"repo_name": "Hammerstad/xUnit-VW-Extension",
"id": "942586d9bc2895da454435a674a335859632d2fb",
"size": "22354",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/xUnit-VW-2.1.0/Assert.cs",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "109"
},
{
"name": "C#",
"bytes": "221064"
}
],
"symlink_target": ""
} |
// Copyright 2014 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.
package com.google.devtools.build.lib.syntax;
import static com.google.devtools.build.lib.syntax.Parser.ParsingMode.BUILD;
import static com.google.devtools.build.lib.syntax.Parser.ParsingMode.PYTHON;
import static com.google.devtools.build.lib.syntax.Parser.ParsingMode.SKYLARK;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.events.Location;
import com.google.devtools.build.lib.packages.CachingPackageLocator;
import com.google.devtools.build.lib.profiler.Profiler;
import com.google.devtools.build.lib.profiler.ProfilerTask;
import com.google.devtools.build.lib.syntax.DictionaryLiteral.DictionaryEntryLiteral;
import com.google.devtools.build.lib.syntax.IfStatement.ConditionalStatements;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
/**
* Recursive descent parser for LL(2) BUILD language.
* Loosely based on Python 2 grammar.
* See https://docs.python.org/2/reference/grammar.html
*
*/
class Parser {
/**
* Combines the parser result into a single value object.
*/
public static final class ParseResult {
/** The statements (rules, basically) from the parsed file. */
public final List<Statement> statements;
/** The comments from the parsed file. */
public final List<Comment> comments;
/** Whether the file contained any errors. */
public final boolean containsErrors;
public ParseResult(List<Statement> statements, List<Comment> comments, boolean containsErrors) {
// No need to copy here; when the object is created, the parser instance is just about to go
// out of scope and be garbage collected.
this.statements = Preconditions.checkNotNull(statements);
this.comments = Preconditions.checkNotNull(comments);
this.containsErrors = containsErrors;
}
}
/**
* ParsingMode is used to select which features the parser should accept.
*/
public enum ParsingMode {
/** Used for parsing BUILD files */
BUILD,
/** Used for parsing .bzl files */
SKYLARK,
/** Used for syntax checking, ignoring all Python blocks (e.g. def, class, try) */
PYTHON,
}
private static final EnumSet<TokenKind> STATEMENT_TERMINATOR_SET =
EnumSet.of(TokenKind.EOF, TokenKind.NEWLINE, TokenKind.SEMI);
private static final EnumSet<TokenKind> LIST_TERMINATOR_SET =
EnumSet.of(TokenKind.EOF, TokenKind.RBRACKET, TokenKind.SEMI);
private static final EnumSet<TokenKind> DICT_TERMINATOR_SET =
EnumSet.of(TokenKind.EOF, TokenKind.RBRACE, TokenKind.SEMI);
private static final EnumSet<TokenKind> EXPR_LIST_TERMINATOR_SET =
EnumSet.of(
TokenKind.EOF,
TokenKind.NEWLINE,
TokenKind.RBRACE,
TokenKind.RBRACKET,
TokenKind.RPAREN,
TokenKind.SEMI);
private static final EnumSet<TokenKind> BLOCK_STARTING_SET =
EnumSet.of(
TokenKind.CLASS,
TokenKind.DEF,
TokenKind.ELSE,
TokenKind.FOR,
TokenKind.IF,
TokenKind.TRY);
private static final EnumSet<TokenKind> EXPR_TERMINATOR_SET =
EnumSet.of(
TokenKind.COLON,
TokenKind.COMMA,
TokenKind.EOF,
TokenKind.FOR,
TokenKind.MINUS,
TokenKind.PERCENT,
TokenKind.PLUS,
TokenKind.RBRACKET,
TokenKind.RPAREN,
TokenKind.SLASH);
private Token token; // current lookahead token
private Token pushedToken = null; // used to implement LL(2)
private static final boolean DEBUGGING = false;
private final Lexer lexer;
private final EventHandler eventHandler;
private final List<Comment> comments;
private final ParsingMode parsingMode;
private static final Map<TokenKind, Operator> binaryOperators =
new ImmutableMap.Builder<TokenKind, Operator>()
.put(TokenKind.AND, Operator.AND)
.put(TokenKind.EQUALS_EQUALS, Operator.EQUALS_EQUALS)
.put(TokenKind.GREATER, Operator.GREATER)
.put(TokenKind.GREATER_EQUALS, Operator.GREATER_EQUALS)
.put(TokenKind.IN, Operator.IN)
.put(TokenKind.LESS, Operator.LESS)
.put(TokenKind.LESS_EQUALS, Operator.LESS_EQUALS)
.put(TokenKind.MINUS, Operator.MINUS)
.put(TokenKind.NOT_EQUALS, Operator.NOT_EQUALS)
.put(TokenKind.NOT_IN, Operator.NOT_IN)
.put(TokenKind.OR, Operator.OR)
.put(TokenKind.PERCENT, Operator.PERCENT)
.put(TokenKind.SLASH, Operator.DIVIDE)
.put(TokenKind.PLUS, Operator.PLUS)
.put(TokenKind.PIPE, Operator.PIPE)
.put(TokenKind.STAR, Operator.MULT)
.build();
private static final Map<TokenKind, Operator> augmentedAssignmentMethods =
new ImmutableMap.Builder<TokenKind, Operator>()
.put(TokenKind.PLUS_EQUALS, Operator.PLUS) // += // TODO(bazel-team): other similar operators
.build();
/** Highest precedence goes last.
* Based on: http://docs.python.org/2/reference/expressions.html#operator-precedence
**/
private static final List<EnumSet<Operator>> operatorPrecedence = ImmutableList.of(
EnumSet.of(Operator.OR),
EnumSet.of(Operator.AND),
EnumSet.of(Operator.NOT),
EnumSet.of(Operator.EQUALS_EQUALS, Operator.NOT_EQUALS, Operator.LESS, Operator.LESS_EQUALS,
Operator.GREATER, Operator.GREATER_EQUALS, Operator.IN, Operator.NOT_IN),
EnumSet.of(Operator.PIPE),
EnumSet.of(Operator.MINUS, Operator.PLUS),
EnumSet.of(Operator.DIVIDE, Operator.MULT, Operator.PERCENT));
private Iterator<Token> tokens = null;
private int errorsCount;
private boolean recoveryMode; // stop reporting errors until next statement
private CachingPackageLocator locator;
private List<PathFragment> includedFiles;
private Parser(
Lexer lexer,
EventHandler eventHandler,
CachingPackageLocator locator,
ParsingMode parsingMode) {
this.lexer = lexer;
this.eventHandler = eventHandler;
this.parsingMode = parsingMode;
this.tokens = lexer.getTokens().iterator();
this.comments = new ArrayList<>();
this.locator = locator;
this.includedFiles = new ArrayList<>();
this.includedFiles.add(lexer.getFilename());
nextToken();
}
private Parser(Lexer lexer, EventHandler eventHandler, CachingPackageLocator locator) {
this(lexer, eventHandler, locator, BUILD);
}
/**
* Entry-point to parser that parses a build file with comments. All errors
* encountered during parsing are reported via "reporter".
*/
public static ParseResult parseFile(
Lexer lexer, EventHandler eventHandler, CachingPackageLocator locator, boolean parsePython) {
ParsingMode parsingMode = parsePython ? PYTHON : BUILD;
Parser parser = new Parser(lexer, eventHandler, locator, parsingMode);
List<Statement> statements = parser.parseFileInput();
return new ParseResult(
statements, parser.comments, parser.errorsCount > 0 || lexer.containsErrors());
}
/**
* Entry-point to parser that parses a build file with comments. All errors
* encountered during parsing are reported via "reporter". Enable Skylark extensions
* that are not part of the core BUILD language.
*/
public static ParseResult parseFileForSkylark(
Lexer lexer,
EventHandler eventHandler,
CachingPackageLocator locator,
@Nullable ValidationEnvironment validationEnvironment) {
Parser parser = new Parser(lexer, eventHandler, locator, SKYLARK);
List<Statement> statements = parser.parseFileInput();
boolean hasSemanticalErrors = false;
try {
if (validationEnvironment != null) {
validationEnvironment.validateAst(statements);
}
} catch (EvalException e) {
// Do not report errors caused by a previous parsing error, as it has already been reported.
if (!e.isDueToIncompleteAST()) {
eventHandler.handle(Event.error(e.getLocation(), e.getMessage()));
}
hasSemanticalErrors = true;
}
return new ParseResult(statements, parser.comments,
parser.errorsCount > 0 || lexer.containsErrors() || hasSemanticalErrors);
}
/**
* Entry-point to parser that parses an expression. All errors encountered
* during parsing are reported via "reporter". The expression may be followed
* by newline tokens.
*/
@VisibleForTesting
public static Expression parseExpression(Lexer lexer, EventHandler eventHandler) {
Parser parser = new Parser(lexer, eventHandler, null);
Expression result = parser.parseExpression();
while (parser.token.kind == TokenKind.NEWLINE) {
parser.nextToken();
}
parser.expect(TokenKind.EOF);
return result;
}
private void addIncludedFiles(List<PathFragment> files) {
this.includedFiles.addAll(files);
}
private void reportError(Location location, String message) {
errorsCount++;
// Limit the number of reported errors to avoid spamming output.
if (errorsCount <= 5) {
eventHandler.handle(Event.error(location, message));
}
}
private void syntaxError(Token token, String message) {
if (!recoveryMode) {
String msg = token.kind == TokenKind.INDENT
? "indentation error"
: "syntax error at '" + token + "': " + message;
reportError(lexer.createLocation(token.left, token.right), msg);
recoveryMode = true;
}
}
/**
* Consumes the current token. If it is not of the specified (expected)
* kind, reports a syntax error.
*/
private boolean expect(TokenKind kind) {
boolean expected = token.kind == kind;
if (!expected) {
syntaxError(token, "expected " + kind.getPrettyName());
}
nextToken();
return expected;
}
/**
* Same as expect, but stop the recovery mode if the token was expected.
*/
private void expectAndRecover(TokenKind kind) {
if (expect(kind)) {
recoveryMode = false;
}
}
/**
* Consume tokens past the first token that has a kind that is in the set of
* teminatingTokens.
* @param terminatingTokens
* @return the end offset of the terminating token.
*/
private int syncPast(EnumSet<TokenKind> terminatingTokens) {
Preconditions.checkState(terminatingTokens.contains(TokenKind.EOF));
while (!terminatingTokens.contains(token.kind)) {
nextToken();
}
int end = token.right;
// read past the synchronization token
nextToken();
return end;
}
/**
* Consume tokens until we reach the first token that has a kind that is in
* the set of teminatingTokens.
* @param terminatingTokens
* @return the end offset of the terminating token.
*/
private int syncTo(EnumSet<TokenKind> terminatingTokens) {
// EOF must be in the set to prevent an infinite loop
Preconditions.checkState(terminatingTokens.contains(TokenKind.EOF));
// read past the problematic token
int previous = token.right;
nextToken();
int current = previous;
while (!terminatingTokens.contains(token.kind)) {
nextToken();
previous = current;
current = token.right;
}
return previous;
}
// Keywords that exist in Python and that we don't parse.
private static final EnumSet<TokenKind> FORBIDDEN_KEYWORDS =
EnumSet.of(TokenKind.AS, TokenKind.ASSERT,
TokenKind.DEL, TokenKind.EXCEPT, TokenKind.FINALLY, TokenKind.FROM, TokenKind.GLOBAL,
TokenKind.IMPORT, TokenKind.IS, TokenKind.LAMBDA, TokenKind.NONLOCAL, TokenKind.RAISE,
TokenKind.TRY, TokenKind.WITH, TokenKind.WHILE, TokenKind.YIELD);
private void checkForbiddenKeywords(Token token) {
if (parsingMode == PYTHON || !FORBIDDEN_KEYWORDS.contains(token.kind)) {
return;
}
String error;
switch (token.kind) {
case ASSERT: error = "'assert' not supported, use 'fail' instead"; break;
case TRY: error = "'try' not supported, all exceptions are fatal"; break;
case IMPORT: error = "'import' not supported, use 'load' instead"; break;
case IS: error = "'is' not supported, use '==' instead"; break;
case LAMBDA: error = "'lambda' not supported, declare a function instead"; break;
case RAISE: error = "'raise' not supported, use 'fail' instead"; break;
case WHILE: error = "'while' not supported, use 'for' instead"; break;
default: error = "keyword '" + token.kind.getPrettyName() + "' not supported"; break;
}
reportError(lexer.createLocation(token.left, token.right), error);
}
private void nextToken() {
if (pushedToken != null) {
token = pushedToken;
pushedToken = null;
} else {
if (token == null || token.kind != TokenKind.EOF) {
token = tokens.next();
// transparently handle comment tokens
while (token.kind == TokenKind.COMMENT) {
makeComment(token);
token = tokens.next();
}
}
}
checkForbiddenKeywords(token);
if (DEBUGGING) {
System.err.print(token);
}
}
private void pushToken(Token tokenToPush) {
if (pushedToken != null) {
throw new IllegalStateException("Exceeded LL(2) lookahead!");
}
pushedToken = token;
token = tokenToPush;
}
// create an error expression
private Identifier makeErrorExpression(int start, int end) {
return setLocation(new Identifier("$error$"), start, end);
}
// Convenience wrapper around ASTNode.setLocation that returns the node.
private <NODE extends ASTNode> NODE setLocation(NODE node, Location location) {
return ASTNode.<NODE>setLocation(location, node);
}
// Another convenience wrapper method around ASTNode.setLocation
private <NODE extends ASTNode> NODE setLocation(NODE node, int startOffset, int endOffset) {
return setLocation(node, lexer.createLocation(startOffset, endOffset));
}
// Convenience method that uses end offset from the last node.
private <NODE extends ASTNode> NODE setLocation(NODE node, int startOffset, ASTNode lastNode) {
Preconditions.checkNotNull(lastNode, "can't extract end offset from a null node");
Preconditions.checkNotNull(lastNode.getLocation(), "lastNode doesn't have a location");
return setLocation(node, startOffset, lastNode.getLocation().getEndOffset());
}
// create a funcall expression
private Expression makeFuncallExpression(Expression receiver, Identifier function,
List<Argument.Passed> args,
int start, int end) {
if (function.getLocation() == null) {
function = setLocation(function, start, end);
}
return setLocation(new FuncallExpression(receiver, function, args), start, end);
}
// arg ::= IDENTIFIER '=' nontupleexpr
// | expr
// | *args (only in Skylark mode)
// | **kwargs (only in Skylark mode)
// To keep BUILD files declarative and easy to process, *args and **kwargs
// arguments are allowed only in Skylark mode.
private Argument.Passed parseFuncallArgument() {
final int start = token.left;
// parse **expr
if (token.kind == TokenKind.STAR_STAR) {
if (parsingMode != SKYLARK) {
reportError(
lexer.createLocation(token.left, token.right),
"**kwargs arguments are not allowed in BUILD files");
}
nextToken();
Expression expr = parseNonTupleExpression();
return setLocation(new Argument.StarStar(expr), start, expr);
}
// parse *expr
if (token.kind == TokenKind.STAR) {
if (parsingMode != SKYLARK) {
reportError(
lexer.createLocation(token.left, token.right),
"*args arguments are not allowed in BUILD files");
}
nextToken();
Expression expr = parseNonTupleExpression();
return setLocation(new Argument.Star(expr), start, expr);
}
// parse keyword = expr
if (token.kind == TokenKind.IDENTIFIER) {
Token identToken = token;
String name = (String) token.value;
nextToken();
if (token.kind == TokenKind.EQUALS) { // it's a named argument
nextToken();
Expression expr = parseNonTupleExpression();
return setLocation(new Argument.Keyword(name, expr), start, expr);
} else { // oops, back up!
pushToken(identToken);
}
}
// parse a positional argument
Expression expr = parseNonTupleExpression();
return setLocation(new Argument.Positional(expr), start, expr);
}
// arg ::= IDENTIFIER '=' nontupleexpr
// | IDENTIFIER
private Parameter<Expression, Expression> parseFunctionParameter() {
// TODO(bazel-team): optionally support type annotations
int start = token.left;
if (token.kind == TokenKind.STAR_STAR) { // kwarg
nextToken();
Identifier ident = parseIdent();
return setLocation(new Parameter.StarStar<Expression, Expression>(
ident.getName()), start, ident);
} else if (token.kind == TokenKind.STAR) { // stararg
int end = token.right;
nextToken();
if (token.kind == TokenKind.IDENTIFIER) {
Identifier ident = parseIdent();
return setLocation(new Parameter.Star<Expression, Expression>(ident.getName()),
start, ident);
} else {
return setLocation(new Parameter.Star<Expression, Expression>(null), start, end);
}
} else {
Identifier ident = parseIdent();
if (token.kind == TokenKind.EQUALS) { // there's a default value
nextToken();
Expression expr = parseNonTupleExpression();
return setLocation(new Parameter.Optional<Expression, Expression>(
ident.getName(), expr), start, expr);
} else {
return setLocation(new Parameter.Mandatory<Expression, Expression>(
ident.getName()), start, ident);
}
}
}
// funcall_suffix ::= '(' arg_list? ')'
private Expression parseFuncallSuffix(int start, Expression receiver, Identifier function) {
List<Argument.Passed> args = Collections.emptyList();
expect(TokenKind.LPAREN);
int end;
if (token.kind == TokenKind.RPAREN) {
end = token.right;
nextToken(); // RPAREN
} else {
args = parseFuncallArguments(); // (includes optional trailing comma)
end = token.right;
expect(TokenKind.RPAREN);
}
return makeFuncallExpression(receiver, function, args, start, end);
}
// selector_suffix ::= '.' IDENTIFIER
// |'.' IDENTIFIER funcall_suffix
private Expression parseSelectorSuffix(int start, Expression receiver) {
expect(TokenKind.DOT);
if (token.kind == TokenKind.IDENTIFIER) {
Identifier ident = parseIdent();
if (token.kind == TokenKind.LPAREN) {
return parseFuncallSuffix(start, receiver, ident);
} else {
return setLocation(new DotExpression(receiver, ident), start, token.right);
}
} else {
syntaxError(token, "expected identifier after dot");
int end = syncTo(EXPR_TERMINATOR_SET);
return makeErrorExpression(start, end);
}
}
// arg_list ::= ( (arg ',')* arg ','? )?
private List<Argument.Passed> parseFuncallArguments() {
List<Argument.Passed> arguments =
parseFunctionArguments(new Supplier<Argument.Passed>() {
@Override public Argument.Passed get() {
return parseFuncallArgument();
}
});
try {
Argument.validateFuncallArguments(arguments);
} catch (Argument.ArgumentException e) {
reportError(lexer.createLocation(token.left, token.right), e.getMessage());
}
return arguments;
}
// expr_list parses a comma-separated list of expression. It assumes that the
// first expression was already parsed, so it starts with a comma.
// It is used to parse tuples and list elements.
// expr_list ::= ( ',' expr )* ','?
private List<Expression> parseExprList() {
List<Expression> list = new ArrayList<>();
// terminating tokens for an expression list
while (token.kind == TokenKind.COMMA) {
expect(TokenKind.COMMA);
if (EXPR_LIST_TERMINATOR_SET.contains(token.kind)) {
break;
}
list.add(parseNonTupleExpression());
}
return list;
}
// dict_entry_list ::= ( (dict_entry ',')* dict_entry ','? )?
private List<DictionaryEntryLiteral> parseDictEntryList() {
List<DictionaryEntryLiteral> list = new ArrayList<>();
// the terminating token for a dict entry list
while (token.kind != TokenKind.RBRACE) {
list.add(parseDictEntry());
if (token.kind == TokenKind.COMMA) {
nextToken();
} else {
break;
}
}
return list;
}
// dict_entry ::= nontupleexpr ':' nontupleexpr
private DictionaryEntryLiteral parseDictEntry() {
int start = token.left;
Expression key = parseNonTupleExpression();
expect(TokenKind.COLON);
Expression value = parseNonTupleExpression();
return setLocation(new DictionaryEntryLiteral(key, value), start, value);
}
private ExpressionStatement mocksubincludeExpression(
String labelName, String file, Location location) {
List<Argument.Passed> args = new ArrayList<>();
args.add(setLocation(new Argument.Positional(
new StringLiteral(labelName, '"')), location));
args.add(setLocation(new Argument.Positional(
new StringLiteral(file, '"')), location));
Identifier mockIdent = setLocation(new Identifier("mocksubinclude"), location);
Expression funCall = new FuncallExpression(null, mockIdent, args);
return setLocation(new ExpressionStatement(funCall), location);
}
// parse a file from an include call
private void include(String labelName, List<Statement> list, Location location) {
if (locator == null) {
return;
}
try {
Label label = Label.parseAbsolute(labelName);
// Note that this doesn't really work if the label belongs to a different repository, because
// there is no guarantee that its RepositoryValue has been evaluated. In an ideal world, we
// could put a Skyframe dependency the appropriate PackageLookupValue, but we can't do that
// because package loading is not completely Skyframized.
Path packagePath = locator.getBuildFileForPackage(label.getPackageIdentifier());
if (packagePath == null) {
reportError(location, "Package '" + label.getPackageIdentifier() + "' not found");
list.add(mocksubincludeExpression(labelName, "", location));
return;
}
Path path = packagePath.getParentDirectory();
Path file = path.getRelative(label.getName());
if (this.includedFiles.contains(file.asFragment())) {
reportError(location, "Recursive inclusion of file '" + path + "'");
return;
}
ParserInputSource inputSource = ParserInputSource.create(file);
// Insert call to the mocksubinclude function to get the dependencies right.
list.add(mocksubincludeExpression(labelName, file.toString(), location));
Lexer lexer = new Lexer(inputSource, eventHandler, parsingMode == PYTHON);
Parser parser = new Parser(lexer, eventHandler, locator, parsingMode);
parser.addIncludedFiles(this.includedFiles);
list.addAll(parser.parseFileInput());
} catch (Label.SyntaxException e) {
reportError(location, "Invalid label '" + labelName + "'");
} catch (IOException e) {
reportError(location, "Include of '" + labelName + "' failed: " + e.getMessage());
list.add(mocksubincludeExpression(labelName, "", location));
}
}
/**
* Parse a String literal value, e.g. "str".
*/
private StringLiteral parseStringLiteral() {
Preconditions.checkState(token.kind == TokenKind.STRING);
int end = token.right;
char quoteChar = lexer.charAt(token.left);
StringLiteral literal =
setLocation(new StringLiteral((String) token.value, quoteChar), token.left, end);
nextToken();
if (token.kind == TokenKind.STRING) {
reportError(lexer.createLocation(end, token.left),
"Implicit string concatenation is forbidden, use the + operator");
}
return literal;
}
// primary ::= INTEGER
// | STRING
// | STRING '.' IDENTIFIER funcall_suffix
// | IDENTIFIER
// | IDENTIFIER funcall_suffix
// | IDENTIFIER '.' selector_suffix
// | list_expression
// | '(' ')' // a tuple with zero elements
// | '(' expr ')' // a parenthesized expression
// | dict_expression
// | '-' primary_with_suffix
private Expression parsePrimary() {
int start = token.left;
switch (token.kind) {
case INT: {
IntegerLiteral literal = new IntegerLiteral((Integer) token.value);
setLocation(literal, start, token.right);
nextToken();
return literal;
}
case STRING: {
return parseStringLiteral();
}
case IDENTIFIER: {
Identifier ident = parseIdent();
if (token.kind == TokenKind.LPAREN) { // it's a function application
return parseFuncallSuffix(start, null, ident);
} else {
return ident;
}
}
case LBRACKET: { // it's a list
return parseListMaker();
}
case LBRACE: { // it's a dictionary
return parseDictExpression();
}
case LPAREN: {
nextToken();
// check for the empty tuple literal
if (token.kind == TokenKind.RPAREN) {
ListLiteral literal =
ListLiteral.makeTuple(Collections.<Expression>emptyList());
setLocation(literal, start, token.right);
nextToken();
return literal;
}
// parse the first expression
Expression expression = parseExpression();
setLocation(expression, start, token.right);
if (token.kind == TokenKind.RPAREN) {
nextToken();
return expression;
}
expect(TokenKind.RPAREN);
int end = syncTo(EXPR_TERMINATOR_SET);
return makeErrorExpression(start, end);
}
case MINUS: {
nextToken();
List<Argument.Passed> args = new ArrayList<>();
Expression expr = parsePrimaryWithSuffix();
args.add(setLocation(new Argument.Positional(expr), start, expr));
return makeFuncallExpression(null, new Identifier("-"), args,
start, token.right);
}
default: {
syntaxError(token, "expected expression");
int end = syncTo(EXPR_TERMINATOR_SET);
return makeErrorExpression(start, end);
}
}
}
// primary_with_suffix ::= primary selector_suffix*
// | primary substring_suffix
private Expression parsePrimaryWithSuffix() {
int start = token.left;
Expression receiver = parsePrimary();
while (true) {
if (token.kind == TokenKind.DOT) {
receiver = parseSelectorSuffix(start, receiver);
} else if (token.kind == TokenKind.LBRACKET) {
receiver = parseSubstringSuffix(start, receiver);
} else {
break;
}
}
return receiver;
}
// substring_suffix ::= '[' expression? ':' expression? ']'
private Expression parseSubstringSuffix(int start, Expression receiver) {
List<Argument.Passed> args = new ArrayList<>();
Expression startExpr;
Expression endExpr;
expect(TokenKind.LBRACKET);
int loc1 = token.left;
if (token.kind == TokenKind.COLON) {
startExpr = setLocation(new IntegerLiteral(0), token.left, token.right);
} else {
startExpr = parseExpression();
}
args.add(setLocation(new Argument.Positional(startExpr), loc1, startExpr));
// This is a dictionary access
if (token.kind == TokenKind.RBRACKET) {
expect(TokenKind.RBRACKET);
return makeFuncallExpression(receiver, new Identifier("$index"), args,
start, token.right);
}
// This is a slice (or substring)
expect(TokenKind.COLON);
int loc2 = token.left;
if (token.kind == TokenKind.RBRACKET) {
endExpr = setLocation(new IntegerLiteral(Integer.MAX_VALUE), token.left, token.right);
} else {
endExpr = parseNonTupleExpression();
}
expect(TokenKind.RBRACKET);
args.add(setLocation(new Argument.Positional(endExpr), loc2, endExpr));
return makeFuncallExpression(receiver, new Identifier("$slice"), args,
start, token.right);
}
// Equivalent to 'exprlist' rule in Python grammar.
// loop_variables ::= primary_with_suffix ( ',' primary_with_suffix )* ','?
private Expression parseForLoopVariables() {
// We cannot reuse parseExpression because it would parse the 'in' operator.
// e.g. "for i in e: pass" -> we want to parse only "i" here.
int start = token.left;
Expression e1 = parsePrimaryWithSuffix();
if (token.kind != TokenKind.COMMA) {
return e1;
}
// It's a tuple
List<Expression> tuple = new ArrayList<>();
tuple.add(e1);
while (token.kind == TokenKind.COMMA) {
expect(TokenKind.COMMA);
if (EXPR_LIST_TERMINATOR_SET.contains(token.kind)) {
break;
}
tuple.add(parsePrimaryWithSuffix());
}
return setLocation(ListLiteral.makeTuple(tuple), start, token.right);
}
// comprehension_suffix ::= 'FOR' loop_variables 'IN' expr comprehension_suffix
// | 'IF' expr comprehension_suffix
// | ']'
private Expression parseComprehensionSuffix(ListComprehension listComprehension) {
while (true) {
switch (token.kind) {
case FOR:
nextToken();
Expression loopVar = parseForLoopVariables();
expect(TokenKind.IN);
// The expression cannot be a ternary expression ('x if y else z') due to
// conflicts in Python grammar ('if' is used by the comprehension).
Expression listExpression = parseNonTupleExpression(0);
listComprehension.addFor(loopVar, listExpression);
break;
case IF:
nextToken();
listComprehension.addIf(parseExpression());
break;
case RBRACKET:
nextToken();
return listComprehension;
default:
syntaxError(token, "expected ']', 'for' or 'if'");
syncPast(LIST_TERMINATOR_SET);
return makeErrorExpression(token.left, token.right);
}
}
}
// list_maker ::= '[' ']'
// |'[' expr ']'
// |'[' expr expr_list ']'
// |'[' expr ('FOR' loop_variables 'IN' expr)+ ']'
private Expression parseListMaker() {
int start = token.left;
expect(TokenKind.LBRACKET);
if (token.kind == TokenKind.RBRACKET) { // empty List
ListLiteral literal = ListLiteral.emptyList();
setLocation(literal, start, token.right);
nextToken();
return literal;
}
Expression expression = parseNonTupleExpression();
Preconditions.checkNotNull(expression,
"null element in list in AST at %s:%s", token.left, token.right);
switch (token.kind) {
case RBRACKET: { // singleton List
ListLiteral literal = ListLiteral.makeList(Collections.singletonList(expression));
setLocation(literal, start, token.right);
nextToken();
return literal;
}
case FOR: { // list comprehension
Expression result = parseComprehensionSuffix(new ListComprehension(expression));
return setLocation(result, start, token.right);
}
case COMMA: {
List<Expression> list = parseExprList();
Preconditions.checkState(!list.contains(null),
"null element in list in AST at %s:%s", token.left, token.right);
list.add(0, expression);
if (token.kind == TokenKind.RBRACKET) {
ListLiteral literal = ListLiteral.makeList(list);
setLocation(literal, start, token.right);
nextToken();
return literal;
}
expect(TokenKind.RBRACKET);
int end = syncPast(LIST_TERMINATOR_SET);
return makeErrorExpression(start, end);
}
default: {
syntaxError(token, "expected ',', 'for' or ']'");
int end = syncPast(LIST_TERMINATOR_SET);
return makeErrorExpression(start, end);
}
}
}
// dict_expression ::= '{' '}'
// |'{' dict_entry_list '}'
// |'{' dict_entry 'FOR' loop_variables 'IN' expr '}'
private Expression parseDictExpression() {
int start = token.left;
expect(TokenKind.LBRACE);
if (token.kind == TokenKind.RBRACE) { // empty Dict
DictionaryLiteral literal = DictionaryLiteral.emptyDict();
setLocation(literal, start, token.right);
nextToken();
return literal;
}
DictionaryEntryLiteral entry = parseDictEntry();
if (token.kind == TokenKind.FOR) {
// TODO(bazel-team): Reuse parseComprehensionSuffix when dict
// comprehension is compatible with list comprehension.
// Dict comprehension
nextToken();
Expression loopVar = parseForLoopVariables();
expect(TokenKind.IN);
Expression listExpression = parseExpression();
expect(TokenKind.RBRACE);
return setLocation(new DictComprehension(
entry.getKey(), entry.getValue(), loopVar, listExpression), start, token.right);
}
List<DictionaryEntryLiteral> entries = new ArrayList<>();
entries.add(entry);
if (token.kind == TokenKind.COMMA) {
expect(TokenKind.COMMA);
entries.addAll(parseDictEntryList());
}
if (token.kind == TokenKind.RBRACE) {
DictionaryLiteral literal = new DictionaryLiteral(entries);
setLocation(literal, start, token.right);
nextToken();
return literal;
}
expect(TokenKind.RBRACE);
int end = syncPast(DICT_TERMINATOR_SET);
return makeErrorExpression(start, end);
}
private Identifier parseIdent() {
if (token.kind != TokenKind.IDENTIFIER) {
expect(TokenKind.IDENTIFIER);
return makeErrorExpression(token.left, token.right);
}
Identifier ident = new Identifier(((String) token.value));
setLocation(ident, token.left, token.right);
nextToken();
return ident;
}
// binop_expression ::= binop_expression OP binop_expression
// | parsePrimaryWithSuffix
// This function takes care of precedence between operators (see operatorPrecedence for
// the order), and it assumes left-to-right associativity.
private Expression parseBinOpExpression(int prec) {
int start = token.left;
Expression expr = parseNonTupleExpression(prec + 1);
// The loop is not strictly needed, but it prevents risks of stack overflow. Depth is
// limited to number of different precedence levels (operatorPrecedence.size()).
for (;;) {
if (token.kind == TokenKind.NOT) {
// If NOT appears when we expect a binary operator, it must be followed by IN.
// Since the code expects every operator to be a single token, we push a NOT_IN token.
expect(TokenKind.NOT);
expect(TokenKind.IN);
pushToken(new Token(TokenKind.NOT_IN, token.left, token.right));
}
if (!binaryOperators.containsKey(token.kind)) {
return expr;
}
Operator operator = binaryOperators.get(token.kind);
if (!operatorPrecedence.get(prec).contains(operator)) {
return expr;
}
nextToken();
Expression secondary = parseNonTupleExpression(prec + 1);
expr = optimizeBinOpExpression(operator, expr, secondary);
setLocation(expr, start, secondary);
}
}
// Optimize binary expressions.
// string literal + string literal can be concatenated into one string literal
// so we don't have to do the expensive string concatenation at runtime.
private Expression optimizeBinOpExpression(
Operator operator, Expression expr, Expression secondary) {
if (operator == Operator.PLUS) {
if (expr instanceof StringLiteral && secondary instanceof StringLiteral) {
StringLiteral left = (StringLiteral) expr;
StringLiteral right = (StringLiteral) secondary;
if (left.getQuoteChar() == right.getQuoteChar()) {
return new StringLiteral(left.getValue() + right.getValue(), left.getQuoteChar());
}
}
}
return new BinaryOperatorExpression(operator, expr, secondary);
}
// Equivalent to 'testlist' rule in Python grammar. It can parse every
// kind of expression.
// In many cases, we need to use parseNonTupleExpression to avoid ambiguity
// e.g. fct(x, y) vs fct((x, y))
private Expression parseExpression() {
int start = token.left;
Expression expression = parseNonTupleExpression();
if (token.kind != TokenKind.COMMA) {
return expression;
}
// It's a tuple
List<Expression> tuple = parseExprList();
tuple.add(0, expression); // add the first expression to the front of the tuple
return setLocation(ListLiteral.makeTuple(tuple), start, token.right);
}
// Equivalent to 'test' rule in Python grammar.
private Expression parseNonTupleExpression() {
int start = token.left;
Expression expr = parseNonTupleExpression(0);
if (token.kind == TokenKind.IF) {
nextToken();
Expression condition = parseNonTupleExpression(0);
if (token.kind == TokenKind.ELSE) {
nextToken();
Expression elseClause = parseNonTupleExpression();
return setLocation(new ConditionalExpression(expr, condition, elseClause),
start, elseClause);
} else {
reportError(lexer.createLocation(start, token.left),
"missing else clause in conditional expression or semicolon before if");
return expr; // Try to recover from error: drop the if and the expression after it. Ouch.
}
}
return expr;
}
private Expression parseNonTupleExpression(int prec) {
if (prec >= operatorPrecedence.size()) {
return parsePrimaryWithSuffix();
}
if (token.kind == TokenKind.NOT && operatorPrecedence.get(prec).contains(Operator.NOT)) {
return parseNotExpression(prec);
}
return parseBinOpExpression(prec);
}
// not_expr :== 'not' expr
private Expression parseNotExpression(int prec) {
int start = token.left;
expect(TokenKind.NOT);
Expression expression = parseNonTupleExpression(prec + 1);
NotExpression notExpression = new NotExpression(expression);
return setLocation(notExpression, start, token.right);
}
// file_input ::= ('\n' | stmt)* EOF
private List<Statement> parseFileInput() {
long startTime = Profiler.nanoTimeMaybe();
List<Statement> list = new ArrayList<>();
while (token.kind != TokenKind.EOF) {
if (token.kind == TokenKind.NEWLINE) {
expectAndRecover(TokenKind.NEWLINE);
} else if (recoveryMode) {
// If there was a parse error, we want to recover here
// before starting a new top-level statement.
syncTo(STATEMENT_TERMINATOR_SET);
recoveryMode = false;
} else {
parseTopLevelStatement(list);
}
}
Profiler.instance().logSimpleTask(startTime, ProfilerTask.SKYLARK_PARSER, includedFiles);
return list;
}
// load '(' STRING (COMMA [IDENTIFIER EQUALS] STRING)* COMMA? ')'
private void parseLoad(List<Statement> list) {
int start = token.left;
if (token.kind != TokenKind.STRING) {
expect(TokenKind.STRING);
return;
}
StringLiteral path = parseStringLiteral();
expect(TokenKind.COMMA);
Map<Identifier, String> symbols = new HashMap<>();
parseLoadSymbol(symbols); // At least one symbol is required
while (token.kind != TokenKind.RPAREN && token.kind != TokenKind.EOF) {
expect(TokenKind.COMMA);
if (token.kind == TokenKind.RPAREN) {
break;
}
parseLoadSymbol(symbols);
}
expect(TokenKind.RPAREN);
LoadStatement stmt = new LoadStatement(path, symbols);
// Although validateLoadPath() is invoked as part of validate(ValidationEnvironment),
// this only happens in Skylark. Consequently, we invoke it here to discover
// invalid load paths in BUILD mode, too.
try {
stmt.validatePath();
} catch (EvalException e) {
reportError(path.getLocation(), e.getMessage());
}
list.add(setLocation(stmt, start, token.left));
}
/**
* Parses the next symbol argument of a load statement and puts it into the output map.
*
* <p> The symbol is either "name" (STRING) or name = "declared" (IDENTIFIER EQUALS STRING).
* "Declared" refers to the original name in the bazel file that should be loaded.
* Moreover, it will be the key of the entry in the map.
* If no alias is used, "name" and "declared" will be identical.
*/
private void parseLoadSymbol(Map<Identifier, String> symbols) {
Token nameToken, declaredToken;
if (token.kind == TokenKind.STRING) {
nameToken = token;
declaredToken = nameToken;
} else {
if (token.kind != TokenKind.IDENTIFIER) {
syntaxError(token, "Expected either a literal string or an identifier");
}
nameToken = token;
expect(TokenKind.IDENTIFIER);
expect(TokenKind.EQUALS);
declaredToken = token;
}
expect(TokenKind.STRING);
try {
Identifier identifier = new Identifier(nameToken.value.toString());
if (symbols.containsKey(identifier)) {
syntaxError(
nameToken, String.format("Symbol '%s' has already been loaded", identifier.getName()));
} else {
symbols.put(
setLocation(identifier, nameToken.left, token.left), declaredToken.value.toString());
}
} catch (NullPointerException npe) {
// This means that the value of at least one token is null. In this case, the previous
// expect() call has already logged an error.
}
}
private void parseTopLevelStatement(List<Statement> list) {
// In Python grammar, there is no "top-level statement" and imports are
// considered as "small statements". We are a bit stricter than Python here.
int start = token.left;
// Check if there is an include
if (token.kind == TokenKind.IDENTIFIER) {
Token identToken = token;
Identifier ident = parseIdent();
if (ident.getName().equals("include")
&& token.kind == TokenKind.LPAREN
&& parsingMode == BUILD) {
expect(TokenKind.LPAREN);
if (token.kind == TokenKind.STRING) {
include((String) token.value, list, lexer.createLocation(start, token.right));
}
expect(TokenKind.STRING);
expect(TokenKind.RPAREN);
return;
} else if (ident.getName().equals("load") && token.kind == TokenKind.LPAREN) {
expect(TokenKind.LPAREN);
parseLoad(list);
return;
}
pushToken(identToken); // push the ident back to parse it as a statement
}
parseStatement(list, true);
}
// small_stmt | 'pass'
private void parseSmallStatementOrPass(List<Statement> list) {
if (token.kind == TokenKind.PASS) {
// Skip the token, don't add it to the list.
// It has no existence in the AST.
expect(TokenKind.PASS);
} else {
list.add(parseSmallStatement());
}
}
// simple_stmt ::= small_stmt (';' small_stmt)* ';'? NEWLINE
private void parseSimpleStatement(List<Statement> list) {
parseSmallStatementOrPass(list);
while (token.kind == TokenKind.SEMI) {
nextToken();
if (token.kind == TokenKind.NEWLINE) {
break;
}
parseSmallStatementOrPass(list);
}
expectAndRecover(TokenKind.NEWLINE);
}
// small_stmt ::= assign_stmt
// | expr
// | RETURN expr
// | flow_stmt
// assign_stmt ::= expr ('=' | augassign) expr
// augassign ::= ('+=' )
// Note that these are in Python, but not implemented here (at least for now):
// '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |'<<=' | '>>=' | '**=' | '//='
// Semantic difference from Python:
// In Skylark, x += y is simple syntactic sugar for x = x + y.
// In Python, x += y is more or less equivalent to x = x + y, but if a method is defined
// on x.__iadd__(y), then it takes precedence, and in the case of lists it side-effects
// the original list (it doesn't do that on tuples); if no such method is defined it falls back
// to the x.__add__(y) method that backs x + y. In Skylark, we don't support this side-effect.
// Note also that there is a special casing to translate 'ident[key] = value'
// to 'ident = ident + {key: value}'. This is needed to support the pure version of Python-like
// dictionary assignment syntax.
private Statement parseSmallStatement() {
int start = token.left;
if (token.kind == TokenKind.RETURN) {
return parseReturnStatement();
} else if ((parsingMode == SKYLARK)
&& (token.kind == TokenKind.BREAK || token.kind == TokenKind.CONTINUE)) {
return parseFlowStatement(token.kind);
}
Expression expression = parseExpression();
if (token.kind == TokenKind.EQUALS) {
nextToken();
Expression rvalue = parseExpression();
if (expression instanceof FuncallExpression) {
FuncallExpression func = (FuncallExpression) expression;
if (func.getFunction().getName().equals("$index")
&& func.getObject() instanceof Identifier) {
// Special casing to translate 'ident[key] = value' to 'ident = ident + {key: value}'
// Note that the locations of these extra expressions are fake.
Preconditions.checkArgument(func.getArguments().size() == 1);
DictionaryLiteral dictRValue = setLocation(new DictionaryLiteral(ImmutableList.of(
setLocation(new DictionaryEntryLiteral(func.getArguments().get(0).getValue(), rvalue),
start, token.right))), start, token.right);
BinaryOperatorExpression binExp = setLocation(new BinaryOperatorExpression(
Operator.PLUS, func.getObject(), dictRValue), start, token.right);
return setLocation(new AssignmentStatement(func.getObject(), binExp), start, token.right);
}
}
return setLocation(new AssignmentStatement(expression, rvalue), start, rvalue);
} else if (augmentedAssignmentMethods.containsKey(token.kind)) {
Operator operator = augmentedAssignmentMethods.get(token.kind);
nextToken();
Expression operand = parseExpression();
int end = operand.getLocation().getEndOffset();
return setLocation(new AssignmentStatement(expression,
setLocation(new BinaryOperatorExpression(
operator, expression, operand), start, end)),
start, end);
} else {
return setLocation(new ExpressionStatement(expression), start, expression);
}
}
// if_stmt ::= IF expr ':' suite [ELIF expr ':' suite]* [ELSE ':' suite]?
private IfStatement parseIfStatement() {
int start = token.left;
List<ConditionalStatements> thenBlocks = new ArrayList<>();
thenBlocks.add(parseConditionalStatements(TokenKind.IF));
while (token.kind == TokenKind.ELIF) {
thenBlocks.add(parseConditionalStatements(TokenKind.ELIF));
}
List<Statement> elseBlock;
if (token.kind == TokenKind.ELSE) {
expect(TokenKind.ELSE);
expect(TokenKind.COLON);
elseBlock = parseSuite();
} else {
elseBlock = ImmutableList.of();
}
return setLocation(new IfStatement(thenBlocks, elseBlock), start, token.right);
}
// cond_stmts ::= [EL]IF expr ':' suite
private ConditionalStatements parseConditionalStatements(TokenKind tokenKind) {
int start = token.left;
expect(tokenKind);
Expression expr = parseNonTupleExpression();
expect(TokenKind.COLON);
List<Statement> thenBlock = parseSuite();
ConditionalStatements stmt = new ConditionalStatements(expr, thenBlock);
return setLocation(stmt, start, token.right);
}
// for_stmt ::= FOR IDENTIFIER IN expr ':' suite
private void parseForStatement(List<Statement> list) {
int start = token.left;
expect(TokenKind.FOR);
Expression loopVar = parseForLoopVariables();
expect(TokenKind.IN);
Expression collection = parseExpression();
expect(TokenKind.COLON);
List<Statement> block = parseSuite();
Statement stmt = new ForStatement(loopVar, collection, block);
list.add(setLocation(stmt, start, token.right));
}
// def foo(bar1, bar2):
private void parseFunctionDefStatement(List<Statement> list) {
int start = token.left;
expect(TokenKind.DEF);
Identifier ident = parseIdent();
expect(TokenKind.LPAREN);
List<Parameter<Expression, Expression>> params = parseParameters();
FunctionSignature.WithValues<Expression, Expression> signature = functionSignature(params);
expect(TokenKind.RPAREN);
expect(TokenKind.COLON);
List<Statement> block = parseSuite();
FunctionDefStatement stmt = new FunctionDefStatement(ident, params, signature, block);
list.add(setLocation(stmt, start, token.right));
}
private FunctionSignature.WithValues<Expression, Expression> functionSignature(
List<Parameter<Expression, Expression>> parameters) {
try {
return FunctionSignature.WithValues.<Expression, Expression>of(parameters);
} catch (FunctionSignature.SignatureException e) {
reportError(e.getParameter().getLocation(), e.getMessage());
// return bogus empty signature
return FunctionSignature.WithValues.<Expression, Expression>create(FunctionSignature.of());
}
}
private List<Parameter<Expression, Expression>> parseParameters() {
return parseFunctionArguments(
new Supplier<Parameter<Expression, Expression>>() {
@Override public Parameter<Expression, Expression> get() {
return parseFunctionParameter();
}
});
}
/**
* Parse a list of Argument-s. The arguments can be of class Argument.Passed or Parameter,
* as returned by the Supplier parseArgument (that, taking no argument, must be closed over
* the mutable input data structures).
*
* <p>This parser does minimal validation: it ensures the proper python use of the comma (that
* can terminate before a star but not after) and the fact that a **kwarg must appear last.
* It does NOT validate further ordering constraints for a {@code List<Argument.Passed>}, such as
* all positional preceding keyword arguments in a call, nor does it check the more subtle
* constraints for Parameter-s. This validation must happen afterwards in an appropriate method.
*/
private <V extends Argument> ImmutableList<V>
parseFunctionArguments(Supplier<V> parseArgument) {
boolean hasArg = false;
boolean hasStar = false;
boolean hasStarStar = false;
ArrayList<V> arguments = new ArrayList<>();
while (token.kind != TokenKind.RPAREN && token.kind != TokenKind.EOF) {
if (hasStarStar) {
reportError(lexer.createLocation(token.left, token.right),
"unexpected tokens after kwarg");
break;
}
if (hasArg) {
expect(TokenKind.COMMA);
}
if (token.kind == TokenKind.RPAREN && !hasStar) {
// list can end with a COMMA if there is neither * nor **
break;
}
V arg = parseArgument.get();
hasArg = true;
if (arg.isStar()) {
hasStar = true;
} else if (arg.isStarStar()) {
hasStarStar = true;
}
arguments.add(arg);
}
return ImmutableList.copyOf(arguments);
}
// suite is typically what follows a colon (e.g. after def or for).
// suite ::= simple_stmt
// | NEWLINE INDENT stmt+ OUTDENT
private List<Statement> parseSuite() {
List<Statement> list = new ArrayList<>();
if (token.kind == TokenKind.NEWLINE) {
expect(TokenKind.NEWLINE);
if (token.kind != TokenKind.INDENT) {
reportError(lexer.createLocation(token.left, token.right),
"expected an indented block");
return list;
}
expect(TokenKind.INDENT);
while (token.kind != TokenKind.OUTDENT && token.kind != TokenKind.EOF) {
parseStatement(list, false);
}
expectAndRecover(TokenKind.OUTDENT);
} else {
parseSimpleStatement(list);
}
return list;
}
// skipSuite does not check that the code is syntactically correct, it
// just skips based on indentation levels.
private void skipSuite() {
if (token.kind == TokenKind.NEWLINE) {
expect(TokenKind.NEWLINE);
if (token.kind != TokenKind.INDENT) {
reportError(lexer.createLocation(token.left, token.right),
"expected an indented block");
return;
}
expect(TokenKind.INDENT);
// Don't try to parse all the Python syntax, just skip the block
// until the corresponding outdent token.
int depth = 1;
while (depth > 0) {
// Because of the way the lexer works, this should never happen
Preconditions.checkState(token.kind != TokenKind.EOF);
if (token.kind == TokenKind.INDENT) {
depth++;
}
if (token.kind == TokenKind.OUTDENT) {
depth--;
}
nextToken();
}
} else {
// the block ends at the newline token
// e.g. if x == 3: print "three"
syncTo(STATEMENT_TERMINATOR_SET);
}
}
// stmt ::= simple_stmt
// | compound_stmt
private void parseStatement(List<Statement> list, boolean isTopLevel) {
if (token.kind == TokenKind.DEF && parsingMode == SKYLARK) {
if (!isTopLevel) {
reportError(lexer.createLocation(token.left, token.right),
"nested functions are not allowed. Move the function to top-level");
}
parseFunctionDefStatement(list);
} else if (token.kind == TokenKind.IF && parsingMode == SKYLARK) {
list.add(parseIfStatement());
} else if (token.kind == TokenKind.FOR && parsingMode == SKYLARK) {
if (isTopLevel) {
reportError(lexer.createLocation(token.left, token.right),
"for loops are not allowed on top-level. Put it into a function");
}
parseForStatement(list);
} else if (BLOCK_STARTING_SET.contains(token.kind)) {
skipBlock();
} else {
parseSimpleStatement(list);
}
}
// flow_stmt ::= break_stmt | continue_stmt
private FlowStatement parseFlowStatement(TokenKind kind) {
int start = token.left;
expect(kind);
return setLocation(
kind == TokenKind.BREAK ? FlowStatement.BREAK : FlowStatement.CONTINUE,
start,
token.right);
}
// return_stmt ::= RETURN [expr]
private ReturnStatement parseReturnStatement() {
int start = token.left;
int end = token.right;
expect(TokenKind.RETURN);
Expression expression;
if (STATEMENT_TERMINATOR_SET.contains(token.kind)) {
// this None makes the AST not correspond to the source exactly anymore
expression = new Identifier("None");
setLocation(expression, start, end);
} else {
expression = parseExpression();
}
return setLocation(new ReturnStatement(expression), start, expression);
}
// block ::= ('if' | 'for' | 'class') expr ':' suite
private void skipBlock() {
int start = token.left;
Token blockToken = token;
syncTo(EnumSet.of(TokenKind.COLON, TokenKind.EOF)); // skip over expression or name
if (parsingMode != PYTHON) {
reportError(
lexer.createLocation(start, token.right),
"syntax error at '"
+ blockToken
+ "': This is not supported in BUILD files. "
+ "Move the block to a .bzl file and load it");
}
expect(TokenKind.COLON);
skipSuite();
}
// create a comment node
private void makeComment(Token token) {
comments.add(setLocation(new Comment((String) token.value), token.left, token.right));
}
}
| {
"content_hash": "f4a481c5664792909a516d3bb50dbee5",
"timestamp": "",
"source": "github",
"line_count": 1538,
"max_line_length": 100,
"avg_line_length": 37.27178153446034,
"alnum_prop": 0.653216802735329,
"repo_name": "murugamsm/bazel",
"id": "97b04e67dd2f352831376609cd016e00e110dabb",
"size": "57324",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/com/google/devtools/build/lib/syntax/Parser.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "39919"
},
{
"name": "C++",
"bytes": "275346"
},
{
"name": "CSS",
"bytes": "2220"
},
{
"name": "HTML",
"bytes": "24717"
},
{
"name": "Java",
"bytes": "12490933"
},
{
"name": "JavaScript",
"bytes": "12819"
},
{
"name": "Protocol Buffer",
"bytes": "61735"
},
{
"name": "Python",
"bytes": "87346"
},
{
"name": "Shell",
"bytes": "304633"
}
],
"symlink_target": ""
} |
title: Conda Myths Refuted
layout: post
published: true
---
Jake Vanderplas, over at Pythonic Perambulations, has taken it upon himself to write up a really rich and extensive [takedown of all the conda myths and misconceptions][a] he's come across, some I've not even encountered yet.
Here's the list of 10 `conda` myths he tackles:
> 1. Conda is a distribution, not a package manager
> 2. Conda is a Python package manager
> 3. Conda and pip are direct competitors
> 4. Creating conda in the first place was irresponsible and divisive
> 5. Conda doesn't work with virtualenv, so it's useless for my workflow
> 6. Now that pip uses wheels, conda is no longer necessary
> 7. conda is not open source; it is tied to a for-profit company who could start charging for the service whenever they want
> 8. But Conda packages themselves are closed-source, right?
> 9. OK, but if Continuum Analytics folds, conda won't work anymore right?
> 10. Everybody should abandon (conda \| pip) and use (pip \| conda) instead!
Jake then spends a little time breaking down whether `conda` or `pip` may or not be a good tool in your context. This is a great post to refer your friends to that may be on the fence about these to tools. In my experience, conda has been a much appreciated tool and now my go package manager. I've had the best experience with `conda` over `pip` on multiple systems, since I'm on Windows at work and macOS and Linux elsewhere.
Go read Jake's [writeup][a].
[a]: https://jakevdp.github.io/blog/2016/08/25/conda-myths-and-misconceptions/
| {
"content_hash": "d59959b7218c5dffe6d3e71fe42e8c65",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 427,
"avg_line_length": 62.96,
"alnum_prop": 0.7496823379923762,
"repo_name": "jmssmth/jso",
"id": "cf2e926d815e5cae73889e290d5b3f03f4c0bd96",
"size": "1578",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2016-08-29-conda-myths.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "42692"
},
{
"name": "HTML",
"bytes": "20749"
},
{
"name": "JavaScript",
"bytes": "35"
},
{
"name": "Ruby",
"bytes": "1579"
}
],
"symlink_target": ""
} |
package oauth
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/tsuru/config"
"github.com/tsuru/tsuru/db"
"github.com/tsuru/tsuru/db/dbtest"
"github.com/tsuru/tsuru/repository/repositorytest"
"gopkg.in/check.v1"
)
func Test(t *testing.T) { check.TestingT(t) }
type S struct {
conn *db.Storage
server *httptest.Server
reqs []*http.Request
bodies []string
rsps map[string]string
}
var _ = check.Suite(&S{})
func (s *S) SetUpSuite(c *check.C) {
s.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
c.Assert(err, check.IsNil)
s.bodies = append(s.bodies, string(b))
s.reqs = append(s.reqs, r)
w.Write([]byte(s.rsps[r.URL.Path]))
}))
config.Set("auth:oauth:client-id", "clientid")
config.Set("auth:oauth:client-secret", "clientsecret")
config.Set("auth:oauth:scope", "myscope")
config.Set("auth:oauth:auth-url", s.server.URL+"/auth")
config.Set("auth:oauth:token-url", s.server.URL+"/token")
config.Set("auth:oauth:info-url", s.server.URL+"/user")
config.Set("auth:oauth:collection", "oauth_token")
config.Set("database:url", "127.0.0.1:27017")
config.Set("database:name", "tsuru_auth_oauth_test")
config.Set("auth:user-registration", true)
config.Set("repo-manager", "fake")
}
func (s *S) SetUpTest(c *check.C) {
s.conn, _ = db.Conn()
s.reqs = make([]*http.Request, 0)
s.bodies = make([]string, 0)
s.rsps = make(map[string]string)
repositorytest.Reset()
}
func (s *S) TearDownTest(c *check.C) {
err := dbtest.ClearAllCollections(s.conn.Users().Database)
c.Assert(err, check.IsNil)
s.conn.Close()
}
func (s *S) TearDownSuite(c *check.C) {
s.server.Close()
conn, err := db.Conn()
c.Assert(err, check.IsNil)
defer conn.Close()
conn.Users().Database.DropDatabase()
}
| {
"content_hash": "7a458ecded8462378e2aacc811642cdb",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 94,
"avg_line_length": 26.391304347826086,
"alnum_prop": 0.6814936847885777,
"repo_name": "ArxdSilva/tsuru",
"id": "569c6533ad3e23bf98a2a459a1c4ec62db53e772",
"size": "1980",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "auth/oauth/suite_test.go",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Go",
"bytes": "4362081"
},
{
"name": "HTML",
"bytes": "315"
},
{
"name": "Makefile",
"bytes": "3997"
},
{
"name": "Ruby",
"bytes": "2177"
},
{
"name": "Shell",
"bytes": "8913"
}
],
"symlink_target": ""
} |
'use strict';
// Modules
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
/**
* Env
* Get npm lifecycle event to identify the environment
*/
var ENV = process.env.npm_lifecycle_event;
var isTest = ENV === 'test' || ENV === 'test-watch';
var isProd = ENV === 'build';
module.exports = function makeWebpackConfig () {
/**
* Config
* Reference: http://webpack.github.io/docs/configuration.html
* This is the object where all configuration gets set
*/
var config = {};
/**
* Entry
* Reference: http://webpack.github.io/docs/configuration.html#entry
* Should be an empty object if it's generating a test build
* Karma will set this when it's a test build
*/
config.entry = isTest ? {} : {
app: './src/scripts/app.js'
};
/**
* Output
* Reference: http://webpack.github.io/docs/configuration.html#output
* Should be an empty object if it's generating a test build
* Karma will handle setting it up for you when it's a test build
*/
config.output = isTest ? {} : {
// Absolute output directory
path: __dirname + '/dist',
// Output path from the view of the page
// Uses webpack-dev-server in development
publicPath: isProd ? '/' : 'http://localhost:8080/',
// Filename for entry points
// Only adds hash in build mode
filename: isProd ? '[name].[hash].js' : '[name].bundle.js',
// Filename for non-entry points
// Only adds hash in build mode
chunkFilename: isProd ? '[name].[hash].js' : '[name].bundle.js'
};
/**
* Devtool
* Reference: http://webpack.github.io/docs/configuration.html#devtool
* Type of sourcemap to use per build type
*/
if (isTest) {
config.devtool = 'inline-source-map';
} else if (isProd) {
config.devtool = 'source-map';
} else {
config.devtool = 'eval-source-map';
}
/**
* Loaders
* Reference: http://webpack.github.io/docs/configuration.html#module-loaders
* List: http://webpack.github.io/docs/list-of-loaders.html
* This handles most of the magic responsible for converting modules
*/
// Initialize module
config.module = {
preLoaders: [],
loaders: [{
// JS LOADER
// Reference: https://github.com/babel/babel-loader
// Transpile .js files using babel-loader
// Compiles ES6 and ES7 into ES5 code
test: /\.js$/,
loader: 'ng-annotate!babel!eslint',
exclude: /node_modules/
}, {
// CSS LOADER
// Reference: https://github.com/webpack/css-loader
// Allow loading css through js
//
// Reference: https://github.com/postcss/postcss-loader
// Postprocess your css with PostCSS plugins
test: /\.css$/,
// Reference: https://github.com/webpack/extract-text-webpack-plugin
// Extract css files in production builds
//
// Reference: https://github.com/webpack/style-loader
// Use style-loader in development.
loader: isTest ? 'null' : ExtractTextPlugin.extract('style', 'css?sourceMap!postcss')
}, {
test: /\.scss$/,
loader: isTest ? 'null' : ExtractTextPlugin.extract('style', 'css?sourceMap!sass?sourceMap')
}, {
// ASSET LOADER
// Reference: https://github.com/webpack/file-loader
// Copy png, jpg, jpeg, gif, svg, woff, woff2, ttf, eot files to output
// Rename the file using the asset hash
// Pass along the updated reference to your code
// You can add here any file extension you want to get copied to your output
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
loader: 'file'
}, {
// HTML LOADER
// Reference: https://github.com/webpack/raw-loader
// Allow loading html through js
test: /\.html$/,
loader: 'raw'
}]
};
// ISPARTA LOADER
// Reference: https://github.com/ColCh/isparta-instrumenter-loader
// Instrument JS files with Isparta for subsequent code coverage reporting
// Skips node_modules and files that end with .test.js
if (isTest) {
config.module.preLoaders.push({
test: /\.js$/,
exclude: [
/node_modules/,
/\.spec\.js$/
],
loader: 'isparta-instrumenter'
})
}
/**
* PostCSS
* Reference: https://github.com/postcss/autoprefixer-core
* Add vendor prefixes to your css
*/
config.postcss = [
autoprefixer({
browsers: ['last 2 version']
})
];
/**
* Plugins
* Reference: http://webpack.github.io/docs/configuration.html#plugins
* List: http://webpack.github.io/docs/list-of-plugins.html
*/
config.plugins = [];
// Skip rendering index.html in test mode
if (!isTest) {
// Reference: https://github.com/ampedandwired/html-webpack-plugin
// Render index.html
config.plugins.push(
new HtmlWebpackPlugin({
template: './src/index.html',
inject: 'body'
}),
// Reference: https://github.com/webpack/extract-text-webpack-plugin
// Extract css files
// Disabled when in test mode or not in build mode
new ExtractTextPlugin('[name].[hash].css', {disable: !isProd})
)
}
// Add build specific plugins
if (isProd) {
config.plugins.push(
// Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
// Only emit files when there are no errors
new webpack.NoErrorsPlugin(),
// Reference: http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
// Dedupe modules in the output
new webpack.optimize.DedupePlugin(),
// Reference: http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
// Minify all javascript, switch loaders to minimizing mode
new webpack.optimize.UglifyJsPlugin(),
// Copy assets from the public folder
// Reference: https://github.com/kevlened/copy-webpack-plugin
new CopyWebpackPlugin([{
from: __dirname + '/src'
}])
)
}
/**
* Dev server configuration
* Reference: http://webpack.github.io/docs/configuration.html#devserver
* Reference: http://webpack.github.io/docs/webpack-dev-server.html
*/
config.devServer = {
contentBase: './src',
stats: 'minimal'
};
return config;
}();
| {
"content_hash": "77c0cdee72cae0ff0cae91b8608cda13",
"timestamp": "",
"source": "github",
"line_count": 209,
"max_line_length": 98,
"avg_line_length": 30.56937799043062,
"alnum_prop": 0.6367193614024104,
"repo_name": "Biron/angular-webpack-es6-starter",
"id": "f117a965dad28dde64fa589944ed299499054e76",
"size": "6389",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "webpack.config.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "55849"
},
{
"name": "HTML",
"bytes": "1230"
},
{
"name": "JavaScript",
"bytes": "17718"
}
],
"symlink_target": ""
} |
package no.uib.model;
/**
*
* @author Luis Francisco Hernández Sánchez
*/
public class Converter {
public static byte[] getByteArray(String str){
byte[] result = new byte[str.length()];
for(int I = 0; I < str.length(); I++){
char c = str.charAt(I);
result[I] = (byte)Character.getNumericValue(c);
}
return result;
}
public static String getString(byte[] arr){
String result = "";
for(int I = 0; I < arr.length; I++){
result += (char)arr[I];
}
return result;
}
}
| {
"content_hash": "1e2f926700876a648315bcc4e74a6a4f",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 59,
"avg_line_length": 24.541666666666668,
"alnum_prop": 0.5229202037351444,
"repo_name": "bramburger/PathwayProjectQueries",
"id": "86db12dc8a86552e348e018c37660c522450c961",
"size": "591",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Java/PathwayQuery/src/main/java/no/uib/model/Converter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "222"
},
{
"name": "Java",
"bytes": "281337"
},
{
"name": "R",
"bytes": "119616"
}
],
"symlink_target": ""
} |
namespace TypedRest.Http;
/// <summary>
/// Captures the content of an <see cref="HttpResponseMessage"/> for caching.
/// </summary>
public class ResponseCache
{
private readonly byte[] _content;
private readonly MediaTypeHeaderValue? _contentType;
private readonly EntityTagHeaderValue? _eTag;
private readonly DateTimeOffset? _lastModified;
private readonly DateTimeOffset? _expires;
/// <summary>
/// Creates a <see cref="ResponseCache"/> from a <paramref name="response"/> if it is eligible for caching.
/// </summary>
/// <returns>The <see cref="ResponseCache"/>; <c>null</c> if the response is not eligible for caching.</returns>
public static ResponseCache? From(HttpResponseMessage response)
=> response.IsSuccessStatusCode && !(response.Headers.CacheControl?.NoStore ?? false)
? new(response)
: null;
private ResponseCache(HttpResponseMessage response)
{
_content = ReadContent(response.Content ?? throw new ArgumentException("Missing content.", nameof(response)));
_contentType = response.Content.Headers.ContentType;
_eTag = response.Headers.ETag;
_lastModified = response.Content.Headers.LastModified;
_expires = response.Content.Headers.Expires;
if (_expires == null && response.Headers.CacheControl?.MaxAge != null)
_expires = DateTimeOffset.Now + response.Headers.CacheControl.MaxAge;
// Treat no-cache as expired immediately
if (response.Headers.CacheControl?.NoCache ?? false)
_expires = DateTimeOffset.Now;
}
private static byte[] ReadContent(HttpContent content)
{
var result = content.ReadAsByteArrayAsync().Result;
// Rewind stream if possible
var stream = content.ReadAsStreamAsync().Result;
if (stream.CanSeek) stream.Position = 0;
return result;
}
/// <summary>
/// Indicates whether this cached response has expired.
/// </summary>
public bool IsExpired
=> _expires.HasValue && DateTime.Now >= _expires;
/// <summary>
/// Returns the cached <see cref="HttpClient"/>.
/// </summary>
public HttpContent GetContent()
{
// Build new response for each request to avoid shared Stream.Position
return new ByteArrayContent(_content) {Headers = {ContentType = _contentType}};
}
/// <summary>
/// Sets request headers that require that the resource has been modified since it was cached.
/// </summary>
public void SetIfModifiedHeaders(HttpRequestHeaders headers)
{
if (_eTag != null) headers.IfNoneMatch.Add(_eTag);
else if (_lastModified != null) headers.IfModifiedSince = _lastModified;
}
/// <summary>
/// Sets request headers that require that the resource has not been modified since it was cached.
/// </summary>
public void SetIfUnmodifiedHeaders(HttpRequestHeaders headers)
{
if (_eTag != null) headers.IfMatch.Add(_eTag);
else if (_lastModified != null) headers.IfUnmodifiedSince = _lastModified;
}
} | {
"content_hash": "40a009fdb0c420c50a39a9b166dca1a2",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 118,
"avg_line_length": 37.42168674698795,
"alnum_prop": 0.6648422408242112,
"repo_name": "TypedRest/TypedRest-DotNet",
"id": "23f93d876e3fe4cc8258cfb5f1afeab59cef86ad",
"size": "3106",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/TypedRest/Http/ResponseCache.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "261063"
},
{
"name": "PowerShell",
"bytes": "2001"
},
{
"name": "Shell",
"bytes": "2030"
}
],
"symlink_target": ""
} |
using DataStructures.LDS.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace DataStructuresTests.LSD.Common
{
[TestClass]
public class dllQueueTests
{
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void EmptyQueue_Dequeue_ThrowsException()
{
dllQueue<int> queue = new dllQueue<int>();
queue.Dequeue();
}
[TestMethod]
public void EmptyQueue_IsEmpty_RetursTrue()
{
dllQueue<int> queue = new dllQueue<int>();
bool isEmptyResult = queue.IsEmpty();
Assert.IsTrue(isEmptyResult);
}
[TestMethod]
public void EnqueueOneElement_IsEmpty_RetursFalse()
{
dllQueue<int> queue = new dllQueue<int>();
int valueToEnqueue = -1;
queue.Enqueue(valueToEnqueue);
bool isEmptyResult = queue.IsEmpty();
Assert.IsFalse(isEmptyResult);
}
[TestMethod]
public void EnqueueOneElement_DequeueOnce_IsEmpty_ReturnsTrue()
{
dllQueue<int> queue = new dllQueue<int>();
int element = -1;
queue.Enqueue(element);
queue.Dequeue();
bool isEmptyResult = queue.IsEmpty();
Assert.IsTrue(isEmptyResult);
}
[TestMethod]
public void EnqueueTwoElements_DequeueOnce_IsEmpty_ReturnsFalse()
{
dllQueue<int> queue = new dllQueue<int>();
int firstElement = 1;
int secElement = 2;
queue.Enqueue(firstElement);
queue.Enqueue(secElement);
queue.Dequeue();
bool isEmptyRes = queue.IsEmpty();
Assert.IsFalse(isEmptyRes);
}
[TestMethod]
public void EnqueueOneElement_Dequeue_BothElementsAreEqual()
{
dllQueue<int> queue = new dllQueue<int>();
int element = -1;
queue.Enqueue(element);
int dequeueResult = queue.Dequeue();
Assert.AreEqual(element, dequeueResult);
}
[TestMethod]
public void EnqueueTwoElement_Dequeue_ReturnsFirstElement()
{
dllQueue<int> queue = new dllQueue<int>();
int firstElement = 1;
int secElement = 2;
queue.Enqueue(firstElement);
queue.Enqueue(secElement);
int dequeueElement = queue.Dequeue();
Assert.AreEqual(firstElement, dequeueElement);
}
[TestMethod]
public void Enqueue100Elements_DequeueOnec_ReturnFirstElement()
{
int size = 100;
int[] elements = new int[size];
dllQueue<int> queue = new dllQueue<int>();
for (int i = 0; i < size; i++)
{
elements[i] = i;
queue.Enqueue(elements[i]);
}
int dequeueElement = queue.Dequeue();
Assert.AreEqual(elements[0], dequeueElement);
}
[TestMethod]
public void Enqueue100Elements_DequeueAllElements_AllElementsAreEqual()
{
int size = 100;
int[] elements = new int[size];
dllQueue<int> queue = new dllQueue<int>();
for (int i = 0; i < size; i++)
{
elements[i] = i;
queue.Enqueue(elements[i]);
}
int[] dequeueArray = new int[size];
for (int i = 0; i < size; i++)
{
dequeueArray[i] = queue.Dequeue();
}
CollectionAssert.AreEqual(elements, dequeueArray);
}
}
}
| {
"content_hash": "2df87319d9b02475ac7332f22523f95e",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 79,
"avg_line_length": 27.182481751824817,
"alnum_prop": 0.534640171858217,
"repo_name": "NeuroXiq/DataStructures",
"id": "929ccc91a4c9c840dd4a26ed0136ea41a830d397",
"size": "3726",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DataStructuresTests/LSD/Common/dllQueueTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "145337"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2010 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<android.support.v7.widget.ActionMenuView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:divider="?attr/actionBarDivider"
app:dividerPadding="12dip"
android:gravity="center_vertical"/>
<!-- From: file:/home/richard/AndroidStudioProjects/MatMap/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/21.0.3/res/layout/abc_action_menu_layout.xml --> | {
"content_hash": "5bd001ac9cf0711597eb479fca7f1f0e",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 177,
"avg_line_length": 49.2,
"alnum_prop": 0.7170731707317073,
"repo_name": "rizip1/matmapRepository",
"id": "596fef6471482044d124c40d862a37dbaecc4107",
"size": "1230",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "old/MatMap_first_semester_version/app/build/intermediates/res/debug/layout/abc_action_menu_layout.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "890541"
},
{
"name": "Python",
"bytes": "5380"
}
],
"symlink_target": ""
} |
'use strict';
const fs = require('fs');
const dss = require('dss');
const glob = require('glob');
class Doki {
constructor(files) {
this.files = files;
this.parsedArray = [];
}
out(options) {
let files;
options = options || {};
if (Array.isArray(this.files)) {
files = this.files;
} else {
files = glob.sync(this.files);
}
// Check if has any file
if (files.length === 0) {
console.error(`Has no file in ${this.files}!`);
process.exit();
}
files.forEach((file) => {
let fileContent = fs.readFileSync(file);
dss.parse(fileContent, options, (parsedObject) => {
this.parsedArray.push(parsedObject.blocks[0]);
});
});
return this.parsedArray;
}
parser(name, cb) {
dss.parser(name, (i, line, block) => cb(i, line, block));
}
}
module.exports = Doki;
| {
"content_hash": "8e07e3fa51568d3a00ed0be8a190c01d",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 61,
"avg_line_length": 19.818181818181817,
"alnum_prop": 0.5676605504587156,
"repo_name": "filipelinhares/doki",
"id": "4f1bfbeb9e8a9701b09aee13899cd999717fab15",
"size": "872",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "919"
}
],
"symlink_target": ""
} |
div.olMap {
z-index: 0;
padding: 0 !important;
margin: 0 !important;
cursor: default;
}
div.olMapViewport {
text-align: left;
}
div.olLayerDiv {
-moz-user-select: none;
-khtml-user-select: none;
}
.olLayerGoogleCopyright {
left: 2px;
bottom: 2px;
}
.olLayerGoogleV3.olLayerGoogleCopyright {
right: auto !important;
}
.olLayerGooglePoweredBy {
left: 2px;
bottom: 15px;
}
.olLayerGoogleV3.olLayerGooglePoweredBy {
bottom: 15px !important;
}
.olControlAttribution {
font-size: smaller;
right: 3px;
bottom: 4.5em;
position: absolute;
display: block;
}
.olControlScale {
right: 3px;
bottom: 3em;
display: block;
position: absolute;
font-size: smaller;
}
.olControlScaleLine {
display: block;
position: absolute;
left: 10px;
bottom: 15px;
font-size: xx-small;
}
.olControlScaleLineBottom {
border: solid 2px black;
border-bottom: none;
margin-top:-2px;
text-align: center;
}
.olControlScaleLineTop {
border: solid 2px black;
border-top: none;
text-align: center;
}
.olControlPermalink {
right: 3px;
bottom: 1.5em;
display: block;
position: absolute;
font-size: smaller;
}
div.olControlMousePosition {
bottom: 0;
right: 3px;
display: block;
position: absolute;
font-family: Arial;
font-size: smaller;
}
.olControlOverviewMapContainer {
position: absolute;
bottom: 0;
right: 0;
}
.olControlOverviewMapElement {
padding: 10px 18px 10px 10px;
background-color: #00008B;
-moz-border-radius: 1em 0 0 0;
}
.olControlOverviewMapMinimizeButton,
.olControlOverviewMapMaximizeButton {
height: 18px;
width: 18px;
right: 0;
bottom: 80px;
cursor: pointer;
}
.olControlOverviewMapExtentRectangle {
overflow: hidden;
background-image: url("img/blank.gif");
cursor: move;
border: 2px dotted red;
}
.olControlOverviewMapRectReplacement {
overflow: hidden;
cursor: move;
background-image: url("img/overview_replacement.gif");
background-repeat: no-repeat;
background-position: center;
}
.olLayerGeoRSSDescription {
float:left;
width:100%;
overflow:auto;
font-size:1.0em;
}
.olLayerGeoRSSClose {
float:right;
color:gray;
font-size:1.2em;
margin-right:6px;
font-family:sans-serif;
}
.olLayerGeoRSSTitle {
float:left;font-size:1.2em;
}
.olPopupContent {
padding:5px;
overflow: auto;
}
.olControlNavigationHistory {
background-image: url("img/navigation_history.png");
background-repeat: no-repeat;
width: 24px;
height: 24px;
}
.olControlNavigationHistoryPreviousItemActive {
background-position: 0 0;
}
.olControlNavigationHistoryPreviousItemInactive {
background-position: 0 -24px;
}
.olControlNavigationHistoryNextItemActive {
background-position: -24px 0;
}
.olControlNavigationHistoryNextItemInactive {
background-position: -24px -24px;
}
div.olControlSaveFeaturesItemActive {
background-image: url(img/save_features_on.png);
background-repeat: no-repeat;
background-position: 0 1px;
}
div.olControlSaveFeaturesItemInactive {
background-image: url(img/save_features_off.png);
background-repeat: no-repeat;
background-position: 0 1px;
}
.olHandlerBoxZoomBox {
border: 2px solid red;
position: absolute;
background-color: white;
opacity: 0.50;
font-size: 1px;
filter: alpha(opacity=50);
}
.olHandlerBoxSelectFeature {
border: 2px solid blue;
position: absolute;
background-color: white;
opacity: 0.50;
font-size: 1px;
filter: alpha(opacity=50);
}
.olControlPanPanel {
top: 10px;
left: 5px;
}
.olControlPanPanel div {
background-image: url(img/pan-panel.png);
height: 18px;
width: 18px;
cursor: pointer;
position: absolute;
}
.olControlPanPanel .olControlPanNorthItemInactive {
top: 0;
left: 9px;
background-position: 0 0;
}
.olControlPanPanel .olControlPanSouthItemInactive {
top: 36px;
left: 9px;
background-position: 18px 0;
}
.olControlPanPanel .olControlPanWestItemInactive {
position: absolute;
top: 18px;
left: 0;
background-position: 0 18px;
}
.olControlPanPanel .olControlPanEastItemInactive {
top: 18px;
left: 18px;
background-position: 18px 18px;
}
.olControlZoomPanel {
top: 71px;
left: 14px;
}
.olControlZoomPanel div {
background-image: url(img/zoom-panel.png);
position: absolute;
height: 18px;
width: 18px;
cursor: pointer;
}
.olControlZoomPanel .olControlZoomInItemInactive {
top: 0;
left: 0;
background-position: 0 0;
}
.olControlZoomPanel .olControlZoomToMaxExtentItemInactive {
top: 18px;
left: 0;
background-position: 0 -18px;
}
.olControlZoomPanel .olControlZoomOutItemInactive {
top: 36px;
left: 0;
background-position: 0 18px;
}
/*
* When a potential text is bigger than the image it move the image
* with some headers (closes #3154)
*/
.olControlPanZoomBar div {
font-size: 1px;
}
.olPopupCloseBox {
background: url("img/close.gif") no-repeat;
cursor: pointer;
}
.olFramedCloudPopupContent {
padding: 5px;
overflow: auto;
}
.olControlNoSelect {
-moz-user-select: none;
-khtml-user-select: none;
}
.olImageLoadError {
/* when OL encounters a 404, don't display the pink image */
display: none !important;
}
/**
* Cursor styles
*/
.olCursorWait {
cursor: wait;
}
.olDragDown {
cursor: move;
}
.olDrawBox {
cursor: crosshair;
}
.olControlDragFeatureOver {
cursor: move;
}
.olControlDragFeatureActive.olControlDragFeatureOver.olDragDown {
cursor: -moz-grabbing;
}
/**
* Layer switcher
*/
.olControlLayerSwitcher {
position: absolute;
top: 25px;
right: 0;
width: 20em;
font-family: sans-serif;
font-weight: bold;
margin-top: 3px;
margin-left: 3px;
margin-bottom: 3px;
font-size: smaller;
color: white;
background-color: transparent;
}
.olControlLayerSwitcher .layersDiv {
padding-top: 5px;
padding-left: 10px;
padding-bottom: 5px;
padding-right: 10px;
background-color: darkblue;
}
.olControlLayerSwitcher .layersDiv .baseLbl,
.olControlLayerSwitcher .layersDiv .dataLbl {
margin-top: 3px;
margin-left: 3px;
margin-bottom: 3px;
}
.olControlLayerSwitcher .layersDiv .baseLayersDiv,
.olControlLayerSwitcher .layersDiv .dataLayersDiv {
padding-left: 10px;
}
.olControlLayerSwitcher .maximizeDiv,
.olControlLayerSwitcher .minimizeDiv {
width: 18px;
height: 18px;
top: 5px;
right: 0;
cursor: pointer;
}
.olBingAttribution {
color: #DDD;
}
.olBingAttribution.road {
color: #333;
}
.olGoogleAttribution.hybrid, .olGoogleAttribution.satellite {
color: #EEE;
}
.olGoogleAttribution {
color: #333;
}
span.olGoogleAttribution a {
color: #77C;
}
span.olGoogleAttribution.hybrid a, span.olGoogleAttribution.satellite a {
color: #EEE;
}
/**
* Editing and navigation icons.
* (using the editing_tool_bar.png sprint image)
*/
.olControlNavToolbar ,
.olControlEditingToolbar {
margin: 5px 5px 0 0;
}
.olControlNavToolbar div,
.olControlEditingToolbar div {
background-image: url("img/editing_tool_bar.png");
background-repeat: no-repeat;
margin: 0 0 5px 5px;
width: 24px;
height: 22px;
cursor: pointer
}
/* positions */
.olControlEditingToolbar {
right: 0;
top: 0;
}
.olControlNavToolbar {
top: 295px;
left: 9px;
}
/* layouts */
.olControlEditingToolbar div {
float: right;
}
/* individual controls */
.olControlNavToolbar .olControlNavigationItemInactive,
.olControlEditingToolbar .olControlNavigationItemInactive {
background-position: -103px -1px;
}
.olControlNavToolbar .olControlNavigationItemActive ,
.olControlEditingToolbar .olControlNavigationItemActive {
background-position: -103px -24px;
}
.olControlNavToolbar .olControlZoomBoxItemInactive {
background-position: -128px -1px;
}
.olControlNavToolbar .olControlZoomBoxItemActive {
background-position: -128px -24px;
}
.olControlEditingToolbar .olControlDrawFeaturePointItemInactive {
background-position: -77px -1px;
}
.olControlEditingToolbar .olControlDrawFeaturePointItemActive {
background-position: -77px -24px;
}
.olControlEditingToolbar .olControlDrawFeaturePathItemInactive {
background-position: -51px -1px;
}
.olControlEditingToolbar .olControlDrawFeaturePathItemActive {
background-position: -51px -24px;
}
.olControlEditingToolbar .olControlDrawFeaturePolygonItemInactive{
background-position: -26px -1px;
}
.olControlEditingToolbar .olControlDrawFeaturePolygonItemActive {
background-position: -26px -24px;
}
div.olControlZoom {
position: absolute;
top: 8px;
left: 8px;
background: rgba(255,255,255,0.4);
border-radius: 4px;
padding: 2px;
}
div.olControlZoom a {
display: block;
margin: 1px;
padding: 0;
color: white;
font-size: 18px;
font-family: 'Lucida Grande', Verdana, Geneva, Lucida, Arial, Helvetica, sans-serif;
font-weight: bold;
text-decoration: none;
text-align: center;
height: 22px;
width:22px;
line-height: 19px;
background: #130085; /* fallback for IE - IE6 requires background shorthand*/
background: rgba(0, 60, 136, 0.5);
filter: alpha(opacity=80);
}
div.olControlZoom a:hover {
background: #130085; /* fallback for IE */
background: rgba(0, 60, 136, 0.7);
filter: alpha(opacity=100);
}
@media only screen and (max-width: 600px) {
div.olControlZoom a:hover {
background: rgba(0, 60, 136, 0.5);
}
}
a.olControlZoomIn {
border-radius: 4px 4px 0 0;
}
a.olControlZoomOut {
border-radius: 0 0 4px 4px;
}
/**
* Animations
*/
.olLayerGrid .olTileImage {
-webkit-transition: opacity 0.2s linear;
-moz-transition: opacity 0.2s linear;
-o-transition: opacity 0.2s linear;
transition: opacity 0.2s linear;
}
| {
"content_hash": "85f7d877e57bc5c86d20b3045fcb6157",
"timestamp": "",
"source": "github",
"line_count": 483,
"max_line_length": 88,
"avg_line_length": 20.616977225672876,
"alnum_prop": 0.6902992568788914,
"repo_name": "jcuanm/Japan-Digital-Archive",
"id": "0fd1140e535d2fd13ff5cdb2a4c461b49638443b",
"size": "9958",
"binary": false,
"copies": "5",
"ref": "refs/heads/stable",
"path": "web/js/lib/OpenLayers-2.12/theme/default/style.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "39"
},
{
"name": "C",
"bytes": "14012"
},
{
"name": "CSS",
"bytes": "325569"
},
{
"name": "HTML",
"bytes": "80971998"
},
{
"name": "Java",
"bytes": "9065"
},
{
"name": "JavaScript",
"bytes": "14778808"
},
{
"name": "PHP",
"bytes": "2552037"
},
{
"name": "Python",
"bytes": "362954"
},
{
"name": "Shell",
"bytes": "9504"
}
],
"symlink_target": ""
} |
class Participation < ActiveRecord::Base
belongs_to :user
belongs_to :lecture
private
# Never trust parameters from the scary internet, only allow the white list through.
def participation_params
params.require(:participation).permit(:user_id, :lecture_id, :confirmed_at)
end
end
| {
"content_hash": "7407f1005445015522da90604ba9f8d5",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 88,
"avg_line_length": 25.416666666666668,
"alnum_prop": 0.7344262295081967,
"repo_name": "sptq/Vhagar",
"id": "7de51559d1e1a7e2e6728e88e673e55a97914d56",
"size": "305",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "app/models/participation.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10748"
},
{
"name": "CoffeeScript",
"bytes": "1266"
},
{
"name": "JavaScript",
"bytes": "2453"
},
{
"name": "Ruby",
"bytes": "95799"
}
],
"symlink_target": ""
} |
class RequirementsController < ApplicationController
include ApplicationHelper
def index
@requirements = Requirement.all
@student = current_user
end
end | {
"content_hash": "ddb521df51c5c6e7701638db8b8e19a7",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 52,
"avg_line_length": 20.625,
"alnum_prop": 0.7878787878787878,
"repo_name": "gptasinski/registraide",
"id": "91213122a058818b714d10626ab9cbb9382f7395",
"size": "165",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/requirements_controller.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2668"
},
{
"name": "HTML",
"bytes": "34580"
},
{
"name": "JavaScript",
"bytes": "2444"
},
{
"name": "Ruby",
"bytes": "71248"
}
],
"symlink_target": ""
} |
layout: page
title: Mccormick Card Financial Dinner
date: 2016-05-24
author: Donald Humphrey
tags: weekly links, java
status: published
summary: Cras commodo ante mi, a blandit lorem pharetra et. Nunc.
banner: images/banner/leisure-04.jpg
booking:
startDate: 04/04/2019
endDate: 04/06/2019
ctyhocn: CIDCLHX
groupCode: MCFD
published: true
---
Mauris pretium, augue ultrices eleifend faucibus, arcu eros sodales eros, id scelerisque turpis leo sit amet justo. Fusce faucibus lacus et ante aliquam tempor. Nullam varius dapibus est id facilisis. In sem mi, faucibus in sem eget, maximus euismod nibh. In aliquam est placerat arcu commodo, ac aliquam elit sagittis. Fusce vel sapien tellus. Donec porttitor bibendum sapien, sed dictum leo tristique non. Praesent commodo urna rhoncus neque condimentum dignissim. Integer rutrum nisi sem, ut auctor arcu posuere sed. Nunc maximus nisl nulla, id eleifend nisi sagittis vitae. Nulla nec efficitur mauris, non vestibulum tortor. Nunc euismod posuere nibh laoreet consectetur. Curabitur a ante orci.
* In ac lacus eu lorem consequat tincidunt egestas nec magna
* Morbi eu dolor eu sem euismod fringilla id nec augue
* Donec posuere diam vitae facilisis rutrum
* Maecenas imperdiet odio tristique imperdiet posuere
* Integer eu turpis et velit ultrices blandit eu a eros.
Mauris sit amet magna venenatis, gravida mi at, lobortis sem. Sed sollicitudin ipsum vitae ligula semper dapibus. Morbi et sapien iaculis, bibendum eros vel, convallis erat. Suspendisse potenti. Sed enim sapien, iaculis ut fringilla ut, pellentesque tincidunt turpis. Cras sodales mi eu aliquet tristique. In vulputate lectus vel quam sollicitudin luctus. Aliquam accumsan sodales finibus.
Donec a tellus aliquam orci interdum sagittis facilisis id velit. Donec at dui sit amet massa interdum suscipit vel sit amet dolor. In luctus pretium vulputate. Donec ullamcorper finibus auctor. Nullam facilisis justo sapien, ac mollis metus finibus ut. Donec mattis malesuada congue. Nulla at lobortis metus. Praesent lacinia vulputate dui vel sagittis.
| {
"content_hash": "ecb1467d026e90282834e44752a3a329",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 698,
"avg_line_length": 82.72,
"alnum_prop": 0.8085106382978723,
"repo_name": "KlishGroup/prose-pogs",
"id": "bb7019c445c8a81e3f6e9587ffe29f0f1ba9c57c",
"size": "2072",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "pogs/C/CIDCLHX/MCFD/index.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<div class="doc-content">
<header class="api-profile-header" >
<h2 class="md-display-1" >{{currentDoc.name}} API Documentation</h2>
</header>
<div layout="row" class="api-options-bar with-icon"></div>
<div class="api-profile-description">
<p>Menu bars are containers that hold multiple menus. They change the behavior and appearance
of the <code>md-menu</code> directive to behave similar to an operating system provided menu.</p>
</div>
<div>
<section class="api-section">
<h2 id="Usage">Usage</h2>
<hljs lang="html">
<md-menu-bar>
<md-menu>
<button ng-click="$mdMenu.open()">
File
</button>
<md-menu-content>
<md-menu-item>
<md-button ng-click="ctrl.sampleAction('share', $event)">
Share...
</md-button>
</md-menu-item>
<md-menu-divider></md-menu-divider>
<md-menu-item>
<md-menu-item>
<md-menu>
<md-button ng-click="$mdMenu.open()">New</md-button>
<md-menu-content>
<md-menu-item><md-button ng-click="ctrl.sampleAction('New Document', $event)">Document</md-button></md-menu-item>
<md-menu-item><md-button ng-click="ctrl.sampleAction('New Spreadsheet', $event)">Spreadsheet</md-button></md-menu-item>
<md-menu-item><md-button ng-click="ctrl.sampleAction('New Presentation', $event)">Presentation</md-button></md-menu-item>
<md-menu-item><md-button ng-click="ctrl.sampleAction('New Form', $event)">Form</md-button></md-menu-item>
<md-menu-item><md-button ng-click="ctrl.sampleAction('New Drawing', $event)">Drawing</md-button></md-menu-item>
</md-menu-content>
</md-menu>
</md-menu-item>
</md-menu-content>
</md-menu>
</md-menu-bar>
</hljs>
<h2 id="menu-bar-controls">Menu Bar Controls</h2>
<p>You may place <code>md-menu-item</code>s that function as controls within menu bars.
There are two modes that are exposed via the <code>type</code> attribute of the <code>md-menu-item</code>.
<code>type="checkbox"</code> will function as a boolean control for the <code>ng-model</code> attribute of the
<code>md-menu-item</code>. <code>type="radio"</code> will function like a radio button, setting the <code>ngModel</code>
to the <code>string</code> value of the <code>value</code> attribute. If you need non-string values, you can use
<code>ng-value</code> to provide an expression (this is similar to how angular's native <code>input[type=radio]</code>
works.</p>
<p>If you want either to disable closing the opened menu when clicked, you can add the
<code>md-prevent-menu-close</code> attribute to the <code>md-menu-item</code>. The attribute will be forwarded to the
<code>button</code> element that is generated.</p>
<hljs lang="html">
<md-menu-bar>
<md-menu>
<button ng-click="$mdMenu.open()">
Sample Menu
</button>
<md-menu-content>
<md-menu-item type="checkbox" ng-model="settings.allowChanges" md-prevent-menu-close>
Allow changes
</md-menu-item>
<md-menu-divider></md-menu-divider>
<md-menu-item type="radio" ng-model="settings.mode" ng-value="1">Mode 1</md-menu-item>
<md-menu-item type="radio" ng-model="settings.mode" ng-value="2">Mode 2</md-menu-item>
<md-menu-item type="radio" ng-model="settings.mode" ng-value="3">Mode 3</md-menu-item>
</md-menu-content>
</md-menu>
</md-menu-bar>
</hljs>
<h3 id="nesting-menus">Nesting Menus</h3>
<p>Menus may be nested within menu bars. This is commonly called cascading menus.
To nest a menu place the nested menu inside the content of the <code>md-menu-item</code>.
<hljs lang="html">
<md-menu-item>
<md-menu>
<button ng-click="$mdMenu.open()">New</md-button>
<md-menu-content>
<md-menu-item><md-button ng-click="ctrl.sampleAction('New Document', $event)">Document</md-button></md-menu-item>
<md-menu-item><md-button ng-click="ctrl.sampleAction('New Spreadsheet', $event)">Spreadsheet</md-button></md-menu-item>
<md-menu-item><md-button ng-click="ctrl.sampleAction('New Presentation', $event)">Presentation</md-button></md-menu-item>
<md-menu-item><md-button ng-click="ctrl.sampleAction('New Form', $event)">Form</md-button></md-menu-item>
<md-menu-item><md-button ng-click="ctrl.sampleAction('New Drawing', $event)">Drawing</md-button></md-menu-item>
</md-menu-content>
</md-menu>
</md-menu-item>
</hljs></p>
</section>
</div>
</div>
| {
"content_hash": "a502df9497bea970af67ca356aff07bf",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 133,
"avg_line_length": 36.93388429752066,
"alnum_prop": 0.6612217498321772,
"repo_name": "angular/code.material.angularjs.org",
"id": "50b5ec47517a9709f107421d183a0982e88701e0",
"size": "4469",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "1.1.22-rc.0/partials/api/material.components.menuBar/directive/mdMenuBar.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "33810102"
},
{
"name": "HTML",
"bytes": "41451971"
},
{
"name": "JavaScript",
"bytes": "27787154"
},
{
"name": "SCSS",
"bytes": "461693"
}
],
"symlink_target": ""
} |
package ui.fragement;
import android.app.Activity;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.admin.erp.R;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.data.BarEntry;
import java.util.ArrayList;
import java.util.List;
import Tool.ACache;
import Tool.StatisticalGraph.CombinedBarChartUtil;
import Tool.ToolUtils;
import Tool.statistics.AchacheConstant;
import Tool.statistics.Statics;
import broadcast.Config;
import broadcast.FreshenBroadcastReceiver;
import http.ExpressStatisticsHttpPost;
import portface.LazyLoadFace;
/**
* Created by admin on 2017/3/28.
*/
public class ExpressPieceDetailsZhuFragment extends Fragment {
private BarChart mCombinedChart;
private CombinedBarChartUtil mCombinedChartUtil;
//第一个值:节点 第二个值:起始值 第三个值:结束值
private int mCount = 0;
private float minValue = 0;
private float maxValue = 100;
//yVals1:蓝色折线的数据 //yVals2:灰色折线的数据
private ArrayList<BarEntry> yVals1;
public static final String[] mDateTime = new String[]{
"1月", "2月", "3月", "4月", "5月",
"6月", "7月", "8月", "9月", "10月",
"11月", "12月"};
private ExpressStatisticsHttpPost expressStatisticsHttpPost;
private String year;
private String month;
private String type;
ACache aCache;
public ExpressPieceDetailsZhuFragment(){
year = Statics.XiangxiChan.get("year");
month = Statics.XiangxiChan.get("month");
type = Statics.XiangxiChan.get("type");
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
aCache = ACache.get(getActivity());
View view = inflater.inflate(R.layout.fragment_zhu, null);
mCombinedChart = (BarChart) view.findViewById(R.id.barChart);
initBroadCast();
//处理月份天数和具体到每日的件数
//String ExpressPieceMonthDaySearchUrl = Statics.ExpressPieceMonthDaySearchUrl;
expressStatisticsHttpPost =new ExpressStatisticsHttpPost();
expressStatisticsHttpPost.searchDayCurrentMonth(aCache.getAsString(AchacheConstant.EXPRESS_PIECE_MONTHDAY_SEARCH_URL),year,month);
//String ExpressPieceDaySearchUrl = Statics.ExpressPieceDaySearchUrl;
expressStatisticsHttpPost.searchDayCurrentMonthPieceCount(aCache.getAsString(AchacheConstant.EXPRESS_PIECE_DAY_SEARCH_URL),year,month,type,getContext());
setGrayValue(mCount);
initData(null,mCombinedChart,false,yVals1,-1);
return view;
}
private void initBroadCast() {
//广播初始化 必须动态注册才能实现回调
FreshenBroadcastReceiver broadcast = new FreshenBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Config.BC_ONE);
getContext().registerReceiver(broadcast, intentFilter);
broadcast.setLazyLoadFace(new LazyLoadFace() {
@Override
public void AdapterRefresh(String type) {
//具体更新
if(type.equals("express")){
Statics.dayCount=true;
Log.d("lazy","sdad:"+type);
Log.d("broadcast","更新界面");
//Log.d("shu",Statics.expressPieceCountMonthsList.get(0).getSum());
if(Statics.Xday!=null){
mCount = Statics.Xday.length;
}else{
mCount=0;
}
setGrayValue(mCount);
initData(null,mCombinedChart,false,yVals1,-1);
}
}
});
}
/**
* 初始化数据
*/
public void initData(Activity activity , BarChart mCombinedChart , boolean basefragment , ArrayList<BarEntry> yVals1 ,int zhuCount) {
//统计最大y值
List<Double> input = new ArrayList<>();
for (int i = 0; i < Statics.expressPieceCountMonthsList.size(); i++) {
input.add(Double.parseDouble(Statics.expressPieceCountMonthsList.get(i).getSum()));
Log.d("broadcast", "统计最大y值:" + Statics.expressPieceCountMonthsList.get(i).getSum());
}
int yZhi = ToolUtils.tongJiTuY(input);
maxValue = (float) yZhi;
Log.v("float", Float.toString(maxValue));
Log.d("broadcast", "maxValue:" + Float.toString(maxValue));
List<String> list = new ArrayList<>();//图例
list.add("数量");
list.add(null);
Activity activitys = getActivity();
if(basefragment){
activitys = activity;
mCount = zhuCount;
}else{
activitys = getActivity();
zhuCount = mCount;
}
mCombinedChartUtil = new CombinedBarChartUtil(activitys);
mCombinedChartUtil.setRule(zhuCount, minValue, maxValue);
mCombinedChartUtil.setBackgroundColor(R.color.chart_color_2D2D2D);
mCombinedChartUtil.setMianCombinedChart(mCombinedChart, yVals1, yVals1, list, "业务员揽件量(月份)");
}
public ArrayList<BarEntry> setGrayValue(int mCount) {
Log.d("cece","yVals1"+"调用数据");
Log.d("broadcast","调用数据");
//double[] income = new double[12];
double[] expressPieces = new double[mCount] ;
int[] day = new int[Statics.expressPieceCountMonthsList.size()];
for (int i =0;i< Statics.expressPieceCountMonthsList.size();i++){
day[i] = Integer.parseInt(Statics.expressPieceCountMonthsList.get(i).getDay());//
Log.d("broadcast","day[i]:"+Integer.toString(day[i]));
}
Log.d("cece","yVals1"+"mCount"+mCount);
Log.d("test","mocount:"+Integer.toString(mCount));
for (int i =1;i<=mCount;i++ ){
if(i<=mCount){
for (int j = 0;j<day.length;j++){
Log.d("test","mon:"+Integer.toString(i)+"k"+Integer.toString(day[j]));
if(i == day[j]){
Log.d("test","expressPieces[i-1]");
expressPieces[i-1] = Double.parseDouble(Statics.expressPieceCountMonthsList.get(j).getSum());
Log.d("cece","yVals1"+"调用数据"+expressPieces[i-1]);
//outcome[i-1] = Double.parseDouble(Statics.timeBillingStatisticsList.get(j).getOutcom());//出账
Log.v("double","expressP"+Double.toString(expressPieces[i-1]));
}
}
}
}
yVals1 = new ArrayList<>();
//yVals2 = new ArrayList<>();
/*for (int i = 0; i < mCount; i++) {
yVals1.add(new BarEntry(getRandom(maxValue / 2, minValue), i, mDateTime[i]));
yVals1.add(new BarEntry((float) income[i], i, mDateTime[i]));
}*/
for (int i = 0; i < mCount; i++) {
Log.d("cece","yVals1"+expressPieces[i]);
yVals1.add(new BarEntry((float) expressPieces[i], i, Statics.Xday));
//yVals2.add(new BarEntry((float) outcome[i], i, mDateTime[i]));//没问题
}
return yVals1;
}
}
| {
"content_hash": "8e43b89ec5b54ad299bf26d2d226c5ab",
"timestamp": "",
"source": "github",
"line_count": 200,
"max_line_length": 161,
"avg_line_length": 36.85,
"alnum_prop": 0.6194029850746269,
"repo_name": "liyanippon/working",
"id": "12409ae4acb31c179808f0a99e3bdf62d6623792",
"size": "7644",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data/work/androidstudio/AndroidStudioProjects/ssr/app/src/main/java/ui/fragement/ExpressPieceDetailsZhuFragment.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "30036"
},
{
"name": "Batchfile",
"bytes": "7951"
},
{
"name": "C",
"bytes": "139882"
},
{
"name": "C#",
"bytes": "933821"
},
{
"name": "C++",
"bytes": "164358"
},
{
"name": "CSS",
"bytes": "1505309"
},
{
"name": "HTML",
"bytes": "15213230"
},
{
"name": "Java",
"bytes": "7271602"
},
{
"name": "JavaScript",
"bytes": "2721649"
},
{
"name": "M4",
"bytes": "193907"
},
{
"name": "PHP",
"bytes": "409031"
},
{
"name": "Pascal",
"bytes": "275042"
},
{
"name": "Perl",
"bytes": "3913080"
},
{
"name": "Perl 6",
"bytes": "20453"
},
{
"name": "PowerShell",
"bytes": "372744"
},
{
"name": "Prolog",
"bytes": "374"
},
{
"name": "Puppet",
"bytes": "1944"
},
{
"name": "Python",
"bytes": "989"
},
{
"name": "Shell",
"bytes": "256369"
},
{
"name": "Tcl",
"bytes": "2138370"
},
{
"name": "Vim script",
"bytes": "590417"
},
{
"name": "Visual Basic",
"bytes": "416"
},
{
"name": "XSLT",
"bytes": "50637"
}
],
"symlink_target": ""
} |
// The SandboxModel is used in the manifest instead of OData V4 model for the following purposes:
// Certain constructor parameters are taken from URL parameters. For the "non-realOData" case, a
// mock server for the back-end requests is set up.
sap.ui.define([
"sap/ui/core/sample/common/SandboxModelHelper",
"sap/ui/model/odata/v4/ODataModel"
], function (SandboxModelHelper, ODataModel) {
"use strict";
var oMockData = {
sFilterBase : "/sap/opu/odata4/IWBEP/TEA/default/IWBEP/TEA_BUSI/0001/",
mFixture : {
"localAnnotations.xml" : {source : "localAnnotations.xml"},
"Equipments?$select=Category,EmployeeId,ID,Name&$expand=EQUIPMENT_2_PRODUCT($select=ID,Name;$expand=PRODUCT_2_CATEGORY($select=CategoryIdentifier,CategoryName),PRODUCT_2_SUPPLIER($select=SUPPLIER_ID,Supplier_Name))&$skip=0&$top=5" : {
source : "equipments.json"
},
"Equipments?$select=Category,EmployeeId,ID,Name&$expand=EQUIPMENT_2_PRODUCT($select=ID,Name;$expand=PRODUCT_2_SUPPLIER($select=SUPPLIER_ID,Supplier_Name))&$skip=0&$top=5" : {
source : "equipments.json"
}
},
aRegExps : [{
regExp : /^GET [\w\/]+\/TEA_BUSI\/0001\/\$metadata\?sap-language=..$/,
response : {source : "metadata.xml"}
}, {
regExp : /^GET [\w\/]+\/tea_busi_product\/0001\/\$metadata\?sap-language=..$/,
response : {source : "metadata_product.xml"}
}, {
regExp : /^GET [\w\/]+\/tea_busi_supplier\/0001\/\$metadata\?sap-language=..$/,
response : {source : "metadata_supplier.xml"}
}],
sSourceBase : "sap/ui/core/sample/odata/v4/ListBindingTemplate/data"
};
return ODataModel.extend("sap.ui.core.sample.odata.v4.ListBindingTemplate.SandboxModel", {
constructor : function (mParameters) {
return SandboxModelHelper.adaptModelParametersAndCreateModel(mParameters, oMockData);
}
});
});
| {
"content_hash": "212cfc4cafac02c8797f470b6f33a6c9",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 238,
"avg_line_length": 45.55,
"alnum_prop": 0.6937431394072447,
"repo_name": "SAP/openui5",
"id": "de46fe94990184cf0aded43b523b8da87afedb99",
"size": "1845",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/sap.ui.core/test/sap/ui/core/demokit/sample/odata/v4/ListBindingTemplate/SandboxModel.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "294216"
},
{
"name": "Gherkin",
"bytes": "17201"
},
{
"name": "HTML",
"bytes": "6443688"
},
{
"name": "Java",
"bytes": "83398"
},
{
"name": "JavaScript",
"bytes": "109546491"
},
{
"name": "Less",
"bytes": "8741757"
},
{
"name": "TypeScript",
"bytes": "20918"
}
],
"symlink_target": ""
} |
package com.sequenceiq.cloudbreak.cmtemplate.configproviders.schemaregistry;
import static com.sequenceiq.cloudbreak.cmtemplate.configproviders.ConfigUtils.config;
import static com.sequenceiq.cloudbreak.cmtemplate.configproviders.kafka.KafkaConfigs.GENERATED_RANGER_SERVICE_NAME;
import static com.sequenceiq.cloudbreak.cmtemplate.configproviders.schemaregistry.SchemaRegistryServiceConfigProvider.RANGER_PLUGIN_SR_SERVICE_NAME;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import com.cloudera.api.swagger.model.ApiClusterTemplateConfig;
import com.sequenceiq.cloudbreak.api.endpoint.v4.common.DatabaseVendor;
import com.sequenceiq.cloudbreak.api.endpoint.v4.database.base.DatabaseType;
import com.sequenceiq.cloudbreak.cmtemplate.CmTemplateProcessor;
import com.sequenceiq.cloudbreak.domain.view.RdsConfigWithoutCluster;
import com.sequenceiq.cloudbreak.template.TemplatePreparationObject;
import com.sequenceiq.cloudbreak.template.views.BlueprintView;
import com.sequenceiq.cloudbreak.template.views.HostgroupView;
import com.sequenceiq.cloudbreak.util.FileReaderUtils;
import com.sequenceiq.common.api.type.InstanceGroupType;
@RunWith(MockitoJUnitRunner.class)
public class SchemaRegistryServiceConfigProviderTest {
private final SchemaRegistryServiceConfigProvider underTest = new SchemaRegistryServiceConfigProvider();
@Test
public void testGetSchemaRegistryServiceConfigs710() {
String inputJson = loadBlueprint("7.1.0");
CmTemplateProcessor cmTemplateProcessor = new CmTemplateProcessor(inputJson);
TemplatePreparationObject preparationObject = getTemplatePreparationObject(cmTemplateProcessor);
List<ApiClusterTemplateConfig> serviceConfigs = underTest.getServiceConfigs(cmTemplateProcessor, preparationObject);
assertThat(serviceConfigs).isEmpty();
}
@Test
public void testGetSchemaRegistryRoleConfigs710() {
String inputJson = loadBlueprint("7.1.0");
CmTemplateProcessor cmTemplateProcessor = new CmTemplateProcessor(inputJson);
TemplatePreparationObject preparationObject = getTemplatePreparationObject(cmTemplateProcessor);
List<ApiClusterTemplateConfig> roleConfigs = underTest.getRoleConfigs(SchemaRegistryRoles.SCHEMA_REGISTRY_SERVER,
preparationObject);
assertThat(roleConfigs).hasSameElementsAs(
List.of(config("schema.registry.storage.connector.connectURI", "jdbc:postgresql://testhost:5432/schema_registry"),
config("schema.registry.storage.connector.user", "schema_registry_server"),
config("schema.registry.storage.connector.password", "schema_registry_server_password")));
}
@Test
public void testGetSchemaRegistryRoleConfigs720() {
String inputJson = loadBlueprint("7.2.0");
CmTemplateProcessor cmTemplateProcessor = new CmTemplateProcessor(inputJson);
TemplatePreparationObject preparationObject = getTemplatePreparationObject(cmTemplateProcessor);
List<ApiClusterTemplateConfig> roleConfigs = underTest.getRoleConfigs(SchemaRegistryRoles.SCHEMA_REGISTRY_SERVER,
preparationObject);
assertThat(roleConfigs).hasSameElementsAs(List.of(
config(RANGER_PLUGIN_SR_SERVICE_NAME, GENERATED_RANGER_SERVICE_NAME)));
}
private TemplatePreparationObject getTemplatePreparationObject(CmTemplateProcessor cmTemplateProcessor) {
HostgroupView master = new HostgroupView("master", 1, InstanceGroupType.GATEWAY, 1);
HostgroupView worker = new HostgroupView("worker", 2, InstanceGroupType.CORE, 3);
BlueprintView blueprintView = new BlueprintView(null, null, null, cmTemplateProcessor);
RdsConfigWithoutCluster rdsConfig = mock(RdsConfigWithoutCluster.class);
when(rdsConfig.getType()).thenReturn(DatabaseType.REGISTRY.toString());
when(rdsConfig.getDatabaseEngine()).thenReturn(DatabaseVendor.POSTGRES);
when(rdsConfig.getConnectionURL()).thenReturn("jdbc:postgresql://testhost:5432/schema_registry");
when(rdsConfig.getConnectionUserName()).thenReturn("schema_registry_server");
when(rdsConfig.getConnectionPassword()).thenReturn("schema_registry_server_password");
return TemplatePreparationObject.Builder.builder()
.withBlueprintView(blueprintView)
.withHostgroupViews(Set.of(master, worker))
.withRdsConfigs(Set.of(rdsConfig))
.build();
}
private String loadBlueprint(String cdhVersion) {
return FileReaderUtils.readFileFromClasspathQuietly("input/cdp-streaming.bp").replace("__CDH_VERSION__", cdhVersion);
}
}
| {
"content_hash": "8382a55c338358de5628ad95fdb38048",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 148,
"avg_line_length": 52.351063829787236,
"alnum_prop": 0.7713879292826661,
"repo_name": "hortonworks/cloudbreak",
"id": "ac04f9cb4fbd307babae5f80f52910080b96e7c1",
"size": "4921",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "template-manager-cmtemplate/src/test/java/com/sequenceiq/cloudbreak/cmtemplate/configproviders/schemaregistry/SchemaRegistryServiceConfigProviderTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7535"
},
{
"name": "Dockerfile",
"bytes": "9586"
},
{
"name": "Fluent",
"bytes": "10"
},
{
"name": "FreeMarker",
"bytes": "395982"
},
{
"name": "Groovy",
"bytes": "523"
},
{
"name": "HTML",
"bytes": "9917"
},
{
"name": "Java",
"bytes": "55250904"
},
{
"name": "JavaScript",
"bytes": "47923"
},
{
"name": "Jinja",
"bytes": "190660"
},
{
"name": "Makefile",
"bytes": "8537"
},
{
"name": "PLpgSQL",
"bytes": "1830"
},
{
"name": "Perl",
"bytes": "17726"
},
{
"name": "Python",
"bytes": "29898"
},
{
"name": "SaltStack",
"bytes": "222692"
},
{
"name": "Scala",
"bytes": "11168"
},
{
"name": "Shell",
"bytes": "416225"
}
],
"symlink_target": ""
} |
package alluxio.worker.netty;
import alluxio.RpcUtils;
import alluxio.StorageTierAssoc;
import alluxio.WorkerStorageTierAssoc;
import alluxio.exception.BlockDoesNotExistException;
import alluxio.exception.ExceptionMessage;
import alluxio.exception.InvalidWorkerStateException;
import alluxio.exception.status.AlluxioStatusException;
import alluxio.network.protocol.RPCProtoMessage;
import alluxio.proto.dataserver.Protocol;
import alluxio.util.IdUtils;
import alluxio.util.proto.ProtoMessage;
import alluxio.worker.block.BlockLockManager;
import alluxio.worker.block.BlockWorker;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import javax.annotation.concurrent.NotThreadSafe;
/**
* Netty handler that handles short circuit read requests.
*/
@NotThreadSafe
class ShortCircuitBlockReadHandler extends ChannelInboundHandlerAdapter {
private static final Logger LOG =
LoggerFactory.getLogger(ShortCircuitBlockReadHandler.class);
/** Executor service for execute the RPCs. */
private final ExecutorService mRpcExecutor;
private final StorageTierAssoc mStorageTierAssoc = new WorkerStorageTierAssoc();
/** The block worker. */
private final BlockWorker mWorker;
/** The lock Id of the block being read. */
private long mLockId;
private long mSessionId;
/**
* Creates an instance of {@link ShortCircuitBlockReadHandler}.
*
* @param service the executor to execute the RPCs
* @param blockWorker the block worker
*/
ShortCircuitBlockReadHandler(ExecutorService service, BlockWorker blockWorker) {
mRpcExecutor = service;
mWorker = blockWorker;
mLockId = BlockLockManager.INVALID_LOCK_ID;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (!(msg instanceof RPCProtoMessage)) {
ctx.fireChannelRead(msg);
return;
}
ProtoMessage message = ((RPCProtoMessage) msg).getMessage();
if (message.isLocalBlockOpenRequest()) {
handleBlockOpenRequest(ctx, message.asLocalBlockOpenRequest());
} else if (message.isLocalBlockCloseRequest()) {
handleBlockCloseRequest(ctx, message.asLocalBlockCloseRequest());
} else {
ctx.fireChannelRead(msg);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {
// The RPC handlers do not throw exceptions. All the exception seen here is either
// network exception or some runtime exception (e.g. NullPointerException).
LOG.error("Failed to handle RPCs.", throwable);
ctx.close();
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) {
if (mLockId != BlockLockManager.INVALID_LOCK_ID) {
try {
mWorker.unlockBlock(mLockId);
} catch (BlockDoesNotExistException e) {
LOG.warn("Failed to unlock lock {} with error {}.", mLockId, e.getMessage());
}
mWorker.cleanupSession(mSessionId);
}
ctx.fireChannelUnregistered();
}
/**
* Handles {@link Protocol.LocalBlockOpenRequest}. Since the open can be expensive, the work is
* delegated to a threadpool. No exceptions should be thrown.
*
* @param ctx the channel handler context
* @param request the local block open request
*/
private void handleBlockOpenRequest(final ChannelHandlerContext ctx,
final Protocol.LocalBlockOpenRequest request) {
mRpcExecutor.submit(() ->
RpcUtils.nettyRPCAndLog(LOG, new RpcUtils.NettyRpcCallable<Void>() {
@Override
public Void call() throws Exception {
if (mLockId == BlockLockManager.INVALID_LOCK_ID) {
mSessionId = IdUtils.createSessionId();
// TODO(calvin): Update the locking logic so this can be done better
if (request.getPromote()) {
try {
mWorker
.moveBlock(mSessionId, request.getBlockId(), mStorageTierAssoc.getAlias(0));
} catch (BlockDoesNotExistException e) {
LOG.debug("Block {} to promote does not exist in Alluxio: {}",
request.getBlockId(), e.getMessage());
} catch (Exception e) {
LOG.warn("Failed to promote block {}: {}", request.getBlockId(), e.getMessage());
}
}
mLockId = mWorker.lockBlock(mSessionId, request.getBlockId());
mWorker.accessBlock(mSessionId, request.getBlockId());
} else {
LOG.warn("Lock block {} without releasing previous block lock {}.",
request.getBlockId(), mLockId);
throw new InvalidWorkerStateException(
ExceptionMessage.LOCK_NOT_RELEASED.getMessage(mLockId));
}
Protocol.LocalBlockOpenResponse response = Protocol.LocalBlockOpenResponse.newBuilder()
.setPath(mWorker.readBlock(mSessionId, request.getBlockId(), mLockId)).build();
ctx.writeAndFlush(new RPCProtoMessage(new ProtoMessage(response)));
return null;
}
@Override
public void exceptionCaught(Throwable e) {
if (mLockId != BlockLockManager.INVALID_LOCK_ID) {
try {
mWorker.unlockBlock(mLockId);
} catch (BlockDoesNotExistException ee) {
LOG.error("Failed to unlock block {}.", request.getBlockId(), e);
}
mLockId = BlockLockManager.INVALID_LOCK_ID;
}
ctx.writeAndFlush(
RPCProtoMessage.createResponse(AlluxioStatusException.fromThrowable(e)));
}
}, "OpenBlock", "Session=%d, Request=%s", mSessionId, request));
}
/**
* Handles {@link Protocol.LocalBlockCloseRequest}. No exceptions should be thrown.
*
* @param ctx the channel handler context
* @param request the local block close request
*/
private void handleBlockCloseRequest(final ChannelHandlerContext ctx,
final Protocol.LocalBlockCloseRequest request) {
mRpcExecutor.submit(() ->
RpcUtils.nettyRPCAndLog(LOG, new RpcUtils.NettyRpcCallable<Void>() {
@Override
public Void call() throws Exception {
if (mLockId != BlockLockManager.INVALID_LOCK_ID) {
mWorker.unlockBlock(mLockId);
mLockId = BlockLockManager.INVALID_LOCK_ID;
} else {
LOG.warn("Close a closed block {}.", request.getBlockId());
}
ctx.writeAndFlush(RPCProtoMessage.createOkResponse(null));
return null;
}
@Override
public void exceptionCaught(Throwable e) {
ctx.writeAndFlush(
RPCProtoMessage.createResponse(AlluxioStatusException.fromThrowable(e)));
mLockId = BlockLockManager.INVALID_LOCK_ID;
}
}, "CloseBlock", "Session=%d, Request=%s", mSessionId, request));
}
}
| {
"content_hash": "ad4399ec17fe2b7d2febabbb154f9b55",
"timestamp": "",
"source": "github",
"line_count": 182,
"max_line_length": 99,
"avg_line_length": 38.675824175824175,
"alnum_prop": 0.6669981531467538,
"repo_name": "Reidddddd/alluxio",
"id": "5b300e7e3250bcd92a8d8705d1f2bb6f0d9136ca",
"size": "7551",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "core/server/worker/src/main/java/alluxio/worker/netty/ShortCircuitBlockReadHandler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2038"
},
{
"name": "Go",
"bytes": "23764"
},
{
"name": "HTML",
"bytes": "599"
},
{
"name": "Java",
"bytes": "8797460"
},
{
"name": "JavaScript",
"bytes": "1079"
},
{
"name": "Python",
"bytes": "11471"
},
{
"name": "Roff",
"bytes": "5797"
},
{
"name": "Ruby",
"bytes": "22472"
},
{
"name": "Shell",
"bytes": "147542"
},
{
"name": "Thrift",
"bytes": "52781"
}
],
"symlink_target": ""
} |
<?php class AboutMeWidget extends WP_Widget
{
function AboutMeWidget(){
$widget_ops = array( 'description' => 'Displays About Me Information' );
$control_ops = array( 'width' => 400, 'height' => 300 );
parent::WP_Widget( false, $name='ET About Me Widget', $widget_ops, $control_ops );
}
/* Displays the Widget in the front-end */
function widget( $args, $instance ){
extract($args);
$title = apply_filters( 'widget_title', empty( $instance['title'] ) ? 'About Me' : esc_html( $instance['title'] ) );
$imagePath = empty( $instance['imagePath'] ) ? '' : esc_url( $instance['imagePath'] );
$aboutText = empty( $instance['aboutText'] ) ? '' : $instance['aboutText'];
echo $before_widget;
if ( $title )
echo $before_title . $title . $after_title; ?>
<div class="clearfix">
<img src="<?php echo et_new_thumb_resize( et_multisite_thumbnail($imagePath), 74, 74, '', true ); ?>" id="about-image" alt="" />
<?php echo( $aboutText )?>
</div> <!-- end about me section -->
<?php
echo $after_widget;
}
/*Saves the settings. */
function update( $new_instance, $old_instance ){
$instance = $old_instance;
$instance['title'] = strip_tags( $new_instance['title'] );
$instance['imagePath'] = esc_url( $new_instance['imagePath'] );
$instance['aboutText'] = current_user_can('unfiltered_html') ? $new_instance['aboutText'] : stripslashes( wp_filter_post_kses( addslashes($new_instance['aboutText']) ) );
return $instance;
}
/*Creates the form for the widget in the back-end. */
function form( $instance ){
//Defaults
$instance = wp_parse_args( (array) $instance, array( 'title'=>'About Me', 'imagePath'=>'', 'aboutText'=>'' ) );
$title = esc_attr( $instance['title'] );
$imagePath = esc_url( $instance['imagePath'] );
$aboutText = esc_textarea( $instance['aboutText'] );
# Title
echo '<p><label for="' . $this->get_field_id('title') . '">' . 'Title:' . '</label><input class="widefat" id="' . $this->get_field_id('title') . '" name="' . $this->get_field_name('title') . '" type="text" value="' . $title . '" /></p>';
# Image
echo '<p><label for="' . $this->get_field_id('imagePath') . '">' . 'Image:' . '</label><textarea cols="20" rows="2" class="widefat" id="' . $this->get_field_id('imagePath') . '" name="' . $this->get_field_name('imagePath') . '" >'. $imagePath .'</textarea></p>';
# About Text
echo '<p><label for="' . $this->get_field_id('aboutText') . '">' . 'Text:' . '</label><textarea cols="20" rows="5" class="widefat" id="' . $this->get_field_id('aboutText') . '" name="' . $this->get_field_name('aboutText') . '" >'. $aboutText .'</textarea></p>';
}
}// end AboutMeWidget class
function AboutMeWidgetInit() {
register_widget('AboutMeWidget');
}
add_action('widgets_init', 'AboutMeWidgetInit'); ?> | {
"content_hash": "b8a9e389d5dfebc64d2770fb695126de",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 264,
"avg_line_length": 45.81967213114754,
"alnum_prop": 0.6114490161001789,
"repo_name": "peter-watters/WebPortfolio",
"id": "9d8139a195153a04ee95db62972d2b8c08153632",
"size": "2795",
"binary": false,
"copies": "23",
"ref": "refs/heads/master",
"path": "fitnessperformacesystems/wp-content/themes/SimplePress/includes/widgets/widget-about.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "4489"
},
{
"name": "ActionScript",
"bytes": "529910"
},
{
"name": "CSS",
"bytes": "5681789"
},
{
"name": "CoffeeScript",
"bytes": "48851"
},
{
"name": "Java",
"bytes": "24402"
},
{
"name": "JavaScript",
"bytes": "15741063"
},
{
"name": "PHP",
"bytes": "36775095"
},
{
"name": "Shell",
"bytes": "53068"
},
{
"name": "XSLT",
"bytes": "5803"
}
],
"symlink_target": ""
} |
{% extends "body.html" %}
{% block content %}
<div class="row">
<div class="col-md-8">
<div class="jumbotron">
<h1>{{ _('Jedenásty Bratislavský Python Meetup') }}</h1>
<h2><span class="glyphicon glyphicon-time" aria-hidden="true"></span> {{ _('07. jún 2016 – 18:30') }}</h2>
<h2><span class="glyphicon glyphicon-map-marker" aria-hidden="true"></span> <a href="https://progressbar.sk/calendar/" title="{{ _('Kalendár ProgressBaru') }}">ProgressBar Hackerspace,<br>Michalská 3, Bratislava</a></h2>
</div>
<p class="text-justify">{{ _('Na júnovom meetupe nám Juraj Bezručka predstaví "python pre neprogramatorov".') }}</p>
<p class="text-justify">{{ _('Juraj nám predstaví funkcie ako map, filter či reduce aj s príkladmi, ďalej tiež list/dict comprehension, prípadne ďalšie užitočné funkcie (vysvetlí ternárny operátor a pod.)') }}</p>
<p class="text-justify">{{ _('Tešíme sa na Vás na stretnutí.') }}</p>
<p>{{ _('Jazyk') }}: {{ _('slovenčina') }}</p>
{# <p> <img class="logo-scale" src="{{ url_for('static', filename='images/logo/github-mark-small.png') }}"/> Github: <a href="https://github.com/pyconsk/meetup/tree/master/Bratislava/201602" target="_blank">https://github.com/pyconsk/meetup/tree/master/Bratislava/201602</a></p> #}
<p>{{ _('Kontakt') }}: <a href="mailto:[email protected]?subject=Jedenásty%20Bratislavský%20Python%20Meetup" title="Bratislava Python Meetup Email">[email protected]</a></p>
<p>{{ _('Organizátor') }}: <a href="/{{ lang_code }}/spy.html" title="">SPy o.z.</a></p>
<br>
<br>
<div id="disqus_thread"></div>
<script>
var disqus_config = function () {
this.page.url = 'https://pycon.sk{{ request.path }}';
this.page.identifier = '11';
};
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = '//pythonmeetup.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a></noscript>
</div>
<div class="col-md-4">
{% include 'right_nav.html' %}
</div>
</div>
{% endblock %}
| {
"content_hash": "da53c9b42762dafe6997d7b1c5fe71ac",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 288,
"avg_line_length": 47.916666666666664,
"alnum_prop": 0.621304347826087,
"repo_name": "pyconsk/pycon.sk",
"id": "e31f2664c27521a47723579859124c509b4c6f90",
"size": "2334",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/templates/ba-11-meetup.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PostScript",
"bytes": "2016167"
},
{
"name": "Python",
"bytes": "7476"
}
],
"symlink_target": ""
} |
package mvc
import (
"strings"
"unicode"
)
func findCtrlWords(ctrlName string) (w []string) {
end := len(ctrlName)
start := -1
for i, n := 0, end; i < n; i++ {
c := rune(ctrlName[i])
if unicode.IsUpper(c) {
// it doesn't count the last uppercase
if start != -1 {
end = i
w = append(w, strings.ToLower(ctrlName[start:end]))
}
start = i
continue
}
end = i + 1
}
// We can't omit the last name, we have to take it.
// because of controller names like
// "UserProfile", we need to return "user", "profile"
// if "UserController", we need to return "user"
// if "User", we need to return "user".
last := ctrlName[start:end]
if last == ctrlSuffix {
return
}
w = append(w, strings.ToLower(last))
return
}
| {
"content_hash": "534dad82cb97f7438b2bfd6e3176e161",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 55,
"avg_line_length": 19.81578947368421,
"alnum_prop": 0.6108897742363878,
"repo_name": "grvcoelho/webhulk",
"id": "686da607b0d8bd7ff16a8965db668b2e09789b68",
"size": "753",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/github.com/kataras/iris/mvc/strutil.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "14437"
}
],
"symlink_target": ""
} |
@import url('https://fonts.googleapis.com/css2?family=Raleway:wght@300&display=swap');
:root {
--border-color: #969696;
}
body {
padding: 10px;
}
h1 {margin: 10px 0}
.bb {
height: 160px;
border-right: dotted 1px var(--border-color);
border-bottom: dotted 1px var(--border-color);
}
.title {
font-family: 'Raleway', sans-serif;
font-size: 15px;
margin: 10px 0 0 10px;
text-transform: capitalize;
position: absolute;
color: var(--border-color);
}
#wrapper {
border-top: dotted 1px var(--border-color);
border-left: dotted 1px var(--border-color);
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
} | {
"content_hash": "45ce398405394879688a9df0b1b6364e",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 86,
"avg_line_length": 19.484848484848484,
"alnum_prop": 0.6905132192846034,
"repo_name": "naver/billboard.js",
"id": "9aac5e545ed549f7de9d9de6bf8efbc50a357611",
"size": "643",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "demo/types/types.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1069"
},
{
"name": "HTML",
"bytes": "432"
},
{
"name": "JavaScript",
"bytes": "22426"
},
{
"name": "SCSS",
"bytes": "23498"
},
{
"name": "Shell",
"bytes": "2920"
},
{
"name": "TypeScript",
"bytes": "1461190"
}
],
"symlink_target": ""
} |
package com.mattunderscore.trees.binary.search;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Comparator;
import org.junit.Test;
import com.mattunderscore.trees.Trees;
import com.mattunderscore.trees.binary.BinaryTreeNode;
import com.mattunderscore.trees.impl.TreesImpl;
import com.mattunderscore.trees.sorted.SortingTreeBuilder;
import com.mattunderscore.trees.utilities.ComparableComparator;
/**
* Test for unbalanced binary search tree.
* @author Matt Champion on 06/09/14.
*/
public final class BinarySearchTreeTest {
private final Trees trees = Trees.get();
@Test
public void addingAndOrdering() {
final Comparator<String> comparator = ComparableComparator.get();
final BinarySearchTree<String> tree = new BinarySearchTree<>(comparator);
assertTrue(tree.isEmpty());
tree.addElement("b");
assertFalse(tree.isEmpty());
tree.addElement("a")
.addElement("c")
.addElement("f")
.addElement("e")
.addElement("d");
assertEquals("b", tree.getRoot().getElement());
assertEquals("a", tree.getRoot().getLeft().getElement());
assertEquals("c", tree.getRoot().getRight().getElement());
assertEquals("f", tree.getRoot().getRight().getRight().getElement());
assertEquals("e", tree.getRoot().getRight().getRight().getLeft().getElement());
assertEquals("d", tree.getRoot().getRight().getRight().getLeft().getLeft().getElement());
}
@Test
public void construction() {
final SortingTreeBuilder<String, BinaryTreeNode<String>> builder = trees.treeBuilders().sortingTreeBuilder();
final BinarySearchTree<String> tree = builder
.addElement("b")
.addElement("a")
.addElement("c")
.addElement("f")
.addElement("e")
.addElement("d")
.build(BinarySearchTree.<String>typeKey());
assertEquals("b", tree.getRoot().getElement());
assertEquals("a", tree.getRoot().getLeft().getElement());
assertEquals("c", tree.getRoot().getRight().getElement());
assertEquals("f", tree.getRoot().getRight().getRight().getElement());
assertEquals("e", tree.getRoot().getRight().getRight().getLeft().getElement());
assertEquals("d", tree.getRoot().getRight().getRight().getLeft().getLeft().getElement());
}
@Test
public void comparableComparator() {
final SortingTreeBuilder<String, BinaryTreeNode<String>> builder = trees.treeBuilders().sortingTreeBuilder();
final BinarySearchTree<String> tree = builder
.addElement("b")
.addElement("a")
.build(BinarySearchTree.<String>typeKey());
assertTrue(tree.getComparator() instanceof ComparableComparator);
}
@Test
public void comparator() {
final Comparator<String> lyingComparator = (s0, s1) -> 0;
final BinarySearchTree<String> tree = trees.treeBuilders()
.<String, BinaryTreeNode<String>>sortingTreeBuilder(lyingComparator)
.addElement("b")
.addElement("a")
.build(BinarySearchTree.<String>typeKey());
assertEquals(lyingComparator, tree.getComparator());
}
@Test
public void absentNodes() {
final Comparator<String> comparator = ComparableComparator.get();
final BinarySearchTree<String> tree = new BinarySearchTree<>(comparator);
assertTrue(tree.isEmpty());
tree.addElement("b");
final BinaryTreeNode<String> root = tree.getRoot();
assertNull(root.getLeft());
assertNull(root.getRight());
}
}
| {
"content_hash": "39697f121626eb4c19d49f553caefaa5",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 117,
"avg_line_length": 36.970873786407765,
"alnum_prop": 0.6525735294117647,
"repo_name": "mattunderscorechampion/tree-root",
"id": "2c633bbad317200470f399e908247406354ea86d",
"size": "5303",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "trees-binary-search/src/test/java/com/mattunderscore/trees/binary/search/BinarySearchTreeTest.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "1159652"
}
],
"symlink_target": ""
} |
//using System;
//using System.Collections.Generic;
//using System.Linq;
//namespace LinFx.Extensions.Timing
//{
// [Service]
// public class TZConvertTimezoneProvider : ITimezoneProvider
// {
// public virtual List<NameValue> GetWindowsTimezones()
// {
// return TZConvert.KnownWindowsTimeZoneIds.OrderBy(x => x).Select(x => new NameValue(x, x)).ToList();
// }
// public virtual List<NameValue> GetIanaTimezones()
// {
// return TZConvert.KnownIanaTimeZoneNames.OrderBy(x => x).Select(x => new NameValue(x, x)).ToList();
// }
// public virtual string WindowsToIana(string windowsTimeZoneId)
// {
// return TZConvert.WindowsToIana(windowsTimeZoneId);
// }
// public virtual string IanaToWindows(string ianaTimeZoneName)
// {
// return TZConvert.IanaToWindows(ianaTimeZoneName);
// }
// public virtual TimeZoneInfo GetTimeZoneInfo(string windowsOrIanaTimeZoneId)
// {
// return TZConvert.GetTimeZoneInfo(windowsOrIanaTimeZoneId);
// }
// }
//}
| {
"content_hash": "1ad709dd062556a6b033b38f917be3de",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 113,
"avg_line_length": 32.02857142857143,
"alnum_prop": 0.623550401427297,
"repo_name": "linfx/LinFx",
"id": "822aa8408cdd6ea620d5f4e51642db6a5710377a",
"size": "1123",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/LinFx/Extensions/Timing/TZConvertTimezoneProvider.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1454562"
},
{
"name": "HTML",
"bytes": "7752"
},
{
"name": "PowerShell",
"bytes": "2008"
}
],
"symlink_target": ""
} |
require_relative 'common'
describe 'Sanitize::Transformers::CleanComment' do
make_my_diffs_pretty!
parallelize_me!
describe 'when :allow_comments is false' do
before do
@s = Sanitize.new(:allow_comments => false, :elements => ['div'])
end
it 'should remove comments' do
_(@s.fragment('foo <!-- comment --> bar')).must_equal 'foo bar'
_(@s.fragment('foo <!-- ')).must_equal 'foo '
_(@s.fragment('foo <!-- - -> bar')).must_equal 'foo '
_(@s.fragment("foo <!--\n\n\n\n-->bar")).must_equal 'foo bar'
_(@s.fragment("foo <!-- <!-- <!-- --> --> -->bar")).must_equal 'foo --> -->bar'
_(@s.fragment("foo <div <!-- comment -->>bar</div>")).must_equal 'foo <div>>bar</div>'
# Special case: the comment markup is inside a <script>, which makes it
# text content and not an actual HTML comment.
_(@s.fragment("<script><!-- comment --></script>")).must_equal ''
_(Sanitize.fragment("<script><!-- comment --></script>", :allow_comments => false, :elements => ['script']))
.must_equal '<script><!-- comment --></script>'
end
end
describe 'when :allow_comments is true' do
before do
@s = Sanitize.new(:allow_comments => true, :elements => ['div'])
end
it 'should allow comments' do
_(@s.fragment('foo <!-- comment --> bar')).must_equal 'foo <!-- comment --> bar'
_(@s.fragment('foo <!-- ')).must_equal 'foo <!-- -->'
_(@s.fragment('foo <!-- - -> bar')).must_equal 'foo <!-- - -> bar-->'
_(@s.fragment("foo <!--\n\n\n\n-->bar")).must_equal "foo <!--\n\n\n\n-->bar"
_(@s.fragment("foo <!-- <!-- <!-- --> --> -->bar")).must_equal 'foo <!-- <!-- <!-- --> --> -->bar'
_(@s.fragment("foo <div <!-- comment -->>bar</div>")).must_equal 'foo <div>>bar</div>'
_(Sanitize.fragment("<script><!-- comment --></script>", :allow_comments => true, :elements => ['script']))
.must_equal '<script><!-- comment --></script>'
end
end
end
| {
"content_hash": "bead9c50705c9f9c26a7ddaed168c363",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 114,
"avg_line_length": 43.54347826086956,
"alnum_prop": 0.5336994508237644,
"repo_name": "rgrove/sanitize",
"id": "a02c76c46b2f0a2f70aa90220eca6c7a96757ada",
"size": "2021",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "test/test_clean_comment.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "7318793"
},
{
"name": "Ruby",
"bytes": "135559"
}
],
"symlink_target": ""
} |
require 'test_helper'
class RemoteMercadoPagoTest < Test::Unit::TestCase
def setup
exp_year = Time.now.year + 1
@gateway = MercadoPagoGateway.new(fixtures(:mercado_pago))
@argentina_gateway = MercadoPagoGateway.new(fixtures(:mercado_pago_argentina))
@colombian_gateway = MercadoPagoGateway.new(fixtures(:mercado_pago_colombia))
@amount = 500
@credit_card = credit_card('5031433215406351')
@colombian_card = credit_card('4013540682746260')
@elo_credit_card = credit_card('5067268650517446',
month: 10,
year: exp_year,
first_name: 'John',
last_name: 'Smith',
verification_value: '737')
@cabal_credit_card = credit_card('6035227716427021',
month: 10,
year: exp_year,
first_name: 'John',
last_name: 'Smith',
verification_value: '737')
@naranja_credit_card = credit_card('5895627823453005',
month: 10,
year: exp_year,
first_name: 'John',
last_name: 'Smith',
verification_value: '123')
@declined_card = credit_card('5031433215406351',
first_name: 'OTHE')
@options = {
billing_address: address,
shipping_address: address,
email: '[email protected]',
description: 'Store Purchase'
}
@processing_options = {
binary_mode: false,
processing_mode: 'gateway',
merchant_account_id: fixtures(:mercado_pago)[:merchant_account_id],
fraud_scoring: true,
fraud_manual_review: true,
payment_method_option_id: '123abc'
}
end
def test_successful_purchase
response = @gateway.purchase(@amount, @credit_card, @options)
assert_success response
assert_equal 'accredited', response.message
end
def test_successful_purchase_with_elo
response = @gateway.purchase(@amount, @elo_credit_card, @options)
assert_success response
assert_equal 'accredited', response.message
end
def test_successful_purchase_with_cabal
response = @argentina_gateway.purchase(@amount, @cabal_credit_card, @options)
assert_success response
assert_equal 'accredited', response.message
end
def test_successful_purchase_with_naranja
response = @argentina_gateway.purchase(@amount, @naranja_credit_card, @options)
assert_success response
assert_equal 'accredited', response.message
end
def test_successful_purchase_with_binary_false
@options.update(binary_mode: false)
response = @gateway.authorize(@amount, @credit_card, @options)
assert_success response
assert_equal 'pending_capture', response.message
end
# Requires setup on merchant account
def test_successful_purchase_with_processing_mode_gateway
response = @gateway.purchase(@amount, @credit_card, @options.merge(@processing_options))
assert_success response
assert_equal 'accredited', response.message
end
def test_successful_purchase_with_american_express
amex_card = credit_card('375365153556885', brand: 'american_express', verification_value: '1234')
response = @gateway.purchase(@amount, amex_card, @options)
assert_success response
assert_equal 'accredited', response.message
end
def test_successful_purchase_with_taxes_and_net_amount
# Minimum transaction amount is 0.30 EUR or ~1112 $COL on 1/27/20.
# This value must exceed that
amount = 10000_00
# These values need to be represented as dollars, so divide them by 100
tax_amount = amount * 0.19
@options[:net_amount] = (amount - tax_amount) / 100
@options[:taxes] = [{ value: tax_amount / 100, type: 'IVA' }]
response = @colombian_gateway.purchase(amount, @colombian_card, @options)
assert_success response
assert_equal 'accredited', response.message
end
def test_successful_purchase_with_notification_url
response = @gateway.purchase(@amount, @credit_card, @options.merge(notification_url: 'https://www.spreedly.com/'))
assert_success response
assert_equal 'https://www.spreedly.com/', response.params['notification_url']
end
def test_failed_purchase
response = @gateway.purchase(@amount, @declined_card, @options)
assert_failure response
assert_equal 'rejected', response.error_code
assert_equal 'cc_rejected_other_reason', response.message
end
def test_successful_authorize_and_capture
auth = @gateway.authorize(@amount, @credit_card, @options)
assert_success auth
assert_equal 'pending_capture', auth.message
assert capture = @gateway.capture(@amount, auth.authorization)
assert_success capture
assert_equal 'accredited', capture.message
end
def test_successful_authorize_and_capture_with_elo
auth = @gateway.authorize(@amount, @elo_credit_card, @options)
assert_success auth
assert_equal 'pending_capture', auth.message
assert capture = @gateway.capture(@amount, auth.authorization)
assert_success capture
assert_equal 'accredited', capture.message
end
def test_successful_authorize_and_capture_with_cabal
auth = @argentina_gateway.authorize(@amount, @cabal_credit_card, @options)
assert_success auth
assert_equal 'pending_capture', auth.message
assert capture = @argentina_gateway.capture(@amount, auth.authorization)
assert_success capture
assert_equal 'accredited', capture.message
end
def test_successful_authorize_and_capture_with_naranja
auth = @argentina_gateway.authorize(@amount, @naranja_credit_card, @options)
assert_success auth
assert_equal 'pending_capture', auth.message
assert capture = @argentina_gateway.capture(@amount, auth.authorization)
assert_success capture
assert_equal 'accredited', capture.message
end
def test_successful_authorize_with_capture_option
auth = @gateway.authorize(@amount, @credit_card, @options.merge(capture: true))
assert_success auth
assert_equal 'accredited', auth.message
end
def test_failed_authorize
response = @gateway.authorize(@amount, @declined_card, @options)
assert_failure response
assert_equal 'cc_rejected_other_reason', response.message
end
def test_partial_capture
auth = @gateway.authorize(@amount + 1, @credit_card, @options)
assert_success auth
assert capture = @gateway.capture(@amount, auth.authorization)
assert_success capture
assert_equal 'accredited', capture.message
end
def test_failed_capture
response = @gateway.capture(@amount, '')
assert_failure response
assert_equal 'json_parse_error', response.message
end
def test_successful_refund
purchase = @gateway.purchase(@amount, @credit_card, @options)
assert_success purchase
assert refund = @gateway.refund(@amount, purchase.authorization)
assert_success refund
assert_equal nil, refund.message
end
def test_successful_refund_with_elo
purchase = @gateway.purchase(@amount, @elo_credit_card, @options)
assert_success purchase
assert refund = @gateway.refund(@amount, purchase.authorization)
assert_success refund
assert_equal nil, refund.message
end
def test_successful_refund_with_cabal
purchase = @argentina_gateway.purchase(@amount, @cabal_credit_card, @options)
assert_success purchase
assert refund = @argentina_gateway.refund(@amount, purchase.authorization)
assert_success refund
assert_equal nil, refund.message
end
def test_successful_refund_with_naranja
purchase = @argentina_gateway.purchase(@amount, @naranja_credit_card, @options)
assert_success purchase
assert refund = @argentina_gateway.refund(@amount, purchase.authorization)
assert_success refund
assert_equal nil, refund.message
end
def test_partial_refund
purchase = @gateway.purchase(@amount, @credit_card, @options)
assert_success purchase
assert refund = @gateway.refund(@amount - 1, purchase.authorization)
assert_success refund
end
def test_failed_refund
response = @gateway.refund(@amount, '')
assert_failure response
assert_equal 'Not Found', response.message
end
def test_successful_void
auth = @gateway.authorize(@amount, @credit_card, @options)
assert_success auth
assert void = @gateway.void(auth.authorization)
assert_success void
assert_equal 'by_collector', void.message
end
def test_successful_void_with_elo
auth = @gateway.authorize(@amount, @elo_credit_card, @options)
assert_success auth
assert void = @gateway.void(auth.authorization)
assert_success void
assert_equal 'by_collector', void.message
end
def test_successful_void_with_cabal
auth = @argentina_gateway.authorize(@amount, @cabal_credit_card, @options)
assert_success auth
assert void = @argentina_gateway.void(auth.authorization)
assert_success void
assert_equal 'by_collector', void.message
end
def test_successful_void_with_naranja
auth = @argentina_gateway.authorize(@amount, @naranja_credit_card, @options)
assert_success auth
assert void = @argentina_gateway.void(auth.authorization)
assert_success void
assert_equal 'by_collector', void.message
end
def test_failed_void
response = @gateway.void('')
assert_failure response
assert_equal 'json_parse_error', response.message
end
def test_successful_verify
response = @gateway.verify(@credit_card, @options)
assert_success response
assert_match %r{pending_capture}, response.message
end
def test_failed_verify
response = @gateway.verify(@declined_card, @options)
assert_failure response
assert_match %r{cc_rejected_other_reason}, response.message
end
def test_invalid_login
gateway = MercadoPagoGateway.new(access_token: '')
response = gateway.purchase(@amount, @credit_card, @options)
assert_failure response
assert_match %r{Invalid access parameters}, response.message
end
def test_transcript_scrubbing
transcript = capture_transcript(@gateway) do
@gateway.purchase(@amount, @credit_card, @options)
end
transcript = @gateway.scrub(transcript)
assert_scrubbed(@credit_card.number, transcript)
assert_scrubbed(@credit_card.verification_value, transcript)
assert_scrubbed(@gateway.options[:access_token], transcript)
end
end
| {
"content_hash": "f9ace2018ac222d06f97cfe92770f90d",
"timestamp": "",
"source": "github",
"line_count": 312,
"max_line_length": 118,
"avg_line_length": 32.705128205128204,
"alnum_prop": 0.7133477067816543,
"repo_name": "Shopify/active_merchant",
"id": "33e6e9b7034d9d8f60a0ab3756afa8d4c94cb383",
"size": "10204",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/remote/gateways/remote_mercado_pago_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "5474224"
}
],
"symlink_target": ""
} |
/**
*/
package subkdm.kdmObjects.impl;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import subkdm.kdmObjects.CodeUnit;
import subkdm.kdmObjects.KdmObjectsPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Code Unit</b></em>'.
* <!-- end-user-doc -->
* <p>
* </p>
*
* @generated
*/
public class CodeUnitImpl extends MinimalEObjectImpl.Container implements CodeUnit {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected CodeUnitImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return KdmObjectsPackage.Literals.CODE_UNIT;
}
} //CodeUnitImpl
| {
"content_hash": "947ff94544d2dacbaf094343dd726564",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 84,
"avg_line_length": 19.926829268292682,
"alnum_prop": 0.6119951040391677,
"repo_name": "lfmendivelso10/AppModernization",
"id": "84b09aa3f34d134b4c654d5c2e2a02746ef0e4b4",
"size": "817",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "source/i2/miso4301_201520/src/subkdm/kdmObjects/impl/CodeUnitImpl.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1018"
},
{
"name": "Java",
"bytes": "4283110"
}
],
"symlink_target": ""
} |
"""
This subpackage provides classes to communicate with other applications via the
`Simple Application Messaging Protocal (SAMP)
<http://www.ivoa.net/documents/SAMP/>`_.
Before integration into Astropy it was known as
`SAMPy <https://pypi.python.org/pypi/sampy/>`_, and was developed by Luigi Paioro
(INAF - Istituto Nazionale di Astrofisica).
"""
from .constants import *
from .errors import *
from .utils import *
from .hub import *
from .client import *
from .integrated_client import *
from .hub_proxy import *
from astropy import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.samp`.
"""
use_internet = _config.ConfigItem(
True,
"Whether to allow `astropy.samp` to use "
"the internet, if available.",
aliases=['astropy.samp.utils.use_internet'])
n_retries = _config.ConfigItem(10,
"How many times to retry communications when they fail")
conf = Conf()
| {
"content_hash": "203bf095080ed8df73951752d8c9edba",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 81,
"avg_line_length": 25.763157894736842,
"alnum_prop": 0.6996935648621042,
"repo_name": "bsipocz/astropy",
"id": "dcd6e9240860aac5908d5a0af75fb7171987eb84",
"size": "1043",
"binary": false,
"copies": "1",
"ref": "refs/heads/hacking",
"path": "astropy/samp/__init__.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "442627"
},
{
"name": "C++",
"bytes": "1057"
},
{
"name": "HTML",
"bytes": "1172"
},
{
"name": "Objective-C",
"bytes": "615"
},
{
"name": "Python",
"bytes": "9395160"
},
{
"name": "TeX",
"bytes": "853"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Coq bench</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../../..">Unstable</a></li>
<li><a href=".">dev / contrib:founify 8.4.dev</a></li>
<li class="active"><a href="">2014-11-20 08:04:42</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="../../../../../about.html">About</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href=".">« Up</a>
<h1>
contrib:founify
<small>
8.4.dev
<span class="label label-info">Not compatible with this Coq</span>
</small>
</h1>
<p><em><script>document.write(moment("2014-11-20 08:04:42 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2014-11-20 08:04:42 UTC)</em><p>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>ruby lint.rb unstable ../unstable/packages/coq:contrib:founify/coq:contrib:founify.8.4.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
<dt>Output</dt>
<dd><pre>The package is valid.
</pre></dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --dry-run coq:contrib:founify.8.4.dev coq.dev</code></dd>
<dt>Return code</dt>
<dd>768</dd>
<dt>Duration</dt>
<dd>0 s</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is dev).
The following dependencies couldn't be met:
- coq:contrib:founify -> coq <= 8.4.dev
Your request can't be satisfied:
- Conflicting version constraints for coq
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq, to test if the problem was incompatibility with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --dry-run coq:contrib:founify.8.4.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>2 s</dd>
<dt>Output</dt>
<dd><pre>The following actions will be performed:
- remove coq.dev
=== 1 to remove ===
=-=- Removing Packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Removing coq.dev.
[WARNING] Directory /home/bench/.opam/system/lib/coq is not empty, not removing
The following actions will be performed:
- install coq.8.4pl4 [required by coq:contrib:founify]
- install coq:contrib:founify.8.4.dev
=== 2 to install ===
=-=- Synchronizing package archives -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
=-=- Installing packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Building coq.8.4pl4:
./configure -configdir /home/bench/.opam/system/lib/coq/config -mandir /home/bench/.opam/system/man -docdir /home/bench/.opam/system/doc --prefix /home/bench/.opam/system --usecamlp5 --camlp5dir /home/bench/.opam/system/lib/camlp5 --coqide no
make -j4 world
make -j4 states
make install
Installing coq.8.4pl4.
Building coq:contrib:founify.8.4.dev:
coq_makefile -f Make -o Makefile
make -j4
make install
Installing coq:contrib:founify.8.4.dev.
</pre></dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>Data not available in this bench.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html> | {
"content_hash": "06bc5bc583aafcd9de4c2ca41920c85a",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 244,
"avg_line_length": 40.739644970414204,
"alnum_prop": 0.5038489469862019,
"repo_name": "coq-bench/coq-bench.github.io-old",
"id": "0f526bda38b1bcbb7dbbcbb59231b7aaeac0c6c8",
"size": "6887",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.01.0-1.2.0/unstable/dev/contrib:founify/8.4.dev/2014-11-20_08-04-42.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
#ifndef RenderRegion_h
#define RenderRegion_h
#include "LayerFragment.h"
#include "RenderBlockFlow.h"
#include "StyleInheritedData.h"
#include "VisiblePosition.h"
#include <memory>
namespace WebCore {
class Element;
class RenderBox;
class RenderBoxRegionInfo;
class RenderFlowThread;
class RenderNamedFlowThread;
class RenderRegion : public RenderBlockFlow {
public:
void styleDidChange(StyleDifference, const RenderStyle* oldStyle) override;
void setFlowThreadPortionRect(const LayoutRect& rect) { m_flowThreadPortionRect = rect; }
LayoutRect flowThreadPortionRect() const { return m_flowThreadPortionRect; }
LayoutRect flowThreadPortionOverflowRect();
LayoutPoint flowThreadPortionLocation() const;
virtual void attachRegion();
virtual void detachRegion();
RenderNamedFlowThread* parentNamedFlowThread() const { return m_parentNamedFlowThread; }
RenderFlowThread* flowThread() const { return m_flowThread; }
// Valid regions do not create circular dependencies with other flows.
bool isValid() const { return m_isValid; }
void setIsValid(bool valid) { m_isValid = valid; }
RenderBoxRegionInfo* renderBoxRegionInfo(const RenderBox*) const;
RenderBoxRegionInfo* setRenderBoxRegionInfo(const RenderBox*, LayoutUnit logicalLeftInset, LayoutUnit logicalRightInset,
bool containingBlockChainIsInset);
std::unique_ptr<RenderBoxRegionInfo> takeRenderBoxRegionInfo(const RenderBox*);
void removeRenderBoxRegionInfo(const RenderBox*);
void deleteAllRenderBoxRegionInfo();
bool isFirstRegion() const;
bool isLastRegion() const;
virtual bool shouldClipFlowThreadContent() const;
// These methods represent the width and height of a "page" and for a RenderRegion they are just the
// content width and content height of a region. For RenderRegionSets, however, they will be the width and
// height of a single column or page in the set.
virtual LayoutUnit pageLogicalWidth() const;
virtual LayoutUnit pageLogicalHeight() const;
LayoutUnit logicalTopOfFlowThreadContentRect(const LayoutRect&) const;
LayoutUnit logicalBottomOfFlowThreadContentRect(const LayoutRect&) const;
LayoutUnit logicalTopForFlowThreadContent() const { return logicalTopOfFlowThreadContentRect(flowThreadPortionRect()); };
LayoutUnit logicalBottomForFlowThreadContent() const { return logicalBottomOfFlowThreadContentRect(flowThreadPortionRect()); };
// This method represents the logical height of the entire flow thread portion used by the region or set.
// For RenderRegions it matches logicalPaginationHeight(), but for sets it is the height of all the pages
// or columns added together.
virtual LayoutUnit logicalHeightOfAllFlowThreadContent() const;
// The top of the nearest page inside the region. For RenderRegions, this is just the logical top of the
// flow thread portion we contain. For sets, we have to figure out the top of the nearest column or
// page.
virtual LayoutUnit pageLogicalTopForOffset(LayoutUnit offset) const;
// Whether or not this region is a set.
virtual bool isRenderRegionSet() const { return false; }
virtual void repaintFlowThreadContent(const LayoutRect& repaintRect);
virtual void collectLayerFragments(LayerFragments&, const LayoutRect&, const LayoutRect&) { }
virtual void adjustRegionBoundsFromFlowThreadPortionRect(LayoutRect& regionBounds) const;
void addLayoutOverflowForBox(const RenderBox*, const LayoutRect&);
void addVisualOverflowForBox(const RenderBox*, const LayoutRect&);
LayoutRect layoutOverflowRectForBox(const RenderBox*);
LayoutRect visualOverflowRectForBox(const RenderBoxModelObject&);
LayoutRect layoutOverflowRectForBoxForPropagation(const RenderBox*);
LayoutRect visualOverflowRectForBoxForPropagation(const RenderBoxModelObject&);
LayoutRect rectFlowPortionForBox(const RenderBox*, const LayoutRect&) const;
void setRegionObjectsRegionStyle();
void restoreRegionObjectsOriginalStyle();
bool canHaveChildren() const override { return false; }
bool canHaveGeneratedChildren() const override { return true; }
VisiblePosition positionForPoint(const LayoutPoint&, const RenderRegion*) override;
virtual bool hasAutoLogicalHeight() const { return false; }
virtual void absoluteQuadsForBoxInRegion(Vector<FloatQuad>&, bool*, const RenderBox*, float, float) { }
protected:
RenderRegion(Element&, RenderStyle&&, RenderFlowThread*);
RenderRegion(Document&, RenderStyle&&, RenderFlowThread*);
void ensureOverflowForBox(const RenderBox*, RefPtr<RenderOverflow>&, bool);
void computePreferredLogicalWidths() override;
void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const override;
enum OverflowType {
LayoutOverflow = 0,
VisualOverflow
};
LayoutRect overflowRectForFlowThreadPortion(const LayoutRect& flowThreadPortionRect, bool isFirstPortion, bool isLastPortion, OverflowType);
void repaintFlowThreadContentRectangle(const LayoutRect& repaintRect, const LayoutRect& flowThreadPortionRect, const LayoutPoint& regionLocation, const LayoutRect* flowThreadPortionClipRect = 0);
void computeOverflowFromFlowThread();
private:
bool isRenderRegion() const final { return true; }
const char* renderName() const override { return "RenderRegion"; }
void insertedIntoTree() override;
void willBeRemovedFromTree() override;
virtual void installFlowThread();
LayoutPoint mapRegionPointIntoFlowThreadCoordinates(const LayoutPoint&);
protected:
RenderFlowThread* m_flowThread;
private:
// If this RenderRegion is displayed as part of another named flow,
// we need to create a dependency tree, so that layout of the
// regions is always done before the regions themselves.
RenderNamedFlowThread* m_parentNamedFlowThread;
LayoutRect m_flowThreadPortionRect;
// This map holds unique information about a block that is split across regions.
// A RenderBoxRegionInfo* tells us about any layout information for a RenderBox that
// is unique to the region. For now it just holds logical width information for RenderBlocks, but eventually
// it will also hold a custom style for any box (for region styling).
typedef HashMap<const RenderBox*, std::unique_ptr<RenderBoxRegionInfo>> RenderBoxRegionInfoMap;
RenderBoxRegionInfoMap m_renderBoxRegionInfo;
bool m_isValid : 1;
};
class CurrentRenderRegionMaintainer {
WTF_MAKE_NONCOPYABLE(CurrentRenderRegionMaintainer);
public:
CurrentRenderRegionMaintainer(RenderRegion&);
~CurrentRenderRegionMaintainer();
RenderRegion& region() const { return m_region; }
private:
RenderRegion& m_region;
};
} // namespace WebCore
SPECIALIZE_TYPE_TRAITS_RENDER_OBJECT(RenderRegion, isRenderRegion())
#endif // RenderRegion_h
| {
"content_hash": "1fef0cbe210784bf20dce2d2806b1aa7",
"timestamp": "",
"source": "github",
"line_count": 167,
"max_line_length": 199,
"avg_line_length": 41.51497005988024,
"alnum_prop": 0.7735468051348623,
"repo_name": "applesrc/WebCore",
"id": "9a4401023c52a14fa9f65e991b2116e811a30ef7",
"size": "8303",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rendering/RenderRegion.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "1942"
},
{
"name": "C",
"bytes": "1389023"
},
{
"name": "C++",
"bytes": "42141769"
},
{
"name": "CMake",
"bytes": "254371"
},
{
"name": "CSS",
"bytes": "195888"
},
{
"name": "HTML",
"bytes": "2042"
},
{
"name": "JavaScript",
"bytes": "325391"
},
{
"name": "Makefile",
"bytes": "59092"
},
{
"name": "Objective-C",
"bytes": "927452"
},
{
"name": "Objective-C++",
"bytes": "3488469"
},
{
"name": "Perl",
"bytes": "646919"
},
{
"name": "Perl6",
"bytes": "79316"
},
{
"name": "Python",
"bytes": "37212"
},
{
"name": "Roff",
"bytes": "26536"
},
{
"name": "Shell",
"bytes": "356"
},
{
"name": "Yacc",
"bytes": "11721"
}
],
"symlink_target": ""
} |
/* globals describe, beforeEach, it, expect, inject, VehicleMock */
describe('Vehicles Index Controller', function(){
'use strict';
var $httpBackend,
$rootScope,
scope,
controller;
beforeEach(module('sc'));
beforeEach(module('sc.vehicles'));
beforeEach(inject(function($injector, $controller, _$rootScope_, Showcase) {
$rootScope = _$rootScope_;
$httpBackend = $injector.get('$httpBackend');
$httpBackend.whenGET(Showcase.API + 'vehicles/compare/1').respond(200, VehicleMock.COMPARE);
$httpBackend.whenGET(Showcase.API + 'vehicles/compare/1,2,3,4').respond(200, VehicleMock.COMPARE);
scope = $rootScope.$new();
$rootScope.flashMessage = '';
// Create the controller
controller = $controller('vehiclesIndexController', {
$scope: scope,
vehiclesCollection: angular.copy(VehicleMock.ALL)
});
$rootScope.compareItems = [];
}));
it('should load four items', function() {
expect(controller.items.length).toEqual(4);
});
it('should validate a comparison', function() {
controller.compare(controller.items[0], true);
scope.$digest();
expect($rootScope.flashMessage).toEqual('');
});
it('should uncheck the first vehicle', function() {
controller.compare(controller.items[0], false);
scope.$digest();
expect($rootScope.flashMessage).toEqual('');
});
it('should trhow a validation error (max 3 items allowed)', function() {
controller.compare(controller.items[0], true);
controller.compare(controller.items[1], true);
controller.compare(controller.items[2], true);
controller.compare(controller.items[3], true);
scope.$digest();
expect($rootScope.flashMessage).toEqual('You can only select up to 3 vehicles to compare.');
});
}); | {
"content_hash": "053bb497915568fabca0f23c523e2360",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 100,
"avg_line_length": 29.87719298245614,
"alnum_prop": 0.7040516735173223,
"repo_name": "jandrade/showcase",
"id": "d74da94cfb3eec32e315b5c73186c58a371620a6",
"size": "1703",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/unit/vehicles/controllers/vehicles.index.controller.spec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7655"
},
{
"name": "HTML",
"bytes": "11042"
},
{
"name": "JavaScript",
"bytes": "68593"
}
],
"symlink_target": ""
} |
package blkidx
| {
"content_hash": "ce60373ad9df0b3480bf4d23d0c30bf4",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 14,
"avg_line_length": 15,
"alnum_prop": 0.8666666666666667,
"repo_name": "PhiCode/blkidx",
"id": "7bd6ad8c033f52660fc6eb69cf05e0180834b748",
"size": "15",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "indexer_test.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "33476"
},
{
"name": "Shell",
"bytes": "1237"
}
],
"symlink_target": ""
} |
<?php
/**
* Used for fetching remote files and reading local files
*
* Supports HTTP 1.0 via cURL or fsockopen, with spotty HTTP 1.1 support
*
* This class can be overloaded with {@see SimplePie::set_file_class()}
*
* @package SimplePie
* @subpackage HTTP
* @todo Move to properly supporting RFC2616 (HTTP/1.1)
*/
class SimplePie_File
{
var $url;
var $useragent;
var $success = true;
var $headers = array();
var $body;
var $status_code;
var $redirects = 0;
var $error;
var $method = SIMPLEPIE_FILE_SOURCE_NONE;
var $permanent_url;
public function __construct($url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false, $curl_options = array())
{
if (class_exists('idna_convert'))
{
$idn = new idna_convert();
$parsed = SimplePie_Misc::parse_url($url);
$url = SimplePie_Misc::compress_parse_url($parsed['scheme'], $idn->encode($parsed['authority']), $parsed['path'], $parsed['query'], $parsed['fragment']);
}
$this->url = $url;
$this->permanent_url = $url;
$this->useragent = $useragent;
if (preg_match('/^http(s)?:\/\//i', $url))
{
if ($useragent === null)
{
$useragent = ini_get('user_agent');
$this->useragent = $useragent;
}
if (!is_array($headers))
{
$headers = array();
}
if (!$force_fsockopen && function_exists('curl_exec'))
{
$this->method = SIMPLEPIE_FILE_SOURCE_REMOTE | SIMPLEPIE_FILE_SOURCE_CURL;
$fp = curl_init();
$headers2 = array();
foreach ($headers as $key => $value)
{
$headers2[] = "$key: $value";
}
if (version_compare(SimplePie_Misc::get_curl_version(), '7.10.5', '>='))
{
curl_setopt($fp, CURLOPT_ENCODING, '');
}
curl_setopt($fp, CURLOPT_URL, $url);
curl_setopt($fp, CURLOPT_HEADER, 1);
curl_setopt($fp, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($fp, CURLOPT_FAILONERROR, 1);
curl_setopt($fp, CURLOPT_TIMEOUT, $timeout);
curl_setopt($fp, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($fp, CURLOPT_REFERER, $url);
curl_setopt($fp, CURLOPT_USERAGENT, $useragent);
curl_setopt($fp, CURLOPT_HTTPHEADER, $headers2);
if (!ini_get('open_basedir') && !ini_get('safe_mode') && version_compare(SimplePie_Misc::get_curl_version(), '7.15.2', '>='))
{
curl_setopt($fp, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($fp, CURLOPT_MAXREDIRS, $redirects);
}
foreach ($curl_options as $curl_param => $curl_value) {
curl_setopt($fp, $curl_param, $curl_value);
}
$this->headers = curl_exec($fp);
if (curl_errno($fp) === 23 || curl_errno($fp) === 61)
{
curl_setopt($fp, CURLOPT_ENCODING, 'none');
$this->headers = curl_exec($fp);
}
if (curl_errno($fp))
{
$this->error = 'cURL error ' . curl_errno($fp) . ': ' . curl_error($fp);
$this->success = false;
}
else
{
// Use the updated url provided by curl_getinfo after any redirects.
if ($info = curl_getinfo($fp)) {
$this->url = $info['url'];
}
curl_close($fp);
$this->headers = explode("\r\n\r\n", $this->headers, $info['redirect_count'] + 1);
$this->headers = array_pop($this->headers);
$parser = new SimplePie_HTTP_Parser($this->headers);
if ($parser->parse())
{
$this->headers = $parser->headers;
$this->body = trim($parser->body);
$this->status_code = $parser->status_code;
if ((in_array($this->status_code, array(300, 301, 302, 303, 307)) || $this->status_code > 307 && $this->status_code < 400) && isset($this->headers['location']) && $this->redirects < $redirects)
{
$this->redirects++;
$location = SimplePie_Misc::absolutize_url($this->headers['location'], $url);
$previousStatusCode = $this->status_code;
$this->__construct($location, $timeout, $redirects, $headers, $useragent, $force_fsockopen);
$this->permanent_url = ($previousStatusCode == 301) ? $location : $url;
return;
}
}
}
}
else
{
$this->method = SIMPLEPIE_FILE_SOURCE_REMOTE | SIMPLEPIE_FILE_SOURCE_FSOCKOPEN;
$url_parts = parse_url($url);
$socket_host = $url_parts['host'];
if (isset($url_parts['scheme']) && strtolower($url_parts['scheme']) === 'https')
{
$socket_host = "ssl://$url_parts[host]";
$url_parts['port'] = 443;
}
if (!isset($url_parts['port']))
{
$url_parts['port'] = 80;
}
$fp = @fsockopen($socket_host, $url_parts['port'], $errno, $errstr, $timeout);
if (!$fp)
{
$this->error = 'fsockopen error: ' . $errstr;
$this->success = false;
}
else
{
stream_set_timeout($fp, $timeout);
if (isset($url_parts['path']))
{
if (isset($url_parts['query']))
{
$get = "$url_parts[path]?$url_parts[query]";
}
else
{
$get = $url_parts['path'];
}
}
else
{
$get = '/';
}
$out = "GET $get HTTP/1.1\r\n";
$out .= "Host: $url_parts[host]\r\n";
$out .= "User-Agent: $useragent\r\n";
if (extension_loaded('zlib'))
{
$out .= "Accept-Encoding: x-gzip,gzip,deflate\r\n";
}
if (isset($url_parts['user']) && isset($url_parts['pass']))
{
$out .= "Authorization: Basic " . base64_encode("$url_parts[user]:$url_parts[pass]") . "\r\n";
}
foreach ($headers as $key => $value)
{
$out .= "$key: $value\r\n";
}
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
$info = stream_get_meta_data($fp);
$this->headers = '';
while (!$info['eof'] && !$info['timed_out'])
{
$this->headers .= fread($fp, 1160);
$info = stream_get_meta_data($fp);
}
if (!$info['timed_out'])
{
$parser = new SimplePie_HTTP_Parser($this->headers);
if ($parser->parse())
{
$this->headers = $parser->headers;
$this->body = trim($parser->body);
$this->status_code = $parser->status_code;
if ((in_array($this->status_code, array(300, 301, 302, 303, 307)) || $this->status_code > 307 && $this->status_code < 400) && isset($this->headers['location']) && $this->redirects < $redirects)
{
$this->redirects++;
$location = SimplePie_Misc::absolutize_url($this->headers['location'], $url);
$previousStatusCode = $this->status_code;
$this->__construct($location, $timeout, $redirects, $headers, $useragent, $force_fsockopen);
$this->permanent_url = ($previousStatusCode == 301) ? $location : $url;
return;
}
if (isset($this->headers['content-encoding']))
{
// Hey, we act dumb elsewhere, so let's do that here too
switch (strtolower(trim($this->headers['content-encoding'], "\x09\x0A\x0D\x20")))
{
case 'gzip':
case 'x-gzip':
$decoder = new SimplePie_gzdecode($this->body);
if (!$decoder->parse())
{
$this->error = 'Unable to decode HTTP "gzip" stream';
$this->success = false;
}
else
{
$this->body = trim($decoder->data);
}
break;
case 'deflate':
if (($decompressed = gzinflate($this->body)) !== false)
{
$this->body = $decompressed;
}
else if (($decompressed = gzuncompress($this->body)) !== false)
{
$this->body = $decompressed;
}
else if (function_exists('gzdecode') && ($decompressed = gzdecode($this->body)) !== false)
{
$this->body = $decompressed;
}
else
{
$this->error = 'Unable to decode HTTP "deflate" stream';
$this->success = false;
}
break;
default:
$this->error = 'Unknown content coding';
$this->success = false;
}
}
}
}
else
{
$this->error = 'fsocket timed out';
$this->success = false;
}
fclose($fp);
}
}
}
else
{
$this->method = SIMPLEPIE_FILE_SOURCE_LOCAL | SIMPLEPIE_FILE_SOURCE_FILE_GET_CONTENTS;
if (empty($url) || !($this->body = trim(file_get_contents($url))))
{
$this->error = 'file_get_contents could not read the file';
$this->success = false;
}
}
}
}
| {
"content_hash": "f49b7020423e1dacf4f0d2ccc0167455",
"timestamp": "",
"source": "github",
"line_count": 266,
"max_line_length": 200,
"avg_line_length": 31.172932330827066,
"alnum_prop": 0.5479980704293295,
"repo_name": "himynameismax/codeigniter",
"id": "a609adf08cecc1ed8fe7322753a9875843656e9b",
"size": "10334",
"binary": false,
"copies": "69",
"ref": "refs/heads/master",
"path": "glpi/vendor/simplepie/simplepie/library/SimplePie/File.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "15982"
},
{
"name": "ApacheConf",
"bytes": "2742"
},
{
"name": "Batchfile",
"bytes": "422"
},
{
"name": "CSS",
"bytes": "692417"
},
{
"name": "HTML",
"bytes": "8442881"
},
{
"name": "JavaScript",
"bytes": "3306478"
},
{
"name": "PHP",
"bytes": "22844717"
},
{
"name": "Perl",
"bytes": "308333"
},
{
"name": "Shell",
"bytes": "7519"
},
{
"name": "Standard ML",
"bytes": "33"
}
],
"symlink_target": ""
} |
// Generated on 2014-06-08 using generator-angular 0.8.0
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
grunt.loadNpmTasks('grunt-karma-coveralls');
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
yeoman: {
// configurable paths
lib: require('./bower.json').appPath || 'lib',
dist: 'dist'
},
// Release settings
bump: {
options: {
files: ['package.json', 'bower.json'],
updateConfigs: [],
commit: true,
push: true,
commitMessage: 'Release v%VERSION%',
commitFiles: ['package.json', 'bower.json'], // '-a' for all files
createTag: true,
tagName: 'v%VERSION%',
tagMessage: 'Version %VERSION%',
pushTo: 'origin'
// gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d' // options to use with '$ git describe'
}
},
coveralls: {
options: {
debug: false,
'coverage_dir': 'coverage/',
dryRun: false,
force: true,
recursive: true
}
},
// Build settings
clean : {
dist : ['.tmp', 'dist']
},
concat : {
dist : {
src: ['<%= yeoman.lib %>/module.js', '<%= yeoman.lib %>/coq.js', '<%= yeoman.lib %>/q/pipeline.js', '<%= yeoman.lib %>/directives/coq-form-services.js', '<%= yeoman.lib %>/directives/coq-model-attribute.js', '<%= yeoman.lib %>/directives/coq-model.js'],
dest: '.tmp/angular-coq.js',
}
},
ngmin: {
dist: {
files: [{
expand: true,
cwd: '.tmp/',
src: '*.js',
dest: '<%= yeoman.dist %>'
}]
}
},
uglify: {
dist: {
files: {
'<%= yeoman.dist %>/angular-coq.min.js': [
'<%= yeoman.dist %>/angular-coq.js'
]
}
}
},
// Test settings
watch: {
jsTest: {
files: ['test/spec/{,**/}*.js'],
tasks: ['newer:jshint:test', 'karma']
}
},
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true
}
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/spec/{,**/}*.js']
}
}
});
grunt.registerTask('test', [
'karma',
'coveralls'
]);
grunt.registerTask('build', [
'clean:dist',
'concat:dist',
'ngmin:dist',
'uglify:dist'
]);
};
| {
"content_hash": "a748f481cbbddcef7611edfe8df08193",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 261,
"avg_line_length": 22.601503759398497,
"alnum_prop": 0.5109780439121756,
"repo_name": "squareteam/angular-coq",
"id": "aa02ecdedb80b35a0920c6f1b63889be96b8591d",
"size": "3006",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Gruntfile.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "41677"
}
],
"symlink_target": ""
} |
using System;
namespace Rivet.Operations
{
[ObjectRemovedByOperation(typeof(RemoveStoredProcedureOperation))]
public sealed class AddStoredProcedureOperation : ObjectOperation
{
public AddStoredProcedureOperation(string schemaName, string name, string definition)
: base(schemaName, name)
{
Definition = definition;
}
public string Definition { get; set; }
public override string ToIdempotentQuery()
{
return
$"if object_id('{SchemaName}.{Name}', 'P') is null and object_id('{SchemaName}.{Name}', 'PC') is null{Environment.NewLine}" +
$" exec sp_executesql N'{ToQuery().Replace("'", "''")}'";
}
public override string ToQuery()
{
return $"create procedure [{SchemaName}].[{Name}] {Definition}";
}
}
} | {
"content_hash": "2546146b85982f230c93f0f58b8a255d",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 129,
"avg_line_length": 27.821428571428573,
"alnum_prop": 0.6713735558408216,
"repo_name": "RivetDB/Rivet",
"id": "afcf1f40853c6d0bdce1f98d09a620101fe0f2ab",
"size": "781",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/Operations/AddStoredProcedureOperation.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1702"
},
{
"name": "C#",
"bytes": "239528"
},
{
"name": "CSS",
"bytes": "11203"
},
{
"name": "HTML",
"bytes": "1140659"
},
{
"name": "JavaScript",
"bytes": "1659"
},
{
"name": "PLSQL",
"bytes": "326"
},
{
"name": "PowerShell",
"bytes": "1366494"
},
{
"name": "XSLT",
"bytes": "1394"
}
],
"symlink_target": ""
} |
package org.apache.commons.functor.adapter;
import org.apache.commons.functor.BinaryPredicate;
import org.apache.commons.functor.Predicate;
import org.apache.commons.lang3.Validate;
/**
* Adapts a
* {@link Predicate Predicate}
* to the
* {@link BinaryPredicate BinaryPredicate} interface
* by ignoring the first binary argument.
*
* @param <L> the left argument type.
* @param <R> the right argument type.
* @version $Revision$ $Date$
*/
public final class IgnoreLeftPredicate<L, R> implements BinaryPredicate<L, R> {
/** The {@link Predicate Predicate} I'm wrapping. */
private final Predicate<? super R> predicate;
/**
* Create a new IgnoreLeftPredicate.
* @param predicate the right predicate
*/
public IgnoreLeftPredicate(Predicate<? super R> predicate) {
this.predicate = Validate.notNull(predicate, "Predicate argument was null");
}
/**
* {@inheritDoc}
*/
public boolean test(L left, R right) {
return predicate.test(right);
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof IgnoreLeftPredicate<?, ?>)) {
return false;
}
IgnoreLeftPredicate<?, ?> that = (IgnoreLeftPredicate<?, ?>) obj;
return this.predicate.equals(that.predicate);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int hash = "IgnoreLeftPredicate".hashCode();
hash ^= predicate.hashCode();
return hash;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "IgnoreLeftPredicate<" + predicate + ">";
}
/**
* Adapt a Predicate to an IgnoreLeftPredicate.
* @param <L> left type
* @param <R> right type
* @param predicate to adapt
* @return IgnoreLeftPredicate<L, R>
*/
public static <L, R> IgnoreLeftPredicate<L, R> adapt(Predicate<? super R> predicate) {
return null == predicate ? null : new IgnoreLeftPredicate<L, R>(predicate);
}
}
| {
"content_hash": "88357d73b08dc3fd97be691cb7fef914",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 90,
"avg_line_length": 26,
"alnum_prop": 0.6097560975609756,
"repo_name": "apache/commons-functor",
"id": "68ce70bf2861408fc1baeccb3ad2bf4813f8eedb",
"size": "2934",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/src/main/java/org/apache/commons/functor/adapter/IgnoreLeftPredicate.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1521502"
},
{
"name": "Shell",
"bytes": "157"
}
],
"symlink_target": ""
} |
#ifndef THREX_H
#define THREX_H
#include "operators.h"
//#include "storage.h"
#include "functions.h"
#include "host_vector.h"
#include "device_vector.h"
#include "host_matrix.h"
#include "device_matrix.h"
#include "blas.h"
// Some cuda header seems to want to define a bool all(bool) in global scope.
// Unbelievable! So here's the workaround for now - just use that global all.
// the __device__ keyword added by Ben Cumming to avoid compiler warning
// ... maybe should be a __device__ __host__
extern __device__ bool all(bool);
namespace minlin {
namespace threx {
//using ::minlin::end;
//using ::minlin::all;
using minlin::inf;
} // end namespace threx
} // end namespace minlin
#endif
| {
"content_hash": "ac55f8d8c2e73c221ed4221b28016138",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 78,
"avg_line_length": 21.90625,
"alnum_prop": 0.6990014265335235,
"repo_name": "bcumming/minlin",
"id": "766fa6da2f259433685ca0abbcb98a1c9d3932dc",
"size": "997",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/minlin/modules/threx/threx.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "153375"
},
{
"name": "C++",
"bytes": "175289"
},
{
"name": "Cuda",
"bytes": "26538"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>dijkstra: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.7.0 / dijkstra - 0.1.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
dijkstra
<small>
0.1.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-03-04 08:05:14 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-04 08:05:14 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.7.0 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.06.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.06.1 Official 4.06.1 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
# This file is generated by dune, edit dune-project instead
opam-version: "2.0"
synopsis: "A Verified Implementation of Dijkstra's Algorithm"
maintainer: ["Masayuki Mizuno <[email protected]>"]
authors: ["Masayuki Mizuno <[email protected]>"]
license: "MIT"
homepage: "https://github.com/fetburner/coq-dijkstra"
bug-reports: "https://github.com/fetburner/coq-dijkstra/issues"
depends: [
"dune" {>= "2.5"}
"coq" {>= "8.8"}
"coq-mathcomp-ssreflect" {>= "1.11"}
]
build: [
["dune" "subst"] {pinned}
[
"dune"
"build"
"-p"
name
"-j"
jobs
"@install"
"@runtest" {with-test}
"@doc" {with-doc}
]
]
dev-repo: "git+https://github.com/fetburner/coq-dijkstra.git"
tags: [
"keyword:graph theory"
"keyword:shortest path"
"keyword:Dijkstra's algorithm"
"category:Computer Science/Graph Theory"
"date:2021-03-02"
"logpath:Dijkstra"
]
url {
src: "https://github.com/fetburner/coq-dijkstra/archive/0.1.0.tar.gz"
checksum: "md5=ba5b8f156d209b428eaafe75436bee97"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-dijkstra.0.1.0 coq.8.7.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.0).
The following dependencies couldn't be met:
- coq-dijkstra -> coq >= 8.8
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-dijkstra.0.1.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "45841b6c5d8df93c1a34dd9d55d7a2b5",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 159,
"avg_line_length": 38.790055248618785,
"alnum_prop": 0.5388121350235009,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "ec1675228090e20f87993e01726e0cc4f2cca72d",
"size": "7046",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.06.1-2.0.5/released/8.7.0/dijkstra/0.1.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
/**
* Classe de documentos
*
* @author Cecília Assis
*/
public class Document {
private final int seqNumber;
private int freq;
/**
* @param seqNumber Número do documento sendo processado.
*/
public Document(int seqNumber) {
this.seqNumber = seqNumber;
this.freq = 1;
}
/////////////////OK
public int getSeqNumber() {
return seqNumber;
}
/////////////////OK
/**
* @return Frequência do termo no documento.
*/
public int getFreq() {
return freq;
}
/**
* Aumenta a frequência do termo no documento.
*/
public void increaseFreq() {
this.freq++;
}
}
| {
"content_hash": "1e9fca715e06eac3bd89429de6410f28",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 59,
"avg_line_length": 16.5,
"alnum_prop": 0.5484848484848485,
"repo_name": "ceciliassis/UFU",
"id": "f847df05fe1ded45446aa46b601aea54f6760f17",
"size": "664",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "buscador-txt-ori/Document.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "16403"
},
{
"name": "C++",
"bytes": "3922"
},
{
"name": "CSS",
"bytes": "1148552"
},
{
"name": "CoffeeScript",
"bytes": "7907"
},
{
"name": "HTML",
"bytes": "311639"
},
{
"name": "Java",
"bytes": "345863"
},
{
"name": "JavaScript",
"bytes": "6973779"
},
{
"name": "PLpgSQL",
"bytes": "8924"
},
{
"name": "Ruby",
"bytes": "15335"
},
{
"name": "Shell",
"bytes": "642"
}
],
"symlink_target": ""
} |
{% extends "users/base.html" %}
{% load users_tags %}
{% block page_title %}Nominations | {{ SITE_INFO.site_name }}{% endblock %}
{% block body_attributes %}class="psf users default-page"{% endblock %}
{% block main-nav_attributes %}psf-navigation{% endblock %}
{% block content_attributes %}with-right-sidebar{% endblock %}
{% block user_content %}
<div>
{% for election, nominations in elections.items %}
<h1><a href="{% url 'nominations:nominees_list' election=election.slug %}">{{ election.name }} Election</a></h1>
{% if nominations.nominations_recieved|length > 0 %}
<h2>Nominations Received</h2>
<ul>
{% for nomination in nominations.nominations_recieved %}
<li>
{% if nomination.nominator == request.user %}
Self Nomination
{% else %}
Nomination from {{ nomination.nominator.first_name }} {{ nomination.nominator.last_name }} {% if nomination.accepted %}<b>Accepted</b>{% else %}<i>Not accepted!</i>{% endif %}
{% endif %}
<a href="{{ nomination.get_absolute_url }}">
{% if nomination.is_editable %}
{% if nomination.nominator == request.user %}
View / Edit
{% else %}
View / Manage Acceptance
{% endif %}
{% else %}
View
{% endif %}
</a>
</li>
{% endfor %}
</ul>
{% endif %}
{% if nominations.nominations_made|length > 0 %}
<h2>Nominations Made</h2>
<ul>
{% for nomination in nominations.nominations_made %}
<li>
{% if nomination.nominee %}
{{ nomination.nominee.name }}
{% else %}
{{ nomination.name }}
{% endif %}
<a href="{{ nomination.get_absolute_url }}">
{% if nomination.is_editable %}
View/Edit
{% else %}
View
{% endif %}
</a>
</li>
{% endfor %}
</ul>
{% endif %}
<br>
{% endfor %}
</div>
{% endblock user_content %}
| {
"content_hash": "f23745e58cd8d03d499c82f6edb06d8f",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 179,
"avg_line_length": 25.930555555555557,
"alnum_prop": 0.5736475629351901,
"repo_name": "python/pythondotorg",
"id": "8c28aa87b56307cc874e0d63e3f4ba653ef96002",
"size": "1867",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "templates/users/nominations_view.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7686"
},
{
"name": "Dockerfile",
"bytes": "229"
},
{
"name": "HTML",
"bytes": "498813"
},
{
"name": "JavaScript",
"bytes": "24050"
},
{
"name": "Makefile",
"bytes": "1615"
},
{
"name": "PostScript",
"bytes": "19072"
},
{
"name": "Procfile",
"bytes": "105"
},
{
"name": "Python",
"bytes": "1145343"
},
{
"name": "Ruby",
"bytes": "1464"
},
{
"name": "SCSS",
"bytes": "198033"
}
],
"symlink_target": ""
} |
var PIXI = require('pixi.js/bin/pixi.dev.js');
var events = require('app/util/events');
var {vec2} = require('p2');
var GuitarString = require('app/views/guitar/GuitarString');
var Dot = require('app/views/guitar/Dot');
var GuitarDataModel = require('app/models/guitar');
var { GuitarStringModel, GuitarNoteModel } = GuitarDataModel;
module.exports = (function() {
'use strict';
const VIEW_NAME = 'GuitarView';
const NUMBER_KEY_RANGE = [49, 57];
/**
* Controls the Guitar instrument view.
* @param {AudioManager} audioManager - The shared audio manager.
* @constructor
*/
return function GuitarView(audioManager) {
const GUITAR_TAG = audioManager.addTag(VIEW_NAME);
const CHANNEL = audioManager.channels.create(0.8);
var stage;
var renderPause = false;
var APPLICATION_STATE = 'collapsed';
var displayContainerCenter;
var pid;
var currentRotation = 0;
var xSpacing, ySpacing;
var baseLayer = new PIXI.DisplayObjectContainer(); // base dots (dots non selected)
var midLayer = new PIXI.DisplayObjectContainer(); // draw strings here
var topLayer = new PIXI.DisplayObjectContainer(); // high dots (dots selected)
var isDrawing = false;
var isUndrawing = false;
var isDragging = false;
var guitarStrings = {};
var dots = {};
var currentDrawingPid;
var currentBeat;
var currentTrack;
var isReady = false;
var isRecording = false;
var isCountdown = false;
var allData;
var pidPool = [];
var gridCount;
var renderer;
Dot.clearTextureCache();
/**
* Add the note to the guitar note pool.
* @param {number} pid - The pid of the note.
*/
function addToPool(pid) {
pidPool.push(pid);
}
/**
* Remove the note from the guitar note pool.
* @param {number} pid - The pid of the note.
*/
function removeFromPool(pid) {
var idx = pidPool.indexOf(pid);
if (idx > -1) {
pidPool.splice(idx, 1);
}
}
/**
* Initialize the guitar view.
* @param {PIXI.Stage} stage_ - The PIXI stage of the view.
* @param {number} pid_ - The ID of the view.
* @param {PIXI.DisplayObjectContainer} displayContainerCenter_ - The center point of the view.
*/
function init(stage_, pid_, displayContainerCenter_, renderer_) {
stage = stage_;
pid = pid_;
displayContainerCenter = displayContainerCenter_;
renderer = renderer_;
displayContainerCenter.addChild(baseLayer);
displayContainerCenter.addChild(midLayer);
displayContainerCenter.addChild(topLayer);
events.addListener('BEAT', function(beatNum) {
currentBeat = beatNum;
});
audioManager.playbackBus.onPlayback(function(note, tags) {
if (renderPause) { return; }
if (tags & GUITAR_TAG) {
if (APPLICATION_STATE === 'collapsed') {
if (guitarStrings[note.pid]) {
guitarStrings[note.pid].playNote();
}
}
}
});
isReady = true;
}
/**
* Load guitar data.
* @param {Model} initialData - The guitar data.
*/
function loadData(initialData) {
if (currentTrack) {
audioManager.removeTrack(currentTrack);
}
for (let pid in guitarStrings) {
if (guitarStrings.hasOwnProperty(pid)) {
guitarStrings[pid].tearDown();
delete dots[pid];
addToPool(pid);
}
}
if (initialData.strings.length <= 0) { return; }
allData = initialData;
gridCount = initialData.rows * initialData.cols;
var maxStrings = Math.ceil(gridCount / 2);
for (let i = 0; i < maxStrings; i++) {
addToPool(i);
}
createDotGrid();
for (let i = 0; i < initialData.strings.length; i++) {
let guitarString = createStringFromModel(initialData.strings[i]);
guitarStrings[guitarString.getPID()] = guitarString;
}
currentTrack = audioManager.createRecordedTrack(
allData.recorded,
CHANNEL,
GUITAR_TAG
);
audioManager.addTrack(currentTrack);
}
/**
* On countdown, don't allow dots to be clicked/drawn
*/
function startCountdown() {
isCountdown = true;
}
/**
* Start recording the guitar note.
*/
function startRecording() {
isRecording = true;
isCountdown = false;
allData.recorded = [];
}
/**
* Stop recording the guitar note.
*/
function stopRecording() {
currentTrack = audioManager.createRecordedTrack(
allData.recorded,
CHANNEL,
GUITAR_TAG
);
isRecording = false;
}
/**
* Add the recorded guitar note to the loop.
* @param {number} pid - The pid of the note.
* @param {string} sound - The played guitar note.
*/
function addRecordedItem(pid, sound) {
if (!isRecording) { return; }
allData.recorded.push(new GuitarNoteModel({
beat: currentBeat,
sound: audioManager.getSound(sound).guid,
pid: pid
}));
}
/**
* Create a new guitar string.
* @param {Model} data - The data for each guitar string.
*/
function createStringFromModel(data) {
removeFromPool(data.pid);
var dotA = dots[data.pointA];
var dotB = dots[data.pointB];
var guitarString = new GuitarString(audioManager, CHANNEL, new GuitarStringModel(), renderer);
guitarString.init(data.pid, midLayer, baseLayer);
guitarString.updateSpacing(xSpacing, ySpacing);
guitarString.onActivate(addRecordedItem);
dotA.setString(guitarString);
dotB.setString(guitarString);
guitarString.setDots(dotA, dotB);
/// Pop forward
midLayer.setChildIndex(dotA.gridDotMiddle, midLayer.children.length - 1);
midLayer.setChildIndex(dotB.gridDotMiddle, midLayer.children.length - 1);
return guitarString;
}
/**
* Add event listeners.
*/
function addEventListeners() {
stage.interactive = true;
var dragStartPosition;
stage.mousedown = stage.touchstart = function(data) {
displayContainerCenter.data = data;
dragStartPosition = data.global.clone();
};
stage.mousemove = stage.touchmove = function(data) {
if (!isDrawing && !isUndrawing) {
if (!isDragging && !isRecording && !isCountdown && dragStartPosition) {
var x = data.global.x - dragStartPosition.x;
var y = data.global.y - dragStartPosition.y;
var dist = Math.sqrt(x*x + y*y);
if (dist > 20) {
isDragging = true;
}
}
for (var pid in guitarStrings) {
if (guitarStrings.hasOwnProperty(pid)) {
guitarStrings[pid].dragMouseCollisionCheck(data);
}
}
}
};
stage.mouseup = stage.touchend = function() {
isDragging = false;
dragStartPosition = null;
};
for (let key in dots) {
if (dots.hasOwnProperty(key)) {
dots[key].addEventListeners();
}
}
document.addEventListener('keyup', onGuitarKeyUp);
}
/**
* Remove event listeners.
*/
function removeEventListeners() {
stage.interactive = false;
stage.mousedown = stage.touchstart = stage.mousemove = stage.touchmove = stage.mouseup = stage.touchend = null;
for (let key in dots) {
if (dots.hasOwnProperty(key)) {
dots[key].removeEventListeners();
}
}
document.removeEventListener('keyup', onGuitarKeyUp);
}
/**
* Keyup handler for guitar strings.
* @param {event} evt - The keyup event.
*/
function onGuitarKeyUp(evt) {
if ((evt.keyCode >= NUMBER_KEY_RANGE[0]) && (evt.keyCode <= NUMBER_KEY_RANGE[1])) {
var keyPos = evt.keyCode - NUMBER_KEY_RANGE[0];
var guitarStringKey = Object.keys(guitarStrings)[keyPos];
if (guitarStrings[guitarStringKey]) {
guitarStrings[guitarStringKey].activate();
guitarStrings[guitarStringKey].playNote();
}
}
}
/**
* Create the grid of dots in the guitar view.
*/
function createDotGrid() {
for (let pid in dots) {
if (dots.hasOwnProperty(pid)) {
let {
gridDotMiddle,
gridDot,
gridDotUpper
} = dots[pid];
dots[pid].tearDown();
baseLayer.removeChild(gridDot);
topLayer.removeChild(gridDotUpper);
midLayer.removeChild(gridDotMiddle);
delete dots[pid];
}
}
for (let i = 0; i < gridCount; i++) {
let dot = new Dot(i, renderer);
dot.onActivate(activateDot);
let {
gridDotMiddle,
gridDot,
gridDotUpper
} = dot;
baseLayer.addChild(gridDot);
topLayer.addChild(gridDotUpper);
midLayer.addChild(gridDotMiddle);
dots[dot.pid] = dot;
}
updateSpacing();
redrawDotGrid();
}
/**
* Activate the dot
* @param {Object} dot - The clicked dot.
*/
function activateDot(dot) {
if (isDragging || isRecording || isCountdown) { return; }
if (APPLICATION_STATE === 'collapsed') { return; }
if (!isDrawing && !dot.getString() && !isUndrawing) {
startString(dot);
} else if (isDrawing && !dot.getString() && !isUndrawing) {
endString(dot);
} else if (!isDrawing && dot.getString() && !isUndrawing) {
restartString(dot);
} else if (!isDrawing && !dot.getString() && isUndrawing) {
endString(dot);
} else if (!isDrawing && !dot.getString() && isUndrawing) {
destroyString(dot);
} else if (isDrawing && !dot.getString() && !isUndrawing) {
destroyString(dot);
} else {
var currentGuitarString = guitarStrings[currentDrawingPid];
if (currentGuitarString && (currentGuitarString.getFirstDot() === dot)) {
destroyString(dot);
}
}
}
/**
* Start drawing the string from the clicked dot.
* @param {Object} dot - The clicked dot.
*/
function startString(dot) {
if (isDrawing) { return; }
var pid = pidPool.pop();
currentDrawingPid = pid;
isDrawing = true;
var guitarString = new GuitarString(audioManager, CHANNEL, new GuitarStringModel());
guitarString.init(pid, midLayer, baseLayer);
guitarString.onActivate(addRecordedItem);
guitarString.setFirstDot(dot);
guitarString.updatePoints(dot.getPosition(), dot.getPosition());
dot.setString(guitarString);
midLayer.setChildIndex(dot.gridDotMiddle, midLayer.children.length - 1);
guitarStrings[pid] = guitarString;
baseLayer.interactive = true;
baseLayer.mousemove = baseLayer.touchmove = function(data) {
var newPosition = data.getLocalPosition(this.parent);
guitarString.updatePointsMouse(dot.getPosition(), newPosition);
};
}
/**
* Destroy the string if dot is re-clicked without attaching the string to another dot.
* @param {Object} dot - The clicked dot.
*/
function destroyString(dot) {
var guitarString = dot.getString();
isUndrawing = false;
isDrawing = false;
dot.setString(null);
var pid = guitarString.getPID();
delete guitarStrings[pid];
addToPool(pid);
guitarString.destroy();
baseLayer.interactive = false;
baseLayer.mousemove = baseLayer.touchmove = null;
}
/**
* Restart drawing the string.
* @param {Object} dot - The clicked dot.
*/
function restartString(dot) {
if (isUndrawing) { return; }
isUndrawing = true;
var guitarString = dot.getString();
currentDrawingPid = guitarString.getPID();
var firstDot = guitarString.getFirstDot();
if (firstDot === dot) {
guitarString.setFirstDot(guitarString.getSecondDot());
firstDot = guitarString.getFirstDot();
}
guitarString.setSecondDot(null);
dot.setString(null);
guitarString.bumpStringDepths();
midLayer.setChildIndex(firstDot.gridDotMiddle, midLayer.children.length - 1);
baseLayer.interactive = true;
baseLayer.mousemove = baseLayer.touchmove = function(data) {
data.originalEvent.preventDefault();
var newPosition = data.getLocalPosition(this.parent);
guitarString.updatePointsMouse(firstDot.getPosition(), newPosition);
};
}
/**
* Complete the string when end dot is clicked.
* @param {Object} dot - The clicked dot.
*/
function endString(dot) {
isDrawing = false;
isUndrawing = false;
var guitarString = guitarStrings[currentDrawingPid];
guitarString.setSecondDot(dot);
guitarString.updateSpacing(xSpacing, ySpacing);
dot.setString(guitarString);
midLayer.setChildIndex(dot.gridDotMiddle, midLayer.children.length - 1);
baseLayer.interactive = false;
baseLayer.mousemove = baseLayer.touchmove = null;
}
/**
* Get the position of the guitar view.
* @param {number} x - The x position of the view.
* @param {number} y - The x position of the view.
* @param {number} xSpacing - The x spacing.
* @param {number} ySpacing - The y spacing.
*/
function getPosition(x, y, xSpacing, ySpacing) {
var pos = vec2.fromValues(x * xSpacing, y * ySpacing);
vec2.rotate(pos, pos, currentRotation);
return pos;
}
/**
* Redraw the dot grid.
*/
function redrawDotGrid() {
var startingX = -Math.floor(allData.cols / 2);
var startX = startingX;
var startY = -Math.floor(allData.rows / 2);
var currentColumn = 0;
for (let i = 0; i < gridCount; i++) {
let position = getPosition(startX, startY, xSpacing, ySpacing);
dots[i].setPosition(new PIXI.Point(position[0], position[1]));
startX = startX + 1;
currentColumn = currentColumn + 1;
if (currentColumn > (allData.cols - 1)) {
currentColumn = 0;
startX = startingX;
startY += 1;
}
}
}
/**
* Do things when the guitar animation is collapsed.
*/
function animationCollapsed() {
APPLICATION_STATE = 'collapsed';
audioManager.addTrack(currentTrack);
removeEventListeners();
}
/**
* Do things when the guitar animation is expanded.
*/
function animationExpanded() {
APPLICATION_STATE = 'expand';
audioManager.removeTrack(currentTrack);
addEventListeners();
}
/**
* Resize the guitar view on resize.
* @param {number} w - The width of the guitar view.
* @param {number} h - The height of the guitar view.
* @param {number} boundsWidth - The bounding width of the guitar view.
* @param {number} boundsHeight - The bounding height of the guitar view.
*/
var lastBoundsWidth;
var lastBoundsHeight;
function resize(w, h, boundsWidth, boundsHeight) {
if (!isReady) { return; }
lastBoundsWidth = boundsWidth;
lastBoundsHeight = boundsHeight;
updateSpacing();
}
/**
* Update the spacing in the guitar grid.
*/
function updateSpacing() {
if (!allData) { return; }
// Flipped because "default" state is vertical.
if (lastBoundsWidth >= lastBoundsHeight) {
xSpacing = (lastBoundsWidth / (allData.cols - 1));
ySpacing = (lastBoundsHeight / (allData.rows - 1));
currentRotation = 0;
} else {
// Y becomes X :)
xSpacing = (lastBoundsHeight / (allData.cols - 1));
ySpacing = (lastBoundsWidth / (allData.rows - 1));
currentRotation = Math.PI / 2;
}
for (let pid in guitarStrings) {
if (guitarStrings.hasOwnProperty(pid)) {
var guitarString = guitarStrings[pid];
guitarString.updateSpacing(xSpacing, ySpacing);
}
}
redrawDotGrid();
}
/**
* Render everything on RAF.
* @param {number} delta - The delta.
*/
function render(delta) {
if (renderPause) { return; }
for (let pid in guitarStrings) {
if (guitarStrings.hasOwnProperty(pid)) {
guitarStrings[pid].render(delta);
}
}
}
/**
* Disable the strings.
*/
function disable() {
renderPause = true;
}
/**
* Enable the strings.
*/
function enable() {
renderPause = false;
}
/**
* Get all of the string data.
*/
function getData() {
allData.strings = [];
for (let pid in guitarStrings) {
if (guitarStrings.hasOwnProperty(pid)) {
var guitarString = guitarStrings[pid];
allData.strings.push(guitarString.getModel());
}
}
return allData;
}
return {
init,
animationCollapsed,
animationExpanded,
enable,
disable,
render,
resize,
startCountdown,
startRecording,
stopRecording,
getData,
loadData,
name: VIEW_NAME,
dataModel: GuitarDataModel,
backgroundColor: 0x1564c0,
getChannel: () => CHANNEL,
supportsPortrait: true,
requiresAntialiasing: true
};
};
})();
| {
"content_hash": "b8e039afb0d07631ca0060b811e82b19",
"timestamp": "",
"source": "github",
"line_count": 660,
"max_line_length": 117,
"avg_line_length": 26.48939393939394,
"alnum_prop": 0.5965795344048505,
"repo_name": "google/ioweb2015",
"id": "b8cbaf21b3afa93cef1f95fab51755f646c86996",
"size": "18099",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "experiment/app/views/GuitarView.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "99732"
},
{
"name": "GLSL",
"bytes": "6366"
},
{
"name": "Go",
"bytes": "276969"
},
{
"name": "HTML",
"bytes": "437367"
},
{
"name": "JavaScript",
"bytes": "644317"
},
{
"name": "Shell",
"bytes": "7652"
}
],
"symlink_target": ""
} |
package org.jephyr.activeobject.mailbox;
import java.util.Queue;
import java.util.concurrent.locks.LockSupport;
import static java.util.Objects.requireNonNull;
public final class QueueMailbox implements Mailbox {
private final Queue<Runnable> queue;
private volatile Thread thread;
public QueueMailbox(Queue<Runnable> queue) {
this.queue = requireNonNull(queue);
}
@Override
public void enqueue(Runnable task) {
queue.add(task);
LockSupport.unpark(thread);
}
@Override
public Runnable dequeue() throws InterruptedException {
thread = Thread.currentThread();
Runnable message;
while ((message = queue.poll()) == null) {
LockSupport.park();
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
return message;
}
}
| {
"content_hash": "1135f1167213fa43198b687fd849adef",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 59,
"avg_line_length": 24.054054054054053,
"alnum_prop": 0.6382022471910113,
"repo_name": "yngui/jephyr",
"id": "639e2a7d2d9c9c938d60934706daa7cdf350f599",
"size": "2032",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "activeobject/runtime/src/main/java/org/jephyr/activeobject/mailbox/QueueMailbox.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "2217410"
}
],
"symlink_target": ""
} |
#include <core/dependencies.h>
#include <core/allocator.h>
/*
* This is the allocator of POK. It remains in partition. You can configure it
* with POK_CONFIG_ALLOCATOR_MEMORY_SIZE (total amount of memory that can be allocated
* and with POK_CONFIG_ALLOCATOR_NB_SPACES (total amount of memory spaces that can be
* allocated (number of successive calls to malloc() or calloc() for example.
*/
#ifdef POK_NEEDS_ALLOCATOR
#ifndef POK_CONFIG_ALLOCATOR_MEMORY_SIZE
#define POK_CONFIG_ALLOCATOR_MEMORY_SIZE 16384
#endif
#ifndef POK_CONFIG_ALLOCATOR_NB_SPACES
#define POK_CONFIG_ALLOCATOR_NB_SPACES 100
#endif
#define POK_ALLOCATOR_CHECK_INIT \
if (pok_allocator_initialized == 0)\
{ \
uint32_t toto; \
for (toto = 0 ; toto < POK_CONFIG_ALLOCATOR_NB_SPACES ; toto++) \
{ \
pok_allocator_spaces[toto].start = 0; \
pok_allocator_spaces[toto].size = 0; \
pok_allocator_spaces[toto].allocated = 0; \
} \
pok_allocator_used_spaces = 1; \
pok_allocator_spaces[0].start = 0; /* Initialize the first space */ \
pok_allocator_spaces[0].allocated = 0; \
pok_allocator_spaces[0].size = POK_CONFIG_ALLOCATOR_MEMORY_SIZE;\
pok_allocator_initialized = 1; \
}
/* POK_ALLOCATOR_CHECK_INIT is a macro that performs initialization functions
* for memory allocator. It is called each time alloc or free functions are called
* but initialized the memory allocator only one time.
*/
typedef struct
{
size_t start;
size_t size;
bool_t allocated;
} pok_allocator_space_t;
uint8_t pok_allocator_memspace[POK_CONFIG_ALLOCATOR_MEMORY_SIZE];
pok_allocator_space_t pok_allocator_spaces[POK_CONFIG_ALLOCATOR_NB_SPACES];
uint32_t pok_allocator_used_spaces = 0;
bool_t pok_allocator_initialized = 0;
#ifdef POK_NEEDS_DEBUG
void pok_allocator_print_spaces ()
{
uint32_t space;
printf ("[LIBPOK] [ALLOCATOR] Used spaces = %d\n", pok_allocator_used_spaces);
for (space = 0 ; space < pok_allocator_used_spaces ; space++)
{
printf ("[LIBPOK] [ALLOCATOR] Space %d start=%d size=%d allocated=%d\n", space, pok_allocator_spaces[space].start, pok_allocator_spaces[space].size, pok_allocator_spaces[space].allocated);
}
}
#endif
void* pok_allocator_allocate (size_t needed_size)
{
POK_ALLOCATOR_CHECK_INIT
uint32_t space;
uint32_t new_space;
if (pok_allocator_used_spaces >= (POK_CONFIG_ALLOCATOR_NB_SPACES - 1))
{
#ifdef POK_NEEDS_DEBUG
printf ("[LIBPOK] [ALLOCATOR] Not enough space\n");
#endif
return NULL;
}
#ifdef POK_NEEDS_DEBUG
printf("Try to take a new memory chunk, required space=%d\n", needed_size);
#endif
for (space = 0 ; space < pok_allocator_used_spaces ; space++)
{
#ifdef POK_NEEDS_DEBUG
printf ("[LIBPOK] [ALLOCATOR] Look space %d, size %d, allocated=%d\n", space, pok_allocator_spaces[space].size, pok_allocator_spaces[space].allocated);
#endif
if ((pok_allocator_spaces[space].allocated == 0) && (pok_allocator_spaces[space].size >= needed_size))
{
if (pok_allocator_spaces[space].size == needed_size)
{
/*
* The space corresponds exactly to the requested memory space
*/
pok_allocator_spaces[space].allocated = 1;
#ifdef POK_NEEDS_DEBUG
printf ("[LIBPOK] [ALLOCATOR] Allocate directly space %d\n", space);
pok_allocator_print_spaces ();
#endif
return (&pok_allocator_memspace[pok_allocator_spaces[space].start]);
}
else
{
/*
* We need to split the block in two new blocks !
*/
new_space = pok_allocator_used_spaces;
pok_allocator_used_spaces = pok_allocator_used_spaces + 1;
pok_allocator_spaces[space].allocated = 1;
pok_allocator_spaces[new_space].allocated = 0;
pok_allocator_spaces[new_space].size = pok_allocator_spaces[space].size - needed_size;
pok_allocator_spaces[space].size = needed_size;
pok_allocator_spaces[new_space].start = pok_allocator_spaces[space].start + needed_size;
#ifdef POK_NEEDS_DEBUG
printf("[LIBPOK] [ALLOCATOR] Allocate space %d, CREATE NEW SPACE %d (size=%d)\n", space, new_space, pok_allocator_spaces[new_space].size);
pok_allocator_print_spaces ();
#endif
return (&pok_allocator_memspace[pok_allocator_spaces[space].start]);
}
}
}
#ifdef POK_NEEDS_DEBUG
printf ("[LIBPOK] [ALLOCATOR] Didn't find any space for that amount of memory (%d)\n", needed_size);
#endif
return NULL;
}
/*
* Delete a space
*/
void pok_allocator_delete_space (uint32_t space)
{
uint32_t tmp;
#ifdef POK_NEEDS_DEBUG
printf("[LIBPOK] [ALLOCATOR] Delete space %d\n", space);
#endif
for (tmp = space ; tmp < POK_CONFIG_ALLOCATOR_NB_SPACES ; tmp++)
{
pok_allocator_spaces[tmp].allocated = pok_allocator_spaces[tmp+1].allocated;
pok_allocator_spaces[tmp].size = pok_allocator_spaces[tmp+1].size;
pok_allocator_spaces[tmp].start = pok_allocator_spaces[tmp+1].start;
}
pok_allocator_used_spaces = pok_allocator_used_spaces - 1;
}
void pok_allocator_merge_space (uint32_t space)
{
uint32_t space2;
if (pok_allocator_used_spaces == 1)
{
return;
}
for (space2 = 0 ; space2 < pok_allocator_used_spaces ; space2++)
{
if ((space2 == space) || (pok_allocator_spaces[space2].allocated == 1))
{
continue;
}
/*
* In that case, space is a the end of space2. We can merge space in space2
*/
if (pok_allocator_spaces[space].start == (pok_allocator_spaces[space2].start + pok_allocator_spaces[space2].size))
{
#ifdef POK_NEEDS_DEBUG
// printf("[LIBPOK] [ALLOCATOR] Merge space %d, with %d\n", space, space2);
#endif
pok_allocator_spaces[space2].size = pok_allocator_spaces[space2].size + pok_allocator_spaces[space].size;
pok_allocator_delete_space (space);
pok_allocator_merge_space (space2);
return;
}
/*
* In that case, space2 is located at the end of space. We can merge space2 in space
*/
if (pok_allocator_spaces[space2].start == (pok_allocator_spaces[space].start + pok_allocator_spaces[space].size))
{
#ifdef POK_NEEDS_DEBUG
// printf("[LIBPOK] [ALLOCATOR] Merge space %d, with %d\n", space, space2);
#endif
pok_allocator_spaces[space].size = pok_allocator_spaces[space].size + pok_allocator_spaces[space2].size;
pok_allocator_delete_space (space2);
pok_allocator_merge_space (space2);
return;
}
}
}
void pok_allocator_free (void* ptr)
{
POK_ALLOCATOR_CHECK_INIT
uint32_t space;
for (space = 0 ; space < pok_allocator_used_spaces ; space++)
{
if (ptr == &pok_allocator_memspace[pok_allocator_spaces[space].start])
{
/* Here, we find the space to free */
pok_allocator_spaces[space].allocated = 0;
pok_allocator_merge_space (space);
#ifdef POK_NEEDS_DEBUG
pok_allocator_print_spaces ();
#endif
return;
}
}
#ifdef POK_NEEDS_DEBUG
printf("[LIBPOK] [ALLOCATOR] free() didn't find the space to free\n");
pok_allocator_print_spaces ();
#endif
return;
}
#endif
| {
"content_hash": "da5535c8b012f8afcffd5be9ead508df",
"timestamp": "",
"source": "github",
"line_count": 237,
"max_line_length": 194,
"avg_line_length": 32.24050632911393,
"alnum_prop": 0.6137940060201544,
"repo_name": "phipse/pok",
"id": "2c12d8d4c431dc120e1f8a1d49161d10565552a0",
"size": "8186",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libpok/core/allocator.c",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Ada",
"bytes": "34095"
},
{
"name": "Assembly",
"bytes": "34154"
},
{
"name": "C",
"bytes": "1537534"
},
{
"name": "C++",
"bytes": "59632"
},
{
"name": "Objective-C",
"bytes": "2742"
},
{
"name": "Perl",
"bytes": "73802"
},
{
"name": "Shell",
"bytes": "5423"
},
{
"name": "TeX",
"bytes": "114139"
},
{
"name": "eC",
"bytes": "79"
}
],
"symlink_target": ""
} |
<?php
namespace PSX\Framework\Tests\Dispatch;
use PHPUnit\Framework\TestCase;
use PSX\Framework\Loader\Context;
use PSX\Framework\Test\Environment;
use PSX\Http\Filter\CORS;
/**
* ControllerFactoryTest
*
* @author Christoph Kappestein <[email protected]>
* @license http://www.apache.org/licenses/LICENSE-2.0
* @link http://phpsx.org
*/
class ControllerFactoryTest extends TestCase
{
public function testGetController()
{
$controller = $this->getController(DummyController::class);
$this->assertTrue(is_array($controller));
$this->assertInstanceOf(CORS::class, $controller[0]);
$this->assertInstanceOf(DummyController::class, $controller[1]);
}
public function testGetControllerInvalid()
{
$this->expectException(\ReflectionException::class);
$this->getController('Foo\Bar');
}
protected function getController($className)
{
$factory = Environment::getService('controller_factory');
return $factory->getController($className, new Context());
}
}
| {
"content_hash": "b78cb0bbd6745b3fa0f78dfd1956a57c",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 72,
"avg_line_length": 25.666666666666668,
"alnum_prop": 0.6910946196660482,
"repo_name": "apioo/psx-framework",
"id": "8aaea0fe7839276b5eddf1537ae03cc111615f37",
"size": "1855",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/Dispatch/ControllerFactoryTest.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "334"
},
{
"name": "PHP",
"bytes": "715075"
}
],
"symlink_target": ""
} |
package com.haulmont.cuba.web.gui.components;
import com.google.common.base.Strings;
import com.haulmont.bali.events.Subscription;
import com.haulmont.bali.util.Preconditions;
import com.haulmont.cuba.core.global.AppBeans;
import com.haulmont.cuba.gui.ComponentsHelper;
import com.haulmont.cuba.gui.app.security.role.edit.UiPermissionDescriptor;
import com.haulmont.cuba.gui.app.security.role.edit.UiPermissionValue;
import com.haulmont.cuba.gui.components.*;
import com.haulmont.cuba.gui.components.sys.FrameImplementation;
import com.haulmont.cuba.gui.data.DsContext;
import com.haulmont.cuba.gui.data.impl.DsContextImplementation;
import com.haulmont.cuba.gui.icons.Icons;
import com.haulmont.cuba.gui.screen.UiControllerUtils;
import com.haulmont.cuba.gui.screen.compatibility.LegacyFrame;
import com.haulmont.cuba.gui.settings.Settings;
import com.haulmont.cuba.gui.sys.TestIdManager;
import com.haulmont.cuba.gui.xml.layout.ComponentLoader;
import com.haulmont.cuba.gui.xml.layout.ComponentsFactory;
import com.haulmont.cuba.web.AppUI;
import com.haulmont.cuba.web.gui.icons.IconResolver;
import com.haulmont.cuba.web.widgets.CubaTabSheet;
import com.vaadin.server.Resource;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Element;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.*;
import java.util.function.Consumer;
import static com.haulmont.cuba.gui.ComponentsHelper.walkComponents;
public class WebTabSheet extends WebAbstractComponent<CubaTabSheet>
implements TabSheet, UiPermissionAware, SupportsChildrenSelection {
protected boolean postInitTaskAdded;
protected boolean componentTabChangeListenerInitialized;
protected ComponentLoader.Context context;
protected Map<String, Tab> tabs = new LinkedHashMap<>();
protected Map<com.vaadin.ui.Component, ComponentDescriptor> tabMapping = new LinkedHashMap<>();
protected Set<com.vaadin.ui.Component> lazyTabs; // lazily initialized set
public WebTabSheet() {
component = createComponent();
component.setCloseHandler(new DefaultCloseHandler());
}
protected CubaTabSheet createComponent() {
return new CubaTabSheet();
}
protected Set<com.vaadin.ui.Component> getLazyTabs() {
if (lazyTabs == null) {
lazyTabs = new LinkedHashSet<>();
}
return lazyTabs;
}
@Override
public void add(Component component) {
throw new UnsupportedOperationException();
}
@Override
public void remove(Component component) {
throw new UnsupportedOperationException();
}
@Override
public void removeAll() {
throw new UnsupportedOperationException();
}
@Override
public Component getOwnComponent(String id) {
Preconditions.checkNotNullArgument(id);
return tabMapping.values().stream()
.filter(cd -> Objects.equals(id, cd.component.getId()))
.map(cd -> cd.component)
.findFirst()
.orElse(null);
}
@Nullable
@Override
public Component getComponent(String id) {
return ComponentsHelper.getComponent(this, id);
}
@Override
public Collection<Component> getOwnComponents() {
List<Component> componentList = new ArrayList<>();
for (ComponentDescriptor cd : tabMapping.values()) {
componentList.add(cd.component);
}
return componentList;
}
@Override
public Collection<Component> getComponents() {
return ComponentsHelper.getComponents(this);
}
@Override
public void applyPermission(UiPermissionDescriptor permissionDescriptor) {
Preconditions.checkNotNullArgument(permissionDescriptor);
final String subComponentId = permissionDescriptor.getSubComponentId();
final TabSheet.Tab tab = getTab(subComponentId);
if (tab != null) {
UiPermissionValue permissionValue = permissionDescriptor.getPermissionValue();
if (permissionValue == UiPermissionValue.HIDE) {
tab.setVisible(false);
} else if (permissionValue == UiPermissionValue.READ_ONLY) {
tab.setEnabled(false);
}
} else {
LoggerFactory.getLogger(WebTabSheet.class).info(String.format("Couldn't find component %s in window %s",
subComponentId, permissionDescriptor.getScreenId()));
}
}
@Override
public void focus() {
component.focus();
}
@Override
public int getTabIndex() {
return component.getTabIndex();
}
@Override
public void setTabIndex(int tabIndex) {
component.setTabIndex(tabIndex);
}
@Override
public void setChildSelected(Component childComponent) {
component.setSelectedTab(childComponent.unwrap(com.vaadin.ui.Component.class));
}
@Override
public boolean isChildSelected(Component component) {
return getSelectedTab().getComponent() == component;
}
protected class Tab implements TabSheet.Tab {
private String name;
private Component tabComponent;
private TabCloseHandler closeHandler;
private String icon;
public Tab(String name, Component tabComponent) {
this.name = name;
this.tabComponent = tabComponent;
}
protected com.vaadin.ui.TabSheet.Tab getVaadinTab() {
com.vaadin.ui.Component composition = WebComponentsHelper.getComposition(tabComponent);
return WebTabSheet.this.component.getTab(composition);
}
public Component getComponent() {
return tabComponent;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getCaption() {
return getVaadinTab().getCaption();
}
@Override
public void setCaption(String caption) {
getVaadinTab().setCaption(caption);
}
@Override
public boolean isEnabled() {
return getVaadinTab().isEnabled();
}
@Override
public void setEnabled(boolean enabled) {
getVaadinTab().setEnabled(enabled);
}
@Override
public boolean isVisible() {
return getVaadinTab().isVisible();
}
@Override
public void setVisible(boolean visible) {
getVaadinTab().setVisible(visible);
}
@Override
public boolean isClosable() {
return getVaadinTab().isClosable();
}
@Override
public void setClosable(boolean closable) {
getVaadinTab().setClosable(closable);
}
@Override
public boolean isDetachable() {
return false;
}
@Override
public void setDetachable(boolean detachable) {
}
@Override
public TabCloseHandler getCloseHandler() {
return closeHandler;
}
@Override
public void setCloseHandler(TabCloseHandler tabCloseHandler) {
this.closeHandler = tabCloseHandler;
}
@Override
public void setStyleName(String styleName) {
getVaadinTab().setStyleName(styleName);
}
@Override
public String getStyleName() {
return getVaadinTab().getStyleName();
}
@Override
public String getIcon() {
return icon;
}
@Override
public void setIcon(String icon) {
this.icon = icon;
if (!StringUtils.isEmpty(icon)) {
Resource iconResource = AppBeans.get(IconResolver.class) // todo replace
.getIconResource(this.icon);
getVaadinTab().setIcon(iconResource);
} else {
getVaadinTab().setIcon(null);
}
}
@Override
public void setIconFromSet(Icons.Icon icon) {
String iconPath = AppBeans.get(Icons.class) // todo replace
.get(icon);
setIcon(iconPath);
}
@Override
public void setDescription(String description) {
getVaadinTab().setDescription(description);
}
@Override
public String getDescription() {
return getVaadinTab().getDescription();
}
}
@Override
public TabSheet.Tab addTab(String name, Component childComponent) {
if (childComponent.getParent() != null && childComponent.getParent() != this) {
throw new IllegalStateException("Component already has parent");
}
final Tab tab = new Tab(name, childComponent);
this.tabs.put(name, tab);
final com.vaadin.ui.Component tabComponent = WebComponentsHelper.getComposition(childComponent);
tabComponent.setSizeFull();
tabMapping.put(tabComponent, new ComponentDescriptor(name, childComponent));
com.vaadin.ui.TabSheet.Tab tabControl = this.component.addTab(tabComponent);
if (Strings.isNullOrEmpty(tab.getCaption())) {
tab.setCaption(name);
}
if (getDebugId() != null) {
this.component.setTestId(tabControl,
AppUI.getCurrent().getTestIdManager().getTestId(getDebugId() + "." + name));
}
if (AppUI.getCurrent().isTestMode()) {
this.component.setCubaId(tabControl, name);
}
if (frame != null) {
if (childComponent instanceof BelongToFrame
&& ((BelongToFrame) childComponent).getFrame() == null) {
((BelongToFrame) childComponent).setFrame(frame);
} else {
((FrameImplementation) frame).registerComponent(childComponent);
}
}
childComponent.setParent(this);
return tab;
}
@Override
public void setDebugId(String id) {
super.setDebugId(id);
String debugId = getDebugId();
if (debugId != null) {
TestIdManager testIdManager = AppUI.getCurrent().getTestIdManager();
for (Map.Entry<com.vaadin.ui.Component, ComponentDescriptor> tabEntry : tabMapping.entrySet()) {
com.vaadin.ui.Component tabComponent = tabEntry.getKey();
com.vaadin.ui.TabSheet.Tab tab = component.getTab(tabComponent);
ComponentDescriptor componentDescriptor = tabEntry.getValue();
String name = componentDescriptor.name;
component.setTestId(tab, testIdManager.getTestId(debugId + "." + name));
}
}
}
@Override
public TabSheet.Tab addLazyTab(String name, Element descriptor, ComponentLoader loader) {
ComponentsFactory cf = AppBeans.get(ComponentsFactory.NAME); // todo replace
CssLayout tabContent = cf.createComponent(CssLayout.NAME);
tabContent.setStyleName("c-tabsheet-lazytab");
tabContent.setSizeFull();
Tab tab = new Tab(name, tabContent);
tabs.put(name, tab);
com.vaadin.ui.Component tabComponent = tabContent.unwrapComposition(com.vaadin.ui.Component.class);
tabMapping.put(tabComponent, new ComponentDescriptor(name, tabContent));
com.vaadin.ui.TabSheet.Tab tabControl = this.component.addTab(tabComponent);
getLazyTabs().add(tabComponent);
this.component.addSelectedTabChangeListener(new LazyTabChangeListener(tabContent, descriptor, loader));
context = loader.getContext();
if (!postInitTaskAdded) {
context.addPostInitTask((c, w) ->
initComponentTabChangeListener()
);
postInitTaskAdded = true;
}
if (getDebugId() != null) {
this.component.setTestId(tabControl,
AppUI.getCurrent().getTestIdManager().getTestId(getDebugId() + "." + name));
}
if (AppUI.getCurrent().isTestMode()) {
this.component.setCubaId(tabControl, name);
}
tabContent.setFrame(context.getFrame());
return tab;
}
@Override
public void removeTab(String name) {
Tab tab = tabs.get(name);
if (tab == null) {
throw new IllegalStateException(String.format("Can't find tab '%s'", name));
}
tabs.remove(name);
Component childComponent = tab.getComponent();
com.vaadin.ui.Component vComponent = WebComponentsHelper.unwrap(childComponent);
this.component.removeComponent(vComponent);
tabMapping.remove(vComponent);
childComponent.setParent(null);
}
@Override
public void removeAllTabs() {
tabMapping.clear();
component.removeAllComponents();
List<Tab> currentTabs = new ArrayList<>(tabs.values());
tabs.clear();
for (Tab tab : currentTabs) {
Component childComponent = tab.getComponent();
childComponent.setParent(null);
}
}
@Override
public void setFrame(Frame frame) {
super.setFrame(frame);
if (frame != null) {
for (ComponentDescriptor descriptor : tabMapping.values()) {
Component childComponent = descriptor.getComponent();
if (childComponent instanceof BelongToFrame
&& ((BelongToFrame) childComponent).getFrame() == null) {
((BelongToFrame) childComponent).setFrame(frame);
}
}
}
}
@Override
public Tab getSelectedTab() {
final com.vaadin.ui.Component component = this.component.getSelectedTab();
if (component == null) {
return null;
}
ComponentDescriptor tabDescriptor = tabMapping.get(component);
if (tabDescriptor == null) {
return null;
}
return tabs.get(tabDescriptor.getName());
}
@Override
public void setSelectedTab(TabSheet.Tab tab) {
Component tabComponent = ((Tab) tab).getComponent();
com.vaadin.ui.Component vTabContent = tabComponent.unwrap(com.vaadin.ui.Component.class);
this.component.setSelectedTab(vTabContent);
}
@Override
public void setSelectedTab(String name) {
Tab tab = tabs.get(name);
if (tab == null) {
throw new IllegalStateException(String.format("Can't find tab '%s'", name));
}
Component tabComponent = tab.getComponent();
com.vaadin.ui.Component vTabContent = tabComponent.unwrap(com.vaadin.ui.Component.class);
this.component.setSelectedTab(vTabContent);
}
@Override
public TabSheet.Tab getTab(String name) {
return tabs.get(name);
}
@Override
public Component getTabComponent(String name) {
Tab tab = tabs.get(name);
return tab.getComponent();
}
@Override
public Collection<TabSheet.Tab> getTabs() {
//noinspection unchecked
return (Collection) tabs.values();
}
@Override
public boolean isTabCaptionsAsHtml() {
return component.isTabCaptionsAsHtml();
}
@Override
public void setTabCaptionsAsHtml(boolean tabCaptionsAsHtml) {
component.setTabCaptionsAsHtml(tabCaptionsAsHtml);
}
@Override
public boolean isTabsVisible() {
return component.isTabsVisible();
}
@Override
public void setTabsVisible(boolean tabsVisible) {
component.setTabsVisible(tabsVisible);
}
private void initComponentTabChangeListener() {
// init component SelectedTabChangeListener only when needed, making sure it is
// after all lazy tabs listeners
if (!componentTabChangeListenerInitialized) {
component.addSelectedTabChangeListener(event -> {
if (context != null) {
context.executeInjectTasks();
context.executeInitTasks();
}
// Fire GUI listener
fireTabChanged(new SelectedTabChangeEvent(WebTabSheet.this,
getSelectedTab(), event.isUserOriginated()));
// Execute outstanding post init tasks after GUI listener.
// We suppose that context.executePostInitTasks() executes a task once and then remove it from task list.
if (context != null) {
context.executePostInitTasks();
}
Window window = ComponentsHelper.getWindow(WebTabSheet.this);
if (window != null) {
if (window.getFrameOwner() instanceof LegacyFrame) {
DsContext dsContext = ((LegacyFrame) window.getFrameOwner()).getDsContext();
if (dsContext != null) {
((DsContextImplementation) dsContext).resumeSuspended();
}
}
} else {
LoggerFactory.getLogger(WebTabSheet.class).warn("Please specify Frame for TabSheet");
}
});
componentTabChangeListenerInitialized = true;
}
}
@Override
public Subscription addSelectedTabChangeListener(Consumer<SelectedTabChangeEvent> listener) {
initComponentTabChangeListener();
return getEventHub().subscribe(SelectedTabChangeEvent.class, listener);
}
@Override
public void removeSelectedTabChangeListener(Consumer<SelectedTabChangeEvent> listener) {
unsubscribe(SelectedTabChangeEvent.class, listener);
}
protected void fireTabChanged(SelectedTabChangeEvent event) {
publish(SelectedTabChangeEvent.class, event);
}
protected class LazyTabChangeListener implements com.vaadin.ui.TabSheet.SelectedTabChangeListener {
protected ComponentContainer tabContent;
protected Element descriptor;
protected ComponentLoader loader;
public LazyTabChangeListener(ComponentContainer tabContent, Element descriptor, ComponentLoader loader) {
this.tabContent = tabContent;
this.descriptor = descriptor;
this.loader = loader;
}
@Override
public void selectedTabChange(com.vaadin.ui.TabSheet.SelectedTabChangeEvent event) {
com.vaadin.ui.Component selectedTab = WebTabSheet.this.component.getSelectedTab();
com.vaadin.ui.Component tabComponent = tabContent.unwrap(com.vaadin.ui.Component.class);
if (selectedTab == tabComponent && getLazyTabs().remove(tabComponent)) {
loader.createComponent();
Component lazyContent = loader.getResultComponent();
tabContent.add(lazyContent);
com.vaadin.ui.Component impl = WebComponentsHelper.getComposition(lazyContent);
impl.setSizeFull();
lazyContent.setParent(WebTabSheet.this);
loader.loadComponent();
WebAbstractComponent contentComponent = (WebAbstractComponent) lazyContent;
contentComponent.setIcon(null);
contentComponent.setCaption(null);
contentComponent.setDescription(null);
Window window = ComponentsHelper.getWindow(WebTabSheet.this);
if (window != null) {
Settings settings = UiControllerUtils.getSettings(window.getFrameOwner());
if (settings != null) {
walkComponents(tabContent, (settingsComponent, name) -> {
if (settingsComponent.getId() != null
&& settingsComponent instanceof HasSettings) {
Element e = settings.get(name);
((HasSettings) settingsComponent).applySettings(e);
if (component instanceof HasPresentations
&& e.attributeValue("presentation") != null) {
final String def = e.attributeValue("presentation");
if (!StringUtils.isEmpty(def)) {
UUID defaultId = UUID.fromString(def);
((HasPresentations) component).applyPresentationAsDefault(defaultId);
}
}
}
});
}
}
}
}
}
protected static class ComponentDescriptor {
protected Component component;
protected String name;
public ComponentDescriptor(String name, Component component) {
this.name = name;
this.component = component;
}
public Component getComponent() {
return component;
}
public String getName() {
return name;
}
}
protected class DefaultCloseHandler implements com.vaadin.ui.TabSheet.CloseHandler {
private static final long serialVersionUID = -6766617382191585632L;
@Override
public void onTabClose(com.vaadin.ui.TabSheet tabsheet, com.vaadin.ui.Component tabContent) {
// have no other way to get tab from tab content
for (Tab tab : tabs.values()) {
Component currentTabContent = tab.getComponent();
com.vaadin.ui.Component tabComponent = currentTabContent.unwrap(com.vaadin.ui.Component.class);
if (tabComponent == tabContent) {
if (tab.isClosable()) {
doHandleCloseTab(tab);
return;
}
}
}
}
protected void doHandleCloseTab(Tab tab) {
if (tab.getCloseHandler() != null) {
tab.getCloseHandler().onTabClose(tab);
} else {
removeTab(tab.getName());
}
}
}
} | {
"content_hash": "36c38dd51d046f1ffdea9d3cddf2fb9f",
"timestamp": "",
"source": "github",
"line_count": 662,
"max_line_length": 121,
"avg_line_length": 33.56948640483384,
"alnum_prop": 0.6088736894208703,
"repo_name": "dimone-kun/cuba",
"id": "eb72ff64321aa278bf8cce0c38d52d40e9e00750",
"size": "22827",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/web/src/com/haulmont/cuba/web/gui/components/WebTabSheet.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "77"
},
{
"name": "CSS",
"bytes": "262124"
},
{
"name": "FreeMarker",
"bytes": "3996"
},
{
"name": "GAP",
"bytes": "33866"
},
{
"name": "Groovy",
"bytes": "402320"
},
{
"name": "HTML",
"bytes": "6405"
},
{
"name": "Java",
"bytes": "18662263"
},
{
"name": "PLSQL",
"bytes": "30350"
},
{
"name": "PLpgSQL",
"bytes": "1723"
},
{
"name": "SQLPL",
"bytes": "93321"
},
{
"name": "Shell",
"bytes": "88"
},
{
"name": "XSLT",
"bytes": "63258"
}
],
"symlink_target": ""
} |
<?php
namespace League\Glide;
use Hamcrest\Matchers;
use InvalidArgumentException;
use League\Glide\Filesystem\FileNotFoundException;
use League\Glide\Filesystem\FilesystemException;
use Mockery;
use PHPUnit\Framework\TestCase;
class ServerTest extends TestCase
{
private $server;
public function setUp(): void
{
$response = Mockery::mock('Psr\Http\Message\ResponseInterface');
$responseFactory = Mockery::mock('League\Glide\Responses\ResponseFactoryInterface');
$responseFactory
->shouldReceive('create')
->andReturn($response)
->shouldReceive('send')
->andReturnUsing(function () {
echo 'content';
});
$this->server = new Server(
Mockery::mock('League\Flysystem\FilesystemOperator'),
Mockery::mock('League\Flysystem\FilesystemOperator'),
Mockery::mock('League\Glide\Api\ApiInterface'),
$responseFactory
);
}
public function tearDown(): void
{
Mockery::close();
}
public function testCreateInstance()
{
$this->assertInstanceOf('League\Glide\Server', $this->server);
}
public function testSetSource()
{
$this->server->setSource(Mockery::mock('League\Flysystem\FilesystemOperator'));
$this->assertInstanceOf('League\Flysystem\FilesystemOperator', $this->server->getSource());
}
public function testGetSource()
{
$this->assertInstanceOf('League\Flysystem\FilesystemOperator', $this->server->getSource());
}
public function testSetSourcePathPrefix()
{
$this->server->setSourcePathPrefix('img/');
$this->assertEquals('img', $this->server->getSourcePathPrefix());
}
public function testGetSourcePathPrefix()
{
$this->assertEquals('', $this->server->getSourcePathPrefix());
}
public function testGetSourcePath()
{
$this->assertEquals('image.jpg', $this->server->getSourcePath('image.jpg'));
}
public function testGetSourcePathWithBaseUrl()
{
$this->server->setBaseUrl('img/');
$this->assertEquals('image.jpg', $this->server->getSourcePath('img/image.jpg'));
// Test for a bug where if the path starts with the same substring as the base url, the source
// path would trim the base url off the filename. eg, the following would've returned 'ur.jpg'
$this->assertEquals('imgur.jpg', $this->server->getSourcePath('imgur.jpg'));
}
public function testGetSourcePathWithPrefix()
{
$this->server->setSourcePathPrefix('img/');
$this->assertEquals('img/image.jpg', $this->server->getSourcePath('image.jpg'));
}
public function testGetSourcePathWithMissingPath()
{
$this->expectException(FileNotFoundException::class);
$this->expectExceptionMessage('Image path missing.');
$this->server->getSourcePath('');
}
public function testGetSourcePathWithEncodedEntities()
{
$this->assertEquals('an image.jpg', $this->server->getSourcePath('an%20image.jpg'));
}
public function testSourceFileExists()
{
$this->server->setSource(Mockery::mock('League\Flysystem\FilesystemOperator', function ($mock) {
$mock->shouldReceive('fileExists')->with('image.jpg')->andReturn(true)->once();
}));
$this->assertTrue($this->server->sourceFileExists('image.jpg'));
}
public function testSetBaseUrl()
{
$this->server->setBaseUrl('img/');
$this->assertEquals('img', $this->server->getBaseUrl());
}
public function testGetBaseUrl()
{
$this->assertEquals('', $this->server->getBaseUrl());
}
public function testSetCache()
{
$this->server->setCache(Mockery::mock('League\Flysystem\FilesystemOperator'));
$this->assertInstanceOf('League\Flysystem\FilesystemOperator', $this->server->getCache());
}
public function testGetCache()
{
$this->assertInstanceOf('League\Flysystem\FilesystemOperator', $this->server->getCache());
}
public function testSetCachePathPrefix()
{
$this->server->setCachePathPrefix('img/');
$this->assertEquals('img', $this->server->getCachePathPrefix());
}
public function testGetCachePathPrefix()
{
$this->assertEquals('', $this->server->getCachePathPrefix());
}
public function testSetInvalidTempDir()
{
$this->expectException(\InvalidArgumentException::class);
$this->server->setTempDir('/invalid/path');
}
public function testSetGetTempDir()
{
$this->server->setTempDir(__DIR__);
$this->assertSame(__DIR__.DIRECTORY_SEPARATOR, $this->server->getTempDir());
}
public function testSetGroupCacheInFolders()
{
$this->server->setGroupCacheInFolders(false);
$this->assertFalse($this->server->getGroupCacheInFolders());
}
public function testGetGroupCacheInFolders()
{
$this->assertTrue($this->server->getGroupCacheInFolders());
}
public function testSetCacheWithFileExtensions()
{
$this->server->setCacheWithFileExtensions(true);
$this->assertTrue($this->server->getCacheWithFileExtensions());
}
public function testGetCacheWithFileExtensions()
{
$this->assertFalse($this->server->getCacheWithFileExtensions());
}
public function testGetCachePath()
{
$this->assertEquals(
'image.jpg/e863e008b6f09807c3b0aa3805bc9c63',
$this->server->getCachePath('image.jpg', ['w' => '100'])
);
}
public function testGetCachePathWithNoFolderGrouping()
{
$this->server->setGroupCacheInFolders(false);
$this->assertEquals(
'e863e008b6f09807c3b0aa3805bc9c63',
$this->server->getCachePath('image.jpg', ['w' => '100'])
);
}
public function testGetCachePathWithPrefix()
{
$this->server->setCachePathPrefix('img/');
$this->assertEquals('img/image.jpg/75094881e9fd2b93063d6a5cb083091c', $this->server->getCachePath('image.jpg', []));
}
public function testGetCachePathWithSourcePrefix()
{
$this->server->setSourcePathPrefix('img/');
$this->assertEquals('image.jpg/75094881e9fd2b93063d6a5cb083091c', $this->server->getCachePath('image.jpg', []));
}
public function testGetCachePathWithExtension()
{
$this->server->setCacheWithFileExtensions(true);
$this->assertEquals('image.jpg/75094881e9fd2b93063d6a5cb083091c.jpg', $this->server->getCachePath('image.jpg', []));
}
public function testGetCachePathWithExtensionAndFmParam()
{
$this->server->setCacheWithFileExtensions(true);
$this->assertEquals('image.jpg/eb6091e07fb06219634a3c82afb88239.gif', $this->server->getCachePath('image.jpg', ['fm' => 'gif']));
}
public function testGetCachePathWithExtensionAndPjpgFmParam()
{
$this->server->setCacheWithFileExtensions(true);
$this->assertEquals('image.jpg/ce5cb75f4a37dec0a0a49854e94123eb.jpg', $this->server->getCachePath('image.jpg', ['fm' => 'pjpg']));
}
public function testGetCachePathWithExtensionAndFmFromDefaults()
{
$this->server->setCacheWithFileExtensions(true);
$this->server->setDefaults(['fm' => 'gif']);
$this->assertEquals('image.jpg/eb6091e07fb06219634a3c82afb88239.gif', $this->server->getCachePath('image.jpg', []));
}
public function testGetCachePathWithExtensionAndPjpgFmFromDefaults()
{
$this->server->setCacheWithFileExtensions(true);
$this->server->setDefaults(['fm' => 'pjpg']);
$this->assertEquals('image.jpg/ce5cb75f4a37dec0a0a49854e94123eb.jpg', $this->server->getCachePath('image.jpg', []));
}
public function testGetCachePathWithExtensionAndFmFromPreset()
{
$this->server->setCacheWithFileExtensions(true);
$this->server->setPresets(['gif' => [
'fm' => 'gif',
]]);
$this->assertEquals('image.jpg/eb6091e07fb06219634a3c82afb88239.gif', $this->server->getCachePath('image.jpg', ['p' => 'gif']));
}
public function testGetCachePathWithExtensionAndPjpgFmFromPreset()
{
$this->server->setCacheWithFileExtensions(true);
$this->server->setPresets(['pjpg' => [
'fm' => 'pjpg',
]]);
$this->assertEquals('image.jpg/ce5cb75f4a37dec0a0a49854e94123eb.jpg', $this->server->getCachePath('image.jpg', ['p' => 'pjpg']));
}
public function testCacheFileExists()
{
$this->server->setCache(Mockery::mock('League\Flysystem\FilesystemOperator', function ($mock) {
$mock->shouldReceive('fileExists')->with('image.jpg/75094881e9fd2b93063d6a5cb083091c')->andReturn(true)->once();
}));
$this->assertTrue($this->server->cacheFileExists('image.jpg', []));
}
public function testDeleteCache()
{
$this->server->setCache(Mockery::mock('League\Flysystem\FilesystemOperator', function ($mock) {
$mock->shouldReceive('deleteDirectory')->with('image.jpg')->andReturn(true)->once();
}));
$this->assertTrue($this->server->deleteCache('image.jpg', []));
}
public function testDeleteCacheWithGroupCacheInFoldersDisabled()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Deleting cached image manipulations is not possible when grouping cache into folders is disabled.');
$this->server->setGroupCacheInFolders(false);
$this->server->deleteCache('image.jpg', []);
}
public function testSetApi()
{
$api = Mockery::mock('League\Glide\Api\ApiInterface');
$this->server->setApi($api);
$this->assertInstanceOf('League\Glide\Api\ApiInterface', $this->server->getApi());
}
public function testGetApi()
{
$this->assertInstanceOf('League\Glide\Api\ApiInterface', $this->server->getApi());
}
public function testSetDefaults()
{
$defaults = [
'fm' => 'jpg',
];
$this->server->setDefaults($defaults);
$this->assertSame($defaults, $this->server->getDefaults());
}
public function testGetDefaults()
{
$this->testSetDefaults();
}
public function testSetPresets()
{
$presets = [
'small' => [
'w' => '200',
'h' => '200',
'fit' => 'crop',
],
];
$this->server->setPresets($presets);
$this->assertSame($presets, $this->server->getPresets());
}
public function testGetPresets()
{
$this->testSetPresets();
}
public function testGetAllParams()
{
$this->server->setDefaults([
'fm' => 'jpg',
]);
$this->server->setPresets([
'small' => [
'w' => '200',
'h' => '200',
'fit' => 'crop',
],
]);
$all_params = $this->server->getAllParams([
'w' => '100',
'p' => 'small',
]);
$this->assertSame([
'fm' => 'jpg',
'w' => '100',
'h' => '200',
'fit' => 'crop',
'p' => 'small',
], $all_params);
}
public function testSetResponseFactory()
{
$this->server->setResponseFactory(Mockery::mock('League\Glide\Responses\ResponseFactoryInterface'));
$this->assertInstanceOf(
'League\Glide\Responses\ResponseFactoryInterface',
$this->server->getResponseFactory()
);
}
public function testGetResponseFactory()
{
$this->testSetResponseFactory();
}
public function testGetImageResponse()
{
$this->server->setResponseFactory(Mockery::mock('League\Glide\Responses\ResponseFactoryInterface', function ($mock) {
$mock->shouldReceive('create')->andReturn(Mockery::mock('Psr\Http\Message\ResponseInterface'));
}));
$this->server->setCache(Mockery::mock('League\Flysystem\FilesystemOperator', function ($mock) {
$mock->shouldReceive('fileExists')->andReturn(true);
}));
$this->assertInstanceOf(
'Psr\Http\Message\ResponseInterface',
$this->server->getImageResponse('image.jpg', [])
);
}
public function testGetImageResponseWithoutResponseFactory()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Unable to get image response, no response factory defined.');
$this->server->getImageResponse('image.jpg', []);
}
public function testGetImageAsBase64()
{
$this->server->setCache(Mockery::mock('League\Flysystem\FilesystemOperator', function ($mock) {
$mock->shouldReceive('fileExists')->andReturn(true);
$mock->shouldReceive('mimeType')->andReturn('image/jpeg');
$mock->shouldReceive('read')->andReturn('content')->once();
}));
$this->assertEquals(
'data:image/jpeg;base64,Y29udGVudA==',
$this->server->getImageAsBase64('image.jpg', [])
);
}
public function testGetImageAsBase64WithUnreadableSource()
{
$this->expectException(FilesystemException::class);
$this->expectExceptionMessage('Could not read the image `image.jpg/75094881e9fd2b93063d6a5cb083091c`.');
$this->server->setCache(Mockery::mock('League\Flysystem\FilesystemOperator', function ($mock) {
$mock->shouldReceive('fileExists')->andReturn(true);
$mock->shouldReceive('mimeType')->andReturn('image/jpeg');
$mock->shouldReceive('read')->andThrow('League\Flysystem\UnableToReadFile')->once();
}));
$this->server->getImageAsBase64('image.jpg', []);
}
/**
* @runInSeparateProcess
*/
public function testOutputImage()
{
$this->server->setCache(Mockery::mock('League\Flysystem\FilesystemOperator', function ($mock) {
$mock->shouldReceive('fileExists')->andReturn(true);
$mock->shouldReceive('mimeType')->andReturn('image/jpeg');
$mock->shouldReceive('fileSize')->andReturn(0);
$file = tmpfile();
fwrite($file, 'content');
$mock->shouldReceive('readStream')->andReturn($file);
}));
ob_start();
$response = $this->server->outputImage('image.jpg', []);
$content = ob_get_clean();
$this->assertNull($response);
$this->assertEquals('content', $content);
}
public function testMakeImageFromSource()
{
$this->server->setSource(Mockery::mock('League\Flysystem\FilesystemOperator', function ($mock) {
$mock->shouldReceive('fileExists')->andReturn(true)->once();
$mock->shouldReceive('read')->andReturn('content')->once();
}));
$this->server->setCache(Mockery::mock('League\Flysystem\FilesystemOperator', function ($mock) {
$mock->shouldReceive('fileExists')->andReturn(false)->once();
$mock->shouldReceive('write')->with('image.jpg/75094881e9fd2b93063d6a5cb083091c', 'content')->once();
}));
$this->server->setApi(Mockery::mock('League\Glide\Api\ApiInterface', function ($mock) {
$tmpDirPattern = Matchers::matchesPattern('~^'.sys_get_temp_dir().'.*~');
$mock->shouldReceive('run')->with($tmpDirPattern, [])->andReturn('content')->once();
}));
$this->assertEquals(
'image.jpg/75094881e9fd2b93063d6a5cb083091c',
$this->server->makeImage('image.jpg', [])
);
}
public function testMakeImageFromSourceWithCustomTmpDir()
{
$this->server->setSource(Mockery::mock('League\Flysystem\FilesystemOperator', function ($mock) {
$mock->shouldReceive('fileExists')->andReturn(true)->once();
$mock->shouldReceive('read')->andReturn('content')->once();
}));
$this->server->setCache(Mockery::mock('League\Flysystem\FilesystemOperator', function ($mock) {
$mock->shouldReceive('fileExists')->andReturn(false)->once();
$mock->shouldReceive('write')->with('image.jpg/75094881e9fd2b93063d6a5cb083091c', 'content')->once();
}));
$this->server->setTempDir(__DIR__);
$this->server->setApi(Mockery::mock('League\Glide\Api\ApiInterface', function ($mock) {
$tmpDirPattern = Matchers::matchesPattern('~^'.__DIR__.'.*~');
$mock->shouldReceive('run')->with($tmpDirPattern, [])->andReturn('content')->once();
}));
$this->assertEquals(
'image.jpg/75094881e9fd2b93063d6a5cb083091c',
$this->server->makeImage('image.jpg', [])
);
}
public function testMakeImageFromCache()
{
$this->server->setCache(Mockery::mock('League\Flysystem\FilesystemOperator', function ($mock) {
$mock->shouldReceive('fileExists')->andReturn(true);
}));
$this->assertEquals(
'image.jpg/75094881e9fd2b93063d6a5cb083091c',
$this->server->makeImage('image.jpg', [])
);
}
public function testMakeImageFromSourceThatDoesNotExist()
{
$this->expectException(FileNotFoundException::class);
$this->expectExceptionMessage('Could not find the image `image.jpg`.');
$this->server->setSource(Mockery::mock('League\Flysystem\FilesystemOperator', function ($mock) {
$mock->shouldReceive('fileExists')->andReturn(false)->once();
}));
$this->server->setCache(Mockery::mock('League\Flysystem\FilesystemOperator', function ($mock) {
$mock->shouldReceive('fileExists')->andReturn(false)->once();
}));
$this->server->makeImage('image.jpg', []);
}
public function testMakeImageWithUnreadableSource()
{
$this->expectException(FilesystemException::class);
$this->expectExceptionMessage('Could not read the image `image.jpg`.');
$this->server->setSource(Mockery::mock('League\Flysystem\FilesystemOperator', function ($mock) {
$mock->shouldReceive('fileExists')->andReturn(true)->once();
$mock->shouldReceive('read')->andThrow('League\Flysystem\UnableToReadFile')->once();
}));
$this->server->setCache(Mockery::mock('League\Flysystem\FilesystemOperator', function ($mock) {
$mock->shouldReceive('fileExists')->andThrow('League\Flysystem\UnableToCheckFileExistence')->once();
}));
$this->server->makeImage('image.jpg', []);
}
public function testMakeImageWithUnwritableCache()
{
$this->expectException(FilesystemException::class);
$this->expectExceptionMessage('Could not write the image `image.jpg/75094881e9fd2b93063d6a5cb083091c`.');
$this->server->setSource(Mockery::mock('League\Flysystem\FilesystemOperator', function ($mock) {
$mock->shouldReceive('fileExists')->andReturn(true)->once();
$mock->shouldReceive('read')->andReturn('content')->once();
}));
$this->server->setCache(Mockery::mock('League\Flysystem\FilesystemOperator', function ($mock) {
$mock->shouldReceive('fileExists')->andThrow('League\Flysystem\UnableToCheckFileExistence')->once();
$mock->shouldReceive('write')->andThrow('League\Flysystem\UnableToWriteFile')->once();
}));
$this->server->setApi(Mockery::mock('League\Glide\Api\ApiInterface', function ($mock) {
$mock->shouldReceive('run')->andReturn('content')->once();
}));
$this->server->makeImage('image.jpg', []);
}
}
| {
"content_hash": "c19a8eaac8f44e31926bf26b6c6d056c",
"timestamp": "",
"source": "github",
"line_count": 572,
"max_line_length": 139,
"avg_line_length": 34.64510489510489,
"alnum_prop": 0.6182065903012565,
"repo_name": "thephpleague/glide",
"id": "3048ba6e21c467c95769163c6b2b8c3c3df83d45",
"size": "19817",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/ServerTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "175752"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Piforatio.Win.View.Panels.DataViewPanels
{
/// <summary>
/// Interaction logic for TasksView.xaml
/// </summary>
public partial class TasksView : UserControl
{
public TasksView()
{
InitializeComponent();
}
}
}
| {
"content_hash": "a56112e66a21e1e56c78e4caf261e724",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 50,
"avg_line_length": 23.714285714285715,
"alnum_prop": 0.7213855421686747,
"repo_name": "oledb/PiforatioAlpha",
"id": "475f68feff95a28c36f4e1b62fb96747ff98526f",
"size": "666",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Piforatio.Core/Piforatio.Win/View/Panels/DataViewPanels/TasksView.xaml.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "134488"
}
],
"symlink_target": ""
} |
package org.apache.taverna.scufl2.validation.correctness;
import org.apache.taverna.scufl2.api.activity.Activity;
import org.apache.taverna.scufl2.api.common.Child;
import org.apache.taverna.scufl2.api.common.Configurable;
import org.apache.taverna.scufl2.api.common.Named;
import org.apache.taverna.scufl2.api.common.Ported;
import org.apache.taverna.scufl2.api.common.Root;
import org.apache.taverna.scufl2.api.common.Typed;
import org.apache.taverna.scufl2.api.configurations.Configuration;
import org.apache.taverna.scufl2.api.container.WorkflowBundle;
import org.apache.taverna.scufl2.api.core.BlockingControlLink;
import org.apache.taverna.scufl2.api.core.ControlLink;
import org.apache.taverna.scufl2.api.core.DataLink;
import org.apache.taverna.scufl2.api.core.Processor;
import org.apache.taverna.scufl2.api.core.Workflow;
import org.apache.taverna.scufl2.api.iterationstrategy.CrossProduct;
import org.apache.taverna.scufl2.api.iterationstrategy.DotProduct;
import org.apache.taverna.scufl2.api.iterationstrategy.IterationStrategyNode;
import org.apache.taverna.scufl2.api.iterationstrategy.IterationStrategyParent;
import org.apache.taverna.scufl2.api.iterationstrategy.IterationStrategyStack;
import org.apache.taverna.scufl2.api.iterationstrategy.IterationStrategyTopNode;
import org.apache.taverna.scufl2.api.iterationstrategy.PortNode;
import org.apache.taverna.scufl2.api.port.AbstractDepthPort;
import org.apache.taverna.scufl2.api.port.AbstractGranularDepthPort;
import org.apache.taverna.scufl2.api.port.ActivityPort;
import org.apache.taverna.scufl2.api.port.InputActivityPort;
import org.apache.taverna.scufl2.api.port.InputPort;
import org.apache.taverna.scufl2.api.port.InputProcessorPort;
import org.apache.taverna.scufl2.api.port.InputWorkflowPort;
import org.apache.taverna.scufl2.api.port.OutputActivityPort;
import org.apache.taverna.scufl2.api.port.OutputPort;
import org.apache.taverna.scufl2.api.port.OutputProcessorPort;
import org.apache.taverna.scufl2.api.port.OutputWorkflowPort;
import org.apache.taverna.scufl2.api.port.Port;
import org.apache.taverna.scufl2.api.port.ProcessorPort;
import org.apache.taverna.scufl2.api.port.ReceiverPort;
import org.apache.taverna.scufl2.api.port.SenderPort;
import org.apache.taverna.scufl2.api.port.WorkflowPort;
import org.apache.taverna.scufl2.api.profiles.ProcessorBinding;
import org.apache.taverna.scufl2.api.profiles.ProcessorInputPortBinding;
import org.apache.taverna.scufl2.api.profiles.ProcessorOutputPortBinding;
import org.apache.taverna.scufl2.api.profiles.ProcessorPortBinding;
import org.apache.taverna.scufl2.api.profiles.Profile;
/**
* @author alanrw
*/
public class DefaultDispatchingVisitor extends DispatchingVisitor {
@Override
public void visitActivity(Activity bean) {
}
@Override
public void visitActivityPort(ActivityPort bean) {
}
@Override
public void visitBlockingControlLink(BlockingControlLink bean) {
}
@Override
public void visitChild(Child<?> bean) {
}
@Override
public void visitConfigurable(Configurable bean) {
}
@Override
public void visitConfiguration(Configuration bean) {
}
@Override
public void visitControlLink(ControlLink bean) {
}
@Override
public void visitCrossProduct(CrossProduct bean) {
}
@Override
public void visitDataLink(DataLink bean) {
}
@Override
public void visitDotProduct(DotProduct bean) {
}
@Override
public void visitInputActivityPort(InputActivityPort bean) {
}
@Override
public void visitInputPort(InputPort bean) {
}
@Override
public void visitInputProcessorPort(InputProcessorPort bean) {
}
@Override
public void visitInputWorkflowPort(InputWorkflowPort bean) {
}
@Override
public void visitIterationStrategyNode(IterationStrategyNode bean) {
}
@Override
public void visitIterationStrategyParent(IterationStrategyParent bean) {
}
@Override
public void visitIterationStrategyStack(IterationStrategyStack bean) {
}
@Override
public void visitIterationStrategyTopNode(IterationStrategyTopNode bean) {
}
@Override
public void visitNamed(Named bean) {
}
@Override
public void visitOutputActivityPort(OutputActivityPort bean) {
}
@Override
public void visitOutputPort(OutputPort bean) {
}
@Override
public void visitOutputProcessorPort(OutputProcessorPort bean) {
}
@Override
public void visitOutputWorkflowPort(OutputWorkflowPort bean) {
}
@Override
public void visitPort(Port bean) {
}
@Override
public void visitPortNode(PortNode bean) {
}
@Override
public void visitPorted(Ported bean) {
}
@Override
public void visitProcessor(Processor bean) {
}
@Override
public void visitProcessorBinding(ProcessorBinding bean) {
}
@Override
public void visitProcessorInputPortBinding(ProcessorInputPortBinding bean) {
}
@Override
public void visitProcessorOutputPortBinding(ProcessorOutputPortBinding bean) {
}
@Override
public void visitProcessorPort(ProcessorPort bean) {
}
@Override
public void visitProcessorPortBinding(ProcessorPortBinding<?, ?> bean) {
}
@Override
public void visitProfile(Profile bean) {
}
@Override
public void visitReceiverPort(ReceiverPort bean) {
}
@Override
public void visitRoot(Root bean) {
}
@Override
public void visitSenderPort(SenderPort bean) {
}
@Override
public void visitTyped(Typed bean) {
}
@Override
public void visitWorkflow(Workflow bean) {
}
@Override
public void visitWorkflowBundle(WorkflowBundle bean) {
}
@Override
public void visitWorkflowPort(WorkflowPort bean) {
}
@Override
public void visitAbstractDepthPort(AbstractDepthPort bean) {
}
@Override
public void visitAbstractGranularDepthPort(AbstractGranularDepthPort bean) {
}
}
| {
"content_hash": "eece724b9478e2d9eceaea7b90855040",
"timestamp": "",
"source": "github",
"line_count": 219,
"max_line_length": 80,
"avg_line_length": 25.926940639269407,
"alnum_prop": 0.807502641775273,
"repo_name": "binfalse/incubator-taverna-language",
"id": "d4ec8b7a1ee2b56cca2e8112572d178aa0420c2e",
"size": "6490",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "taverna-scufl2-api/src/main/java/org/apache/taverna/scufl2/validation/correctness/DefaultDispatchingVisitor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1886753"
},
{
"name": "Python",
"bytes": "4597"
},
{
"name": "Ruby",
"bytes": "2927"
},
{
"name": "Shell",
"bytes": "916"
},
{
"name": "Web Ontology Language",
"bytes": "79530"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.