text stringlengths 2 1.04M | meta dict |
|---|---|
package com.wut.resources.storage.row;
import com.wut.model.Data;
import com.wut.model.map.MappedData;
import com.wut.model.scalar.IdData;
import com.wut.model.scalar.StringData;
import com.wut.pipeline.WutRequest;
import com.wut.provider.Provider;
import com.wut.provider.row.RowProvider;
import com.wut.provider.table.TableResourceProvider;
import com.wut.resources.common.AbstractOperation;
import com.wut.resources.common.MissingParameterException;
import com.wut.resources.operations.UpdateOperation;
public class UpdateRowOperation extends UpdateOperation {
private TableResourceProvider provider = RowProvider.getRowProvider();
private TableResourceProvider cacheProvider = RowProvider.getRowCache();
@Override
public Data perform(WutRequest request) throws Exception {
IdData application = new IdData(request.getApplication());
IdData customer = new IdData(request.getCustomer());
IdData user = new IdData(request.getUser().getId());
StringData tableStringData = request.getParameter("table");
IdData tableId = new IdData(tableStringData.toRawString());
String idString = request.getStringParameter("id");
IdData rowId = new IdData(idString);
MappedData data = request.getParameter("data");
if (data == null) { // TODO: DONT THIS THIS CHECK IS NEEDED
throw new MissingParameterException("data");
}
Data result = provider.update(application, customer, user, tableId, rowId, data);
return result;
}
@Override
public Data cacheGet(WutRequest request) throws MissingParameterException {
return null;
}
@Override
public boolean cachePut(WutRequest request, Data d) throws MissingParameterException {
IdData application = new IdData(request.getApplication());
IdData customer = new IdData(request.getCustomer());
IdData user = new IdData(request.getUser().getId());
StringData tableStringData = request.getParameter("table");
IdData tableId = new IdData(tableStringData.toRawString());
String idString = request.getStringParameter("id");
IdData rowId = new IdData(idString);
MappedData data = request.getParameter("data");
if (data == null) { // TODO: DONT THIS THIS CHECK IS NEEDED
throw new MissingParameterException("data");
}
Data result = cacheProvider.update(application, customer, user, tableId, rowId, data);
return result != null;
}
}
| {
"content_hash": "7a15c509c0a7956a785de03206467bfe",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 88,
"avg_line_length": 37.645161290322584,
"alnum_prop": 0.7677806341045416,
"repo_name": "WebUtilityKit/api-server",
"id": "ee04d747fffed8d3986af6f47ab2cade9af16c8d",
"size": "2334",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "storage/src/main/java/com/wut/resources/storage/row/UpdateRowOperation.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1119746"
},
{
"name": "JavaScript",
"bytes": "3422"
},
{
"name": "Python",
"bytes": "5253"
},
{
"name": "Shell",
"bytes": "7081"
}
],
"symlink_target": ""
} |
int main() {
float cel;
float fa;
printf("\n Escreva uma temperatura em Celsius e converterei para Fahrenheit");
scanf("%f",&cel);
fa=(1.8*cel)+32;
printf("%f",fa);
return 0;
}
| {
"content_hash": "d5e0e46968c5f50529e535dc4b6c17da",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 79,
"avg_line_length": 20.444444444444443,
"alnum_prop": 0.6467391304347826,
"repo_name": "PaulaGVF/Celsius-to-Fahrenheit",
"id": "d47ed6227a4ea5dc994b99d696cb750bbdc18703",
"size": "206",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "celsius.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "206"
}
],
"symlink_target": ""
} |
package com.joy.threadpool;
import java.util.Collection;
public interface IQueue<T> {
public void enqueue(T object) throws Exception;
public void enqueue(Collection<T> objects) throws Exception;
public T dequeue();
}
| {
"content_hash": "e788061f8199282f3a7b45bdc66cbd8e",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 63,
"avg_line_length": 22.8,
"alnum_prop": 0.7543859649122807,
"repo_name": "joyghosh/ThreadPool",
"id": "82f7e1bf3419f2eb3e81f925ce44e1cf5218a41e",
"size": "228",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/joy/threadpool/IQueue.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "9856"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>axiomatic-abp: 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.9.1 / axiomatic-abp - 8.8.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
axiomatic-abp
<small>
8.8.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-08-24 17:47:06 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-24 17:47:06 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.12 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.9.1 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/axiomatic-abp"
license: "Unknown"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/AxiomaticABP"]
depends: [
"ocaml"
"coq" {>= "8.8" & < "8.9~"}
]
tags: [ "keyword: Alternating Bit Protocol" "keyword: Process Calculi" "keyword: reactive systems" "category: Computer Science/Concurrent Systems and Protocols/Correctness of specific protocols" ]
authors: [ "Jan Friso Groote" ]
bug-reports: "https://github.com/coq-contribs/axiomatic-abp/issues"
dev-repo: "git+https://github.com/coq-contribs/axiomatic-abp.git"
synopsis: "Verification of an axiomatisation of the Alternating Bit Protocol"
description: """
The Alternating Bit Protocol is expressed in an axiomatized calculi of process.
Correctness is proven."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/axiomatic-abp/archive/v8.8.0.tar.gz"
checksum: "md5=6f7b3cc0f84e1d4f446276c239c21d7c"
}
</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-axiomatic-abp.8.8.0 coq.8.9.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.9.1).
The following dependencies couldn't be met:
- coq-axiomatic-abp -> coq < 8.9~ -> ocaml < 4.03.0
base of this switch (use `--unlock-base' to force)
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-axiomatic-abp.8.8.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">
<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": "1f586096bfb20310d079099d1179d328",
"timestamp": "",
"source": "github",
"line_count": 167,
"max_line_length": 236,
"avg_line_length": 42.82035928143713,
"alnum_prop": 0.5505523702978604,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "554fd11e691daf3a395f43df3137ba2bb57a67f4",
"size": "7153",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.05.0-2.0.6/released/8.9.1/axiomatic-abp/8.8.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?php
namespace Predis\Protocol\Text\Handler;
use Predis\CommunicationException;
use Predis\Connection\ComposableConnectionInterface;
use Predis\Response\Iterator\MultiBulk as MultiBulkIterator;
use Predis\Protocol\ProtocolException;
/**
* Handler for the multibulk response type in the standard Redis wire protocol.
* It returns multibulk responses as iterators that can stream bulk elements.
*
* Streamable multibulk responses are not globally supported by the abstractions
* built-in into Predis, such as transactions or pipelines. Use them with care!
*
* @link http://redis.io/topics/protocol
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class StreamableMultiBulkResponse implements ResponseHandlerInterface
{
/**
* {@inheritdoc}
*/
public function handle(ComposableConnectionInterface $connection, $payload)
{
$length = (int) $payload;
if ("$length" != $payload) {
CommunicationException::handle(new ProtocolException(
$connection, "Cannot parse '$payload' as a valid length for a multi-bulk response."
));
}
return new MultiBulkIterator($connection, $length);
}
}
| {
"content_hash": "d665a2ddd028824fb85b814aede68932",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 99,
"avg_line_length": 30.615384615384617,
"alnum_prop": 0.7160804020100503,
"repo_name": "cola1129/devtool",
"id": "a2d66b7fc736ceec20f248802249971b53e8cfeb",
"size": "1426",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "phpra/vendor/lib/Predis/Protocol/Text/Handler/StreamableMultiBulkResponse.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "49343"
},
{
"name": "JavaScript",
"bytes": "2080156"
},
{
"name": "PHP",
"bytes": "6755602"
},
{
"name": "Python",
"bytes": "16042"
},
{
"name": "Shell",
"bytes": "7396"
}
],
"symlink_target": ""
} |
(function () {
'use strict';
angular
.module('contracts')
.factory('RewardsContractService', RewardsContractService);
RewardsContractService.$inject = [/*Example: '$state', '$window' */];
function RewardsContractService(/*Example: $state, $window */) {
// Rewards service logic
// ...
// Public API
return {
addReward: function (contract) {
if(!contract.rewards) {
contract.rewards = [];
}
contract.rewards.push({});
},
removeReward: function (contract, index) {
contract.rewards.splice(index, 1);
}
};
}
})();
| {
"content_hash": "f3038c25cd52a18b65058b07c8c6d3be",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 71,
"avg_line_length": 22.142857142857142,
"alnum_prop": 0.5709677419354838,
"repo_name": "etkirsch/cnd-mean",
"id": "af48bed4d31767994c9c140dc4d3340d413696b9",
"size": "620",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "modules/contracts/client/services/rewards.client.service.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2172"
},
{
"name": "HTML",
"bytes": "90598"
},
{
"name": "JavaScript",
"bytes": "555636"
},
{
"name": "Shell",
"bytes": "685"
}
],
"symlink_target": ""
} |
package org.spongycastle.crypto.tls.test;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.SecureRandom;
import org.spongycastle.crypto.tls.TlsServerProtocol;
import org.spongycastle.util.io.Streams;
import org.spongycastle.util.io.TeeOutputStream;
/**
* A simple test designed to conduct a TLS handshake with an external TLS client.
* <p/>
* Please refer to GnuTLSSetup.txt or OpenSSLSetup.txt, and x509-*.pem files in this package for
* help configuring an external TLS client.
*/
public class TlsServerTest
{
private static final SecureRandom secureRandom = new SecureRandom();
public static void main(String[] args)
throws Exception
{
InetAddress address = InetAddress.getLocalHost();
int port = 5556;
ServerSocket ss = new ServerSocket(port, 16, address);
while (true)
{
Socket s = ss.accept();
System.out.println("--------------------------------------------------------------------------------");
System.out.println("Accepted " + s);
ServerThread t = new ServerThread(s);
t.start();
}
}
static class ServerThread
extends Thread
{
private final Socket s;
ServerThread(Socket s)
{
this.s = s;
}
public void run()
{
try
{
MockTlsServer server = new MockTlsServer();
TlsServerProtocol serverProtocol = new TlsServerProtocol(s.getInputStream(), s.getOutputStream(), secureRandom);
serverProtocol.accept(server);
OutputStream log = new TeeOutputStream(serverProtocol.getOutputStream(), System.out);
Streams.pipeAll(serverProtocol.getInputStream(), log);
serverProtocol.close();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
finally
{
try
{
s.close();
}
catch (IOException e)
{
}
finally
{
}
}
}
}
}
| {
"content_hash": "0c33737929e3f478af03e54c7d4481f1",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 128,
"avg_line_length": 28.88888888888889,
"alnum_prop": 0.5397435897435897,
"repo_name": "iseki-masaya/spongycastle",
"id": "af74ec77dae71a9a61e476a8a1aeaa26808b9113",
"size": "2340",
"binary": false,
"copies": "1",
"ref": "refs/heads/spongy-master",
"path": "core/src/test/java/org/spongycastle/crypto/tls/test/TlsServerTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "51928"
},
{
"name": "Java",
"bytes": "21991233"
},
{
"name": "Shell",
"bytes": "71300"
}
],
"symlink_target": ""
} |
<?php
/**
* Category flat model
*
* @category Mage
* @package Mage_Catalog
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_Catalog_Model_Resource_Category_Flat extends Mage_Index_Model_Resource_Abstract
{
/**
* Amount of categories to be processed in batch
*/
const CATEGORY_BATCH = 500;
/**
* Store id
*
* @var int
*/
protected $_storeId = null;
/**
* Loaded
*
* @var boolean
*/
protected $_loaded = false;
/**
* Nodes
*
* @var array
*/
protected $_nodes = array();
/**
* Columns
*
* @var array
*/
protected $_columns = null;
/**
* Columns sql
*
* @var array
*/
protected $_columnsSql = null;
/**
* Attribute codes
*
* @var array
*/
protected $_attributeCodes = null;
/**
* Inactive categories ids
*
* @var array
*/
protected $_inactiveCategoryIds = null;
/**
* Store flag which defines if Catalog Category Flat Data has been initialized
*
* @var array
*/
protected $_isBuilt = array();
/**
* Store flag which defines if Catalog Category Flat Data has been initialized
*
* @deprecated after 1.7.0.0 use $this->_isBuilt instead
*
* @var bool|null
*/
protected $_isRebuilt = null;
/**
* array with root category id per store
*
* @var array
*/
protected $_storesRootCategories;
/**
* Whether table changes are allowed
*
* @var bool
*/
protected $_allowTableChanges = true;
/**
* Factory instance
*
* @var Mage_Catalog_Model_Factory
*/
protected $_factory;
/**
* Initialize factory instance
*
* @param array $args
*/
public function __construct(array $args = array())
{
$this->_factory = !empty($args['factory']) ? $args['factory'] : Mage::getSingleton('catalog/factory');
parent::__construct();
}
/**
* Resource initializations
*
*/
protected function _construct()
{
$this->_init('catalog/category_flat', 'entity_id');
}
/**
* Set store id
*
* @param integer $storeId
* @return Mage_Catalog_Model_Resource_Category_Flat
*/
public function setStoreId($storeId)
{
$this->_storeId = (int)$storeId;
return $this;
}
/**
* Return store id
*
* @return integer
*/
public function getStoreId()
{
if (is_null($this->_storeId)) {
return (int)Mage::app()->getStore()->getId();
}
return $this->_storeId;
}
/**
* Get main table name
*
* @return string
*/
public function getMainTable()
{
return $this->getMainStoreTable($this->getStoreId());
}
/**
* Return name of table for given $storeId.
*
* @param integer $storeId
* @return string
*/
public function getMainStoreTable($storeId = Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID)
{
if (is_string($storeId)) {
$storeId = intval($storeId);
}
if ($this->getUseStoreTables() && $storeId) {
$suffix = sprintf('store_%d', $storeId);
$table = $this->getTable(array('catalog/category_flat', $suffix));
} else {
$table = parent::getMainTable();
}
return $table;
}
/**
* Return true if need use for each store different table of flat categories data.
*
* @return boolean
*/
public function getUseStoreTables()
{
return true;
}
/**
* Add inactive categories ids
*
* @param array $ids
* @return Mage_Catalog_Model_Resource_Category_Flat
*/
public function addInactiveCategoryIds($ids)
{
if (!is_array($this->_inactiveCategoryIds)) {
$this->_initInactiveCategoryIds();
}
$this->_inactiveCategoryIds = array_merge($ids, $this->_inactiveCategoryIds);
return $this;
}
/**
* Retreive inactive categories ids
*
* @return Mage_Catalog_Model_Resource_Category_Flat
*/
protected function _initInactiveCategoryIds()
{
$this->_inactiveCategoryIds = array();
Mage::dispatchEvent('catalog_category_tree_init_inactive_category_ids', array('tree' => $this));
return $this;
}
/**
* Retreive inactive categories ids
*
* @return array
*/
public function getInactiveCategoryIds()
{
if (!is_array($this->_inactiveCategoryIds)) {
$this->_initInactiveCategoryIds();
}
return $this->_inactiveCategoryIds;
}
/**
* Load nodes by parent id
*
* @param Mage_Catalog_Model_Category|int $parentNode
* @param integer $recursionLevel
* @param integer $storeId
* @param bool $onlyActive
* @return Mage_Catalog_Model_Resource_Category_Flat
*/
protected function _loadNodes($parentNode = null, $recursionLevel = 0, $storeId = 0, $onlyActive = true)
{
$_conn = $this->_getReadAdapter();
$startLevel = 1;
$parentPath = '';
if ($parentNode instanceof Mage_Catalog_Model_Category) {
$parentPath = $parentNode->getPath();
$startLevel = $parentNode->getLevel();
} elseif (is_numeric($parentNode)) {
$selectParent = $_conn->select()
->from($this->getMainStoreTable($storeId))
->where('entity_id = ?', $parentNode)
->where('store_id = ?', $storeId);
$parentNode = $_conn->fetchRow($selectParent);
if ($parentNode) {
$parentPath = $parentNode['path'];
$startLevel = $parentNode['level'];
}
}
$select = $_conn->select()
->from(
array('main_table' => $this->getMainStoreTable($storeId)),
array('entity_id',
new Zend_Db_Expr('main_table.' . $_conn->quoteIdentifier('name')),
new Zend_Db_Expr('main_table.' . $_conn->quoteIdentifier('path')),
'is_active',
'is_anchor'))
->where('main_table.include_in_menu = ?', '1')
->order('main_table.position');
if ($onlyActive) {
$select->where('main_table.is_active = ?', '1');
}
/** @var $urlRewrite Mage_Catalog_Helper_Category_Url_Rewrite_Interface */
$urlRewrite = $this->_factory->getCategoryUrlRewriteHelper();
$urlRewrite->joinTableToSelect($select, $storeId);
if ($parentPath) {
$select->where($_conn->quoteInto("main_table.path like ?", "$parentPath/%"));
}
if ($recursionLevel != 0) {
$levelField = $_conn->quoteIdentifier('level');
$select->where($levelField . ' <= ?', $startLevel + $recursionLevel);
}
$inactiveCategories = $this->getInactiveCategoryIds();
if (!empty($inactiveCategories)) {
$select->where('main_table.entity_id NOT IN (?)', $inactiveCategories);
}
// Allow extensions to modify select (e.g. add custom category attributes to select)
Mage::dispatchEvent('catalog_category_flat_loadnodes_before', array('select' => $select));
$arrNodes = $_conn->fetchAll($select);
$nodes = array();
foreach ($arrNodes as $node) {
$node['id'] = $node['entity_id'];
$nodes[$node['id']] = Mage::getModel('catalog/category')->setData($node);
}
return $nodes;
}
/**
* Creating sorted array of nodes
*
* @param array $children
* @param string $path
* @param Varien_Object $parent
*/
public function addChildNodes($children, $path, $parent)
{
if (isset($children[$path])) {
foreach ($children[$path] as $child) {
$childrenNodes = $parent->getChildrenNodes();
if ($childrenNodes && isset($childrenNodes[$child->getId()])) {
$childrenNodes[$child['entity_id']]->setChildrenNodes(array($child->getId()=>$child));
} else {
if ($childrenNodes) {
$childrenNodes[$child->getId()] = $child;
} else {
$childrenNodes = array($child->getId()=>$child);
}
$parent->setChildrenNodes($childrenNodes);
}
if ($path) {
$childrenPath = explode('/', $path);
} else {
$childrenPath = array();
}
$childrenPath[] = $child->getId();
$childrenPath = implode('/', $childrenPath);
$this->addChildNodes($children, $childrenPath, $child);
}
}
}
/**
* Return sorted array of nodes
*
* @param integer|null $parentId
* @param integer $recursionLevel
* @param integer $storeId
* @return array
*/
public function getNodes($parentId, $recursionLevel = 0, $storeId = 0)
{
if (!$this->_loaded) {
$selectParent = $this->_getReadAdapter()->select()
->from($this->getMainStoreTable($storeId))
->where('entity_id = ?', $parentId);
if ($parentNode = $this->_getReadAdapter()->fetchRow($selectParent)) {
$parentNode['id'] = $parentNode['entity_id'];
$parentNode = Mage::getModel('catalog/category')->setData($parentNode);
$this->_nodes[$parentNode->getId()] = $parentNode;
$nodes = $this->_loadNodes($parentNode, $recursionLevel, $storeId);
$childrenItems = array();
foreach ($nodes as $node) {
$pathToParent = explode('/', $node->getPath());
array_pop($pathToParent);
$pathToParent = implode('/', $pathToParent);
$childrenItems[$pathToParent][] = $node;
}
$this->addChildNodes($childrenItems, $parentNode->getPath(), $parentNode);
$childrenNodes = $this->_nodes[$parentNode->getId()];
if ($childrenNodes->getChildrenNodes()) {
$this->_nodes = $childrenNodes->getChildrenNodes();
}
else {
$this->_nodes = array();
}
$this->_loaded = true;
}
}
return $this->_nodes;
}
/**
* Return array or collection of categories
*
* @param integer $parent
* @param integer $recursionLevel
* @param boolean|string $sorted
* @param boolean $asCollection
* @param boolean $toLoad
* @return array|Varien_Data_Collection
*/
public function getCategories($parent, $recursionLevel = 0, $sorted = false, $asCollection = false, $toLoad = true)
{
if ($asCollection) {
$select = $this->_getReadAdapter()->select()
->from(array('mt' => $this->getMainStoreTable($this->getStoreId())), array('path'))
->where('mt.entity_id = ?', $parent);
$parentPath = $this->_getReadAdapter()->fetchOne($select);
$collection = Mage::getModel('catalog/category')->getCollection()
->addNameToResult()
->addUrlRewriteToResult()
->addParentPathFilter($parentPath)
->addStoreFilter()
->addIsActiveFilter()
->addAttributeToFilter('include_in_menu', 1)
->addSortedField($sorted);
if ($toLoad) {
return $collection->load();
}
return $collection;
}
return $this->getNodes($parent, $recursionLevel, Mage::app()->getStore()->getId());
}
/**
* Return node with id $nodeId
*
* @param integer $nodeId
* @param array $nodes
* @return Varien_Object
*/
public function getNodeById($nodeId, $nodes = null)
{
if (is_null($nodes)) {
$nodes = $this->getNodes($nodeId);
}
if (isset($nodes[$nodeId])) {
return $nodes[$nodeId];
}
foreach ($nodes as $node) {
if ($node->getChildrenNodes()) {
return $this->getNodeById($nodeId, $node->getChildrenNodes());
}
}
return array();
}
/**
* Check if Catalog Category Flat Data has been initialized
*
* @param bool|int|\Mage_Core_Model_Store|null $storeView Store(id) for which the value is checked
* @return bool
*/
public function isBuilt($storeView = null)
{
$storeView = is_null($storeView) ? Mage::app()->getDefaultStoreView() : Mage::app()->getStore($storeView);
if ($storeView === null) {
$storeId = Mage_Core_Model_App::ADMIN_STORE_ID;
} else {
$storeId = $storeView->getId();
}
if (!isset($this->_isBuilt[$storeId])) {
$select = $this->_getReadAdapter()->select()
->from($this->getMainStoreTable($storeId), 'entity_id')
->limit(1);
try {
$this->_isBuilt[$storeId] = (bool)$this->_getReadAdapter()->fetchOne($select);
} catch (Exception $e) {
$this->_isBuilt[$storeId] = false;
}
}
return $this->_isBuilt[$storeId];
}
/**
* Rebuild flat data from eav
*
* @param array|null $stores
* @return Mage_Catalog_Model_Resource_Category_Flat
*/
public function rebuild($stores = null)
{
if ($stores === null) {
$stores = Mage::app()->getStores();
}
if (!is_array($stores)) {
$stores = array($stores);
}
$rootId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
$categories = array();
$categoriesIds = array();
/* @var $store Mage_Core_Model_Store */
foreach ($stores as $store) {
if ($this->_allowTableChanges) {
$this->_createTable($store->getId());
}
if (!isset($categories[$store->getRootCategoryId()])) {
$select = $this->_getWriteAdapter()->select()
->from($this->getTable('catalog/category'))
->where('path = ?', (string)$rootId)
->orWhere('path = ?', "{$rootId}/{$store->getRootCategoryId()}")
->orWhere('path LIKE ?', "{$rootId}/{$store->getRootCategoryId()}/%");
$categories[$store->getRootCategoryId()] = $this->_getWriteAdapter()->fetchAll($select);
$categoriesIds[$store->getRootCategoryId()] = array();
foreach ($categories[$store->getRootCategoryId()] as $category) {
$categoriesIds[$store->getRootCategoryId()][] = $category['entity_id'];
}
}
$categoriesIdsChunks = array_chunk($categoriesIds[$store->getRootCategoryId()], self::CATEGORY_BATCH);
foreach ($categoriesIdsChunks as $categoriesIdsChunk) {
$attributesData = $this->_getAttributeValues($categoriesIdsChunk, $store->getId());
$data = array();
foreach ($categories[$store->getRootCategoryId()] as $category) {
if (!isset($attributesData[$category['entity_id']])) {
continue;
}
$category['store_id'] = $store->getId();
$data[] = $this->_prepareValuesToInsert(
array_merge($category, $attributesData[$category['entity_id']])
);
}
$this->_getWriteAdapter()->insertMultiple($this->getMainStoreTable($store->getId()), $data);
}
}
return $this;
}
/**
* Prepare array of column and columnValue pairs
*
* @param array $data
* @return array
*/
protected function _prepareValuesToInsert($data)
{
$values = array();
foreach (array_keys($this->_columns) as $key => $column) {
if (isset($data[$column])) {
$values[$column] = $data[$column];
} else {
$values[$column] = null;
}
}
return $values;
}
/**
* Create Flate Table(s)
*
* @param array|int $stores
* @return Mage_Catalog_Model_Resource_Category_Flat
*/
public function createTable($stores)
{
return $this->_createTable($stores);
}
/**
* Creating table and adding attributes as fields to table
*
* @param array|integer $store
* @return Mage_Catalog_Model_Resource_Category_Flat
*/
protected function _createTable($store)
{
$tableName = $this->getMainStoreTable($store);
$_writeAdapter = $this->_getWriteAdapter();
$_writeAdapter->dropTable($tableName);
$table = $this->_getWriteAdapter()
->newTable($tableName)
->setComment(sprintf('Catalog Category Flat (Store %d)', $store));
//Adding columns
if ($this->_columnsSql === null) {
$this->_columns = array_merge($this->_getStaticColumns(), $this->_getEavColumns());
foreach ($this->_columns as $fieldName => $fieldProp) {
$default = $fieldProp['default'];
if ($fieldProp['type'][0] == Varien_Db_Ddl_Table::TYPE_TIMESTAMP
&& $default == 'CURRENT_TIMESTAMP') {
$default = Varien_Db_Ddl_Table::TIMESTAMP_INIT;
}
$table->addColumn($fieldName, $fieldProp['type'][0], $fieldProp['type'][1], array(
'nullable' => $fieldProp['nullable'],
'unsigned' => $fieldProp['unsigned'],
'default' => $default,
'primary' => isset($fieldProp['primary']) ? $fieldProp['primary'] : false,
), ($fieldProp['comment'] != '') ?
$fieldProp['comment'] :
ucwords(str_replace('_', ' ', $fieldName))
);
}
}
// Adding indexes
$table->addIndex(
$_writeAdapter->getIndexName($tableName, array('entity_id')),
array('entity_id'),
array('type' => 'primary')
);
$table->addIndex(
$_writeAdapter->getIndexName($tableName, array('store_id')), array('store_id'), array('type' => 'index')
);
$table->addIndex(
$_writeAdapter->getIndexName($tableName, array('path')), array('path'), array('type' => 'index')
);
$table->addIndex(
$_writeAdapter->getIndexName($tableName, array('level')), array('level'), array('type' => 'index')
);
// Adding foreign keys
$table->addForeignKey(
$_writeAdapter->getForeignKeyName(
$tableName, 'entity_id', $this->getTable('catalog/category'), 'entity_id'
),
'entity_id', $this->getTable('catalog/category'), 'entity_id',
Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE);
$table->addForeignKey(
$_writeAdapter->getForeignKeyName($tableName, 'store_id', $this->getTable('core/store'), 'store_id'),
'store_id', $this->getTable('core/store'), 'store_id',
Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE);
$_writeAdapter->createTable($table);
return $this;
}
/**
* Return array of static columns
*
* @return array
*/
protected function _getStaticColumns()
{
$helper = Mage::getResourceHelper('catalog');
$columns = array();
$columnsToSkip = array('entity_type_id', 'attribute_set_id');
$describe = $this->_getWriteAdapter()->describeTable($this->getTable('catalog/category'));
foreach ($describe as $column) {
if (in_array($column['COLUMN_NAME'], $columnsToSkip)) {
continue;
}
$_is_unsigned = '';
$ddlType = $helper->getDdlTypeByColumnType($column['DATA_TYPE']);
$column['DEFAULT'] = trim($column['DEFAULT'],"' ");
switch ($ddlType) {
case Varien_Db_Ddl_Table::TYPE_SMALLINT:
case Varien_Db_Ddl_Table::TYPE_INTEGER:
case Varien_Db_Ddl_Table::TYPE_BIGINT:
$_is_unsigned = (bool)$column['UNSIGNED'];
if ($column['DEFAULT'] === '') {
$column['DEFAULT'] = null;
}
$options = null;
if ($column['SCALE'] > 0) {
$ddlType = Varien_Db_Ddl_Table::TYPE_DECIMAL;
} else {
break;
}
case Varien_Db_Ddl_Table::TYPE_DECIMAL:
$options = $column['PRECISION'] . ',' . $column['SCALE'];
$_is_unsigned = null;
if ($column['DEFAULT'] === '') {
$column['DEFAULT'] = null;
}
break;
case Varien_Db_Ddl_Table::TYPE_TEXT:
$options = $column['LENGTH'];
$_is_unsigned = null;
break;
case Varien_Db_Ddl_Table::TYPE_TIMESTAMP:
$options = null;
$_is_unsigned = null;
break;
case Varien_Db_Ddl_Table::TYPE_DATETIME:
$_is_unsigned = null;
break;
}
$columns[$column['COLUMN_NAME']] = array(
'type' => array($ddlType, $options),
'unsigned' => $_is_unsigned,
'nullable' => $column['NULLABLE'],
'default' => ($column['DEFAULT'] === null ? false : $column['DEFAULT']),
'comment' => $column['COLUMN_NAME']
);
}
$columns['store_id'] = array(
'type' => array(Varien_Db_Ddl_Table::TYPE_SMALLINT, 5),
'unsigned' => true,
'nullable' => false,
'default' => '0',
'comment' => 'Store Id'
);
return $columns;
}
/**
* Return array of eav columns, skip attribute with static type
*
* @return array
*/
protected function _getEavColumns()
{
$columns = array();
$attributes = $this->_getAttributes();
foreach ($attributes as $attribute) {
if ($attribute['backend_type'] == 'static') {
continue;
}
$columns[$attribute['attribute_code']] = array();
switch ($attribute['backend_type']) {
case 'varchar':
$columns[$attribute['attribute_code']] = array(
'type' => array(Varien_Db_Ddl_Table::TYPE_TEXT, 255),
'unsigned' => null,
'nullable' => true,
'default' => null,
'comment' => (string)$attribute['frontend_label']
);
break;
case 'int':
$columns[$attribute['attribute_code']] = array(
'type' => array(Varien_Db_Ddl_Table::TYPE_INTEGER, null),
'unsigned' => null,
'nullable' => true,
'default' => null,
'comment' => (string)$attribute['frontend_label']
);
break;
case 'text':
$columns[$attribute['attribute_code']] = array(
'type' => array(Varien_Db_Ddl_Table::TYPE_TEXT, '64k'),
'unsigned' => null,
'nullable' => true,
'default' => null,
'comment' => (string)$attribute['frontend_label']
);
break;
case 'datetime':
$columns[$attribute['attribute_code']] = array(
'type' => array(Varien_Db_Ddl_Table::TYPE_DATETIME, null),
'unsigned' => null,
'nullable' => true,
'default' => null,
'comment' => (string)$attribute['frontend_label']
);
break;
case 'decimal':
$columns[$attribute['attribute_code']] = array(
'type' => array(Varien_Db_Ddl_Table::TYPE_DECIMAL, '12,4'),
'unsigned' => null,
'nullable' => true,
'default' => null,
'comment' => (string)$attribute['frontend_label']
);
break;
}
}
return $columns;
}
/**
* Return array of attribute codes for entity type 'catalog_category'
*
* @return array
*/
protected function _getAttributes()
{
if ($this->_attributeCodes === null) {
$select = $this->_getWriteAdapter()->select()
->from($this->getTable('eav/entity_type'), array())
->join(
$this->getTable('eav/attribute'),
$this->getTable('eav/attribute')
. '.entity_type_id = ' . $this->getTable('eav/entity_type') . '.entity_type_id',
$this->getTable('eav/attribute').'.*'
)
->where(
$this->getTable('eav/entity_type') . '.entity_type_code = ?', Mage_Catalog_Model_Category::ENTITY
);
$this->_attributeCodes = array();
foreach ($this->_getWriteAdapter()->fetchAll($select) as $attribute) {
$this->_attributeCodes[$attribute['attribute_id']] = $attribute;
}
}
return $this->_attributeCodes;
}
/**
* Return attribute values for given entities and store
*
* @param array $entityIds
* @param integer $store_id
* @return array
*/
protected function _getAttributeValues($entityIds, $store_id)
{
if (!is_array($entityIds)) {
$entityIds = array($entityIds);
}
$values = array();
foreach ($entityIds as $entityId) {
$values[$entityId] = array();
}
$attributes = $this->_getAttributes();
$attributesType = array(
'varchar',
'int',
'decimal',
'text',
'datetime'
);
foreach ($attributesType as $type) {
foreach ($this->_getAttributeTypeValues($type, $entityIds, $store_id) as $row) {
$values[$row['entity_id']][$attributes[$row['attribute_id']]['attribute_code']] = $row['value'];
}
}
return $values;
}
/**
* Return attribute values for given entities and store of specific attribute type
*
* @param string $type
* @param array $entityIds
* @param integer $storeId
* @return array
*/
protected function _getAttributeTypeValues($type, $entityIds, $storeId)
{
$select = $this->_getWriteAdapter()->select()
->from(
array('def' => $this->getTable(array('catalog/category', $type))),
array('entity_id', 'attribute_id')
)
->joinLeft(
array('store' => $this->getTable(array('catalog/category', $type))),
'store.entity_id = def.entity_id AND store.attribute_id = def.attribute_id '
. 'AND store.store_id = ' . $storeId,
array('value' => $this->_getWriteAdapter()->getCheckSql(
'store.value_id > 0',
$this->_getWriteAdapter()->quoteIdentifier('store.value'),
$this->_getWriteAdapter()->quoteIdentifier('def.value')
))
)
->where('def.entity_id IN (?)', $entityIds)
->where('def.store_id IN (?)', array(Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID, $storeId));
return $this->_getWriteAdapter()->fetchAll($select);
}
/**
* Delete store table(s) of given stores;
*
* @param array|integer $stores
* @return Mage_Catalog_Model_Resource_Category_Flat
*/
public function deleteStores($stores)
{
$this->_deleteTable($stores);
return $this;
}
/**
* Delete table(s) of given stores.
*
* @param array|integer $stores
* @return Mage_Catalog_Model_Resource_Category_Flat
*/
protected function _deleteTable($stores)
{
if (!is_array($stores)) {
$stores = array($stores);
}
foreach ($stores as $store) {
$this->_getWriteAdapter()->dropTable($this->getMainStoreTable($store));
}
return $this;
}
/**
* Synchronize flat data with eav model for category
*
* @param Varien_Object $category
* @return Mage_Catalog_Model_Resource_Category_Flat
*/
protected function _synchronize($category)
{
$table = $this->getMainStoreTable($category->getStoreId());
$data = $this->_prepareDataForAllFields($category);
$this->_getWriteAdapter()->insertOnDuplicate($table, $data);
return $this;
}
/**
* Synchronize flat data with eav model.
*
* @param Mage_Catalog_Model_Category|int $category
* @param array $storeIds
* @return Mage_Catalog_Model_Resource_Category_Flat
*/
public function synchronize($category = null, $storeIds = array())
{
if (is_null($category)) {
if (empty($storeIds)) {
$storeIds = null;
}
$stores = $this->getStoresRootCategories($storeIds);
$storesObjects = array();
foreach ($stores as $storeId => $rootCategoryId) {
$_store = new Varien_Object(array(
'store_id' => $storeId,
'root_category_id' => $rootCategoryId
));
$_store->setIdFieldName('store_id');
$storesObjects[] = $_store;
}
$this->rebuild($storesObjects);
} else if ($category instanceof Mage_Catalog_Model_Category) {
$categoryId = $category->getId();
foreach ($category->getStoreIds() as $storeId) {
if ($storeId == Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID) {
continue;
}
$attributeValues = $this->_getAttributeValues($categoryId, $storeId);
$data = new Varien_Object($category->getData());
$data->addData($attributeValues[$categoryId])
->setStoreId($storeId);
$this->_synchronize($data);
}
} else if (is_numeric($category)) {
$write = $this->_getWriteAdapter();
$select = $write->select()
->from($this->getTable('catalog/category'))
->where('entity_id=?', $category);
$row = $write->fetchRow($select);
if (!$row) {
return $this;
}
$stores = $this->getStoresRootCategories();
$path = explode('/', $row['path']);
foreach ($stores as $storeId => $rootCategoryId) {
if (in_array($rootCategoryId, $path)) {
$attributeValues = $this->_getAttributeValues($category, $storeId);
$data = new Varien_Object($row);
$data->addData($attributeValues[$category])
->setStoreId($storeId);
$this->_synchronize($data);
} else {
$where = $write->quoteInto('entity_id = ?', $category);
$write->delete($this->getMainStoreTable($storeId), $where);
}
}
}
return $this;
}
/**
* Remove table of given stores
*
* @param int|array $stores
* @return Mage_Catalog_Model_Resource_Category_Flat
*/
public function removeStores($stores)
{
$this->_deleteTable($stores);
return $this;
}
/**
* Synchronize flat category data after move by affected category ids
*
* @param array $affectedCategoryIds
* @return Mage_Catalog_Model_Resource_Category_Flat
*/
public function move(array $affectedCategoryIds)
{
$write = $this->_getWriteAdapter();
$select = $write->select()
->from($this->getTable('catalog/category'), array('entity_id', 'path'))
->where('entity_id IN(?)', $affectedCategoryIds);
$pairs = $write->fetchPairs($select);
$pathCond = array($write->quoteInto('entity_id IN(?)', $affectedCategoryIds));
$parentIds = array();
foreach ($pairs as $path) {
$pathCond[] = $write->quoteInto('path LIKE ?', $path . '/%');
$parentIds = array_merge($parentIds, explode('/', $path));
}
$stores = $this->getStoresRootCategories();
$where = join(' OR ', $pathCond);
$lastId = 0;
while (true) {
$select = $write->select()
->from($this->getTable('catalog/category'))
->where('entity_id>?', $lastId)
->where($where)
->order('entity_id')
->limit(500);
$rowSet = $write->fetchAll($select);
if (!$rowSet) {
break;
}
$addStores = array();
$remStores = array();
foreach ($rowSet as &$row) {
$lastId = $row['entity_id'];
$path = explode('/', $row['path']);
foreach ($stores as $storeId => $rootCategoryId) {
if (in_array($rootCategoryId, $path)) {
$addStores[$storeId][$row['entity_id']] = $row;
} else {
$remStores[$storeId][] = $row['entity_id'];
}
}
}
// remove
foreach ($remStores as $storeId => $categoryIds) {
$where = $write->quoteInto('entity_id IN(?)', $categoryIds);
$write->delete($this->getMainStoreTable($storeId), $where);
}
// add/update
foreach ($addStores as $storeId => $storeCategoryIds) {
$attributeValues = $this->_getAttributeValues(array_keys($storeCategoryIds), $storeId);
foreach ($storeCategoryIds as $row) {
$data = new Varien_Object($row);
$data->addData($attributeValues[$row['entity_id']])
->setStoreId($storeId);
$this->_synchronize($data);
}
}
}
return $this;
}
/**
* Synchronize flat data with eav after moving category
*
* @param integer $categoryId
* @param integer $prevParentId
* @param integer $parentId
* @return Mage_Catalog_Model_Resource_Category_Flat
*/
public function moveold($categoryId, $prevParentId, $parentId)
{
$catalogCategoryTable = $this->getTable('catalog/category');
$_staticFields = array(
'parent_id',
'path',
'level',
'position',
'children_count',
'updated_at'
);
$prevParent = Mage::getModel('catalog/category')->load($prevParentId);
$parent = Mage::getModel('catalog/category')->load($parentId);
if ($prevParent->getStore()->getWebsiteId() != $parent->getStore()->getWebsiteId()) {
foreach ($prevParent->getStoreIds() as $storeId) {
$this->_getWriteAdapter()->delete(
$this->getMainStoreTable($storeId),
$this->_getWriteAdapter()->quoteInto('entity_id = ?', $categoryId)
);
}
$select = $this->_getReadAdapter()->select()
->from($catalogCategoryTable, 'path')
->where('entity_id = ?', $categoryId);
$categoryPath = $this->_getWriteAdapter()->fetchOne($select);
$select = $this->_getWriteAdapter()->select()
->from($catalogCategoryTable, 'entity_id')
->where('path LIKE ?', "$categoryPath/%")
->orWhere('path = ?', $categoryPath);
$_categories = $this->_getWriteAdapter()->fetchAll($select);
foreach ($_categories as $_category) {
foreach ($parent->getStoreIds() as $storeId) {
$_tmpCategory = Mage::getModel('catalog/category')
->setStoreId($storeId)
->load($_category['entity_id']);
$this->_synchronize($_tmpCategory);
}
}
} else {
foreach ($parent->getStoreIds() as $store) {
$mainStoreTable = $this->getMainStoreTable($store);
$update = "UPDATE {$mainStoreTable}, {$catalogCategoryTable} SET";
foreach ($_staticFields as $field) {
$update .= " {$mainStoreTable}.".$field."={$catalogCategoryTable}.".$field.",";
}
$update = substr($update, 0, -1);
$update .= " WHERE {$mainStoreTable}.entity_id = {$catalogCategoryTable}.entity_id AND " .
"($catalogCategoryTable}.path like '{$parent->getPath()}/%' OR " .
"{$catalogCategoryTable}.path like '{$prevParent->getPath()}/%')";
$this->_getWriteAdapter()->query($update);
}
}
$prevParent = null;
$parent = null;
$_tmpCategory = null;
// $this->_move($categoryId, $prevParentPath, $parentPath);
return $this;
}
/**
* Prepare array of category data to insert or update.
* array(
* 'field_name' => 'value'
* )
*
* @param Varien_Object $category
* @param array $replaceFields
* @return array
*/
protected function _prepareDataForAllFields($category, $replaceFields = array())
{
$table = $this->getMainStoreTable($category->getStoreId());
$this->_getWriteAdapter()->resetDdlCache($table);
$table = $this->_getWriteAdapter()->describeTable($table);
$data = array();
$idFieldName = Mage::getSingleton('catalog/category')->getIdFieldName();
foreach ($table as $column => $columnData) {
if ($column != $idFieldName || null !== $category->getData($column)) {
if (key_exists($column, $replaceFields)) {
$value = $category->getData($replaceFields[$column]);
} else {
$value = $category->getData($column);
}
if (is_array($value)) {
$value = implode(',', $value);
}
$data[$column] = $value;
}
}
return $data;
}
/**
* Retrieve attribute instance
* Special for non static flat table
*
* @param mixed $attribute
* @return Mage_Eav_Model_Entity_Attribute_Abstract
*/
public function getAttribute($attribute)
{
return Mage::getSingleton('catalog/config')
->getAttribute(Mage_Catalog_Model_Category::ENTITY, $attribute);
}
/**
* Get count of active/not active children categories
*
* @param Mage_Catalog_Model_Category $category
* @param bool $isActiveFlag
* @return integer
*/
public function getChildrenAmount($category, $isActiveFlag = true)
{
$_table = $this->getMainStoreTable($category->getStoreId());
$select = $this->_getReadAdapter()->select()
->from($_table, "COUNT({$_table}.entity_id)")
->where("{$_table}.path LIKE ?", $category->getPath() . '/%')
->where("{$_table}.is_active = ?", (int) $isActiveFlag);
return (int) $this->_getReadAdapter()->fetchOne($select);
}
/**
* Get products count in category
*
* @param Mage_Catalog_Model_Category $category
* @return integer
*/
public function getProductCount($category)
{
$select = $this->_getReadAdapter()->select()
->from(
$this->getTable('catalog/category_product'),
"COUNT({$this->getTable('catalog/category_product')}.product_id)"
)
->where("{$this->getTable('catalog/category_product')}.category_id = ?", $category->getId())
->group("{$this->getTable('catalog/category_product')}.category_id");
return (int) $this->_getReadAdapter()->fetchOne($select);
}
/**
* Return parent categories of category
*
* @param Mage_Catalog_Model_Category $category
* @param bool $isActive
* @return array
*/
public function getParentCategories($category, $isActive = true)
{
$categories = array();
$select = $this->_getReadAdapter()->select()
->from(
array('main_table' => $this->getMainStoreTable($category->getStoreId())),
array('main_table.entity_id', 'main_table.name')
)
->where('main_table.entity_id IN (?)', array_reverse(explode(',', $category->getPathInStore())));
if ($isActive) {
$select->where('main_table.is_active = ?', '1');
}
$select->order('main_table.path ASC');
$urlRewrite = $this->_factory->getCategoryUrlRewriteHelper();
$urlRewrite->joinTableToSelect($select, $category->getStoreId());
$result = $this->_getReadAdapter()->fetchAll($select);
foreach ($result as $row) {
$row['id'] = $row['entity_id'];
$categories[$row['entity_id']] = Mage::getModel('catalog/category')->setData($row);
}
return $categories;
}
/**
* Return parent category of current category with own custom design settings
*
* @param Mage_Catalog_Model_Category $category
* @return Mage_Catalog_Model_Category
*/
public function getParentDesignCategory($category)
{
$adapter = $this->_getReadAdapter();
$levelField = $adapter->quoteIdentifier('level');
$pathIds = array_reverse($category->getPathIds());
$select = $adapter->select()
->from(array('main_table' => $this->getMainStoreTable($category->getStoreId())), '*')
->where('entity_id IN (?)', $pathIds)
->where('custom_use_parent_settings = ?', 0)
->where($levelField . ' != ?', 0)
->order('level ' . Varien_Db_Select::SQL_DESC);
$result = $adapter->fetchRow($select);
return Mage::getModel('catalog/category')->setData($result);
}
/**
* Return children categories of category
*
* @param Mage_Catalog_Model_Category $category
* @return array
*/
public function getChildrenCategories($category)
{
$categories = $this->_loadNodes($category, 1, $category->getStoreId());
return $categories;
}
/**
* Return children categories of category with inactive
*
* @param Mage_Catalog_Model_Category $category
* @return array
*/
public function getChildrenCategoriesWithInactive($category)
{
return $this->_loadNodes($category, 1, $category->getStoreId(), false);
}
/**
* Check is category in list of store categories
*
* @param Mage_Catalog_Model_Category $category
* @return boolean
*/
public function isInRootCategoryList($category)
{
$pathIds = $category->getParentIds();
return in_array(Mage::app()->getStore()->getRootCategoryId(), $pathIds);
}
/**
* Return children ids of category
*
* @param Mage_Catalog_Model_Category $category
* @param bool $recursive
* @param bool $isActive
* @return array
*/
public function getChildren($category, $recursive = true, $isActive = true)
{
$select = $this->_getReadAdapter()->select()
->from($this->getMainStoreTable($category->getStoreId()), 'entity_id')
->where('path LIKE ?', "{$category->getPath()}/%");
if (!$recursive) {
$select->where('level <= ?', $category->getLevel() + 1);
}
if ($isActive) {
$select->where('is_active = ?', '1');
}
$_categories = $this->_getReadAdapter()->fetchAll($select);
$categoriesIds = array();
foreach ($_categories as $_category) {
$categoriesIds[] = $_category['entity_id'];
}
return $categoriesIds;
}
/**
* Return all children ids of category (with category id)
*
* @param Mage_Catalog_Model_Category $category
* @return array
*/
public function getAllChildren($category)
{
$categoriesIds = $this->getChildren($category);
$myId = array($category->getId());
$categoriesIds = array_merge($myId, $categoriesIds);
return $categoriesIds;
}
/**
* Check if category id exist
*
* @param int $id
* @return bool
*/
public function checkId($id)
{
$select = $this->_getReadAdapter()->select()
->from($this->getMainStoreTable($this->getStoreId()), 'entity_id')
->where('entity_id=?', $id);
return $this->_getReadAdapter()->fetchOne($select);
}
/**
* Get design update data of parent categories
*
* @param Mage_Catalog_Model_Category $category
* @return array
*/
public function getDesignUpdateData($category)
{
$categories = array();
$pathIds = array();
foreach (array_reverse($category->getParentIds()) as $pathId) {
if ($pathId == Mage::app()->getStore()->getRootCategoryId()) {
$pathIds[] = $pathId;
break;
}
$pathIds[] = $pathId;
}
$select = $this->_getReadAdapter()->select()
->from(
array('main_table' => $this->getMainStoreTable($category->getStoreId())),
array(
'main_table.entity_id',
'main_table.custom_design',
'main_table.custom_design_apply',
'main_table.custom_design_from',
'main_table.custom_design_to',
)
)
->where('main_table.entity_id IN (?)', $pathIds)
->where('main_table.is_active = ?', '1')
->order('main_table.path ' . Varien_Db_Select::SQL_DESC);
$result = $this->_getReadAdapter()->fetchAll($select);
foreach ($result as $row) {
$row['id'] = $row['entity_id'];
$categories[$row['entity_id']] = Mage::getModel('catalog/category')->setData($row);
}
return $categories;
}
/**
* Retrieve anchors above
*
* @param array $filterIds
* @param int $storeId
* @return array
*/
public function getAnchorsAbove(array $filterIds, $storeId = 0)
{
$select = $this->_getReadAdapter()->select()
->from(array('e' => $this->getMainStoreTable($storeId)), 'entity_id')
->where('is_anchor = ?', 1)
->where('entity_id IN (?)', $filterIds);
return $this->_getReadAdapter()->fetchCol($select);
}
/**
* Retrieve array with root category id per store
*
* @param int|array $storeIds result limitation
* @return array
*/
public function getStoresRootCategories($storeIds = null)
{
if (is_null($this->_storesRootCategories)) {
$select = $this->_getWriteAdapter()->select()
->from(array('cs' => $this->getTable('core/store')), array('store_id'))
->join(
array('csg' => $this->getTable('core/store_group')),
'csg.group_id = cs.group_id',
array('root_category_id'))
->where('cs.store_id <> ?', Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID);
$this->_storesRootCategories = $this->_getWriteAdapter()->fetchPairs($select);
}
if (!is_null($storeIds)) {
if (!is_array($storeIds)) {
$storeIds = array($storeIds);
}
$stores = array();
foreach ($this->_storesRootCategories as $storeId => $rootId) {
if (in_array($storeId, $storeIds)) {
$stores[$storeId] = $rootId;
}
}
return $stores;
}
return $this->_storesRootCategories;
}
/**
* Creating table and adding attributes as fields to table for all stores
*
* @return Mage_Catalog_Model_Resource_Category_Flat
*/
protected function _createTables()
{
if ($this->_allowTableChanges) {
foreach (Mage::app()->getStores() as $store) {
$this->_createTable($store->getId());
}
}
return $this;
}
/**
* Transactional rebuild flat data from eav
*
* @throws Exception
* @return Mage_Catalog_Model_Resource_Category_Flat
*/
public function reindexAll()
{
$this->_createTables();
$allowTableChanges = $this->_allowTableChanges;
if ($allowTableChanges) {
$this->_allowTableChanges = false;
}
$this->beginTransaction();
try {
$this->rebuild();
$this->commit();
if ($allowTableChanges) {
$this->_allowTableChanges = true;
}
} catch (Exception $e) {
$this->rollBack();
if ($allowTableChanges) {
$this->_allowTableChanges = true;
}
throw $e;
}
return $this;
}
/**
* Check if Catalog Category Flat Data has been initialized
*
* @deprecated use Mage_Catalog_Model_Resource_Category_Flat::isBuilt() instead
*
* @return bool
*/
public function isRebuilt()
{
return $this->isBuilt();
}
}
| {
"content_hash": "a9534546bc7d1f74e825b8e7f4bb13a5",
"timestamp": "",
"source": "github",
"line_count": 1485,
"max_line_length": 119,
"avg_line_length": 34.43905723905724,
"alnum_prop": 0.5052598646904697,
"repo_name": "Louspirit/E-Commerce-Website",
"id": "02d960a86a8bf28ca86fec355020f2cfdfba2801",
"size": "52098",
"binary": false,
"copies": "14",
"ref": "refs/heads/master",
"path": "app/code/core/Mage/Catalog/Model/Resource/Category/Flat.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "19946"
},
{
"name": "CSS",
"bytes": "1655613"
},
{
"name": "JavaScript",
"bytes": "1036085"
},
{
"name": "PHP",
"bytes": "44369436"
},
{
"name": "PowerShell",
"bytes": "1028"
},
{
"name": "Ruby",
"bytes": "288"
},
{
"name": "Shell",
"bytes": "1753"
},
{
"name": "XSLT",
"bytes": "2066"
}
],
"symlink_target": ""
} |
#ifndef QmitkEuler3DTransformViewWidgetHIncluded
#define QmitkEuler3DTransformViewWidgetHIncluded
#include "ui_QmitkEuler3DTransformControls.h"
#include "MitkRigidRegistrationUIExports.h"
#include "QmitkRigidRegistrationTransformsGUIBase.h"
#include <itkImage.h>
/*!
* \brief Widget for rigid registration
*
* Displays options for rigid registration.
*/
class MITKRIGIDREGISTRATIONUI_EXPORT QmitkEuler3DTransformView : public QmitkRigidRegistrationTransformsGUIBase
{
public:
QmitkEuler3DTransformView( QWidget* parent = nullptr, Qt::WindowFlags f = nullptr );
~QmitkEuler3DTransformView();
virtual mitk::TransformParameters::TransformType GetTransformType() override;
virtual itk::Object::Pointer GetTransform() override;
virtual itk::Array<double> GetTransformParameters() override;
virtual void SetTransformParameters(itk::Array<double> transformValues) override;
virtual QString GetName() override;
virtual void SetupUI(QWidget* parent) override;
virtual itk::Array<double> GetScales() override;
virtual vtkTransform* Transform(vtkMatrix4x4* vtkmatrix, vtkTransform* vtktransform, itk::Array<double> transformParams) override;
virtual int GetNumberOfTransformParameters() override;
private:
template < class TPixelType, unsigned int VImageDimension >
itk::Object::Pointer GetTransform2(itk::Image<TPixelType, VImageDimension>* itkImage1);
protected:
Ui::QmitkEuler3DTransformControls m_Controls;
itk::Object::Pointer m_TransformObject;
double m_CenterX;
double m_CenterY;
double m_CenterZ;
};
#endif
| {
"content_hash": "9c1390affb2480bc752cb0ec6b59b981",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 132,
"avg_line_length": 26.491525423728813,
"alnum_prop": 0.7991042866282789,
"repo_name": "NifTK/MITK",
"id": "32d97bed34f7ee4e781d4cbbdfc0d5b4a7db610e",
"size": "2061",
"binary": false,
"copies": "5",
"ref": "refs/heads/niftk",
"path": "Modules/RigidRegistrationUI/RigidRegistrationTransforms/QmitkEuler3DTransformView.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "2343401"
},
{
"name": "C++",
"bytes": "28797565"
},
{
"name": "CMake",
"bytes": "864932"
},
{
"name": "CSS",
"bytes": "117579"
},
{
"name": "HTML",
"bytes": "101835"
},
{
"name": "JavaScript",
"bytes": "167070"
},
{
"name": "Makefile",
"bytes": "25077"
},
{
"name": "Objective-C",
"bytes": "476388"
},
{
"name": "Python",
"bytes": "62916"
},
{
"name": "QMake",
"bytes": "5583"
},
{
"name": "Shell",
"bytes": "1261"
}
],
"symlink_target": ""
} |
<html>
<head>
<title>OGRE: Member List - OGRE Documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link type="text/css" rel="stylesheet" href="doxygen.css">
<link type="text/css" rel="stylesheet" href="tabs.css">
</head>
<body>
<!-- Generated by Doxygen 1.7.4 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="dirs.html"><span>Directories</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="inherits.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespaceOgre.html">Ogre</a> </li>
<li class="navelem"><a class="el" href="classOgre_1_1Terrain.html">Terrain</a> </li>
<li class="navelem"><a class="el" href="structOgre_1_1Terrain_1_1DerivedDataResponse.html">DerivedDataResponse</a> </li>
</ul>
</div>
</div>
<div class="header">
<div class="headertitle">
<div class="title">Ogre::Terrain::DerivedDataResponse Member List</div> </div>
</div>
<div class="contents">
This is the complete list of members for <a class="el" href="structOgre_1_1Terrain_1_1DerivedDataResponse.html">Ogre::Terrain::DerivedDataResponse</a>, including all inherited members.<table>
<tr class="memlist"><td><a class="el" href="structOgre_1_1Terrain_1_1DerivedDataResponse.html#a364544a6a9c0c3a17c2ee11f6518b4dd">deltaUpdateRect</a></td><td><a class="el" href="structOgre_1_1Terrain_1_1DerivedDataResponse.html">Ogre::Terrain::DerivedDataResponse</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structOgre_1_1Terrain_1_1DerivedDataResponse.html#a4d21ac16f65468550c6946f16f1de15b">lightMapBox</a></td><td><a class="el" href="structOgre_1_1Terrain_1_1DerivedDataResponse.html">Ogre::Terrain::DerivedDataResponse</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structOgre_1_1Terrain_1_1DerivedDataResponse.html#a69fc735a122d3037bf10d9a897e379a1">lightmapUpdateRect</a></td><td><a class="el" href="structOgre_1_1Terrain_1_1DerivedDataResponse.html">Ogre::Terrain::DerivedDataResponse</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structOgre_1_1Terrain_1_1DerivedDataResponse.html#ae75d9cbcc311fd797178b17e553421f7">normalMapBox</a></td><td><a class="el" href="structOgre_1_1Terrain_1_1DerivedDataResponse.html">Ogre::Terrain::DerivedDataResponse</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structOgre_1_1Terrain_1_1DerivedDataResponse.html#a26f573c43021a442c89fbc3850a45d34">normalUpdateRect</a></td><td><a class="el" href="structOgre_1_1Terrain_1_1DerivedDataResponse.html">Ogre::Terrain::DerivedDataResponse</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structOgre_1_1Terrain_1_1DerivedDataResponse.html#a331febe763a7cdf5a376570c40294985">operator<<</a>(std::ostream &o, const DerivedDataResponse &r)</td><td><a class="el" href="structOgre_1_1Terrain_1_1DerivedDataResponse.html">Ogre::Terrain::DerivedDataResponse</a></td><td><code> [friend]</code></td></tr>
<tr class="memlist"><td><a class="el" href="structOgre_1_1Terrain_1_1DerivedDataResponse.html#ae47b1a81e0de479f34f0c48d315c0b1e">remainingTypeMask</a></td><td><a class="el" href="structOgre_1_1Terrain_1_1DerivedDataResponse.html">Ogre::Terrain::DerivedDataResponse</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structOgre_1_1Terrain_1_1DerivedDataResponse.html#aa8d6dfd215d499896823a6279cb37928">terrain</a></td><td><a class="el" href="structOgre_1_1Terrain_1_1DerivedDataResponse.html">Ogre::Terrain::DerivedDataResponse</a></td><td></td></tr>
</table></div>
<hr>
<p>
Copyright © 2008 Torus Knot Software Ltd<br />
<!--Creative Commons License--><a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-sa/3.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-ShareAlike 3.0 Unported License</a>.<br/>
<!--/Creative Commons License--><!-- <rdf:RDF xmlns="http://web.resource.org/cc/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<Work rdf:about="">
<license rdf:resource="http://creativecommons.org/licenses/by-sa/2.5/" />
<dc:type rdf:resource="http://purl.org/dc/dcmitype/Text" />
</Work>
<License rdf:about="http://creativecommons.org/licenses/by-sa/2.5/"><permits rdf:resource="http://web.resource.org/cc/Reproduction"/><permits rdf:resource="http://web.resource.org/cc/Distribution"/><requires rdf:resource="http://web.resource.org/cc/Notice"/><requires rdf:resource="http://web.resource.org/cc/Attribution"/><permits rdf:resource="http://web.resource.org/cc/DerivativeWorks"/><requires rdf:resource="http://web.resource.org/cc/ShareAlike"/></License></rdf:RDF> -->
Last modified Sat Jan 14 2012 18:40:57
</p>
</body>
</html>
| {
"content_hash": "a4f10b5402cc790ca8837dd1951285b5",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 481,
"avg_line_length": 86.77272727272727,
"alnum_prop": 0.7033350794482277,
"repo_name": "milram/ogre-1.7.4-osx",
"id": "269f69e96a9402cf1b29e81f85e271627af89829",
"size": "5727",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Docs/api/html/structOgre_1_1Terrain_1_1DerivedDataResponse-members.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package com.sumologic.marathon.client
import akka.actor.ActorSystem
import akka.util.Timeout
import com.sumologic.marathon.client.model.MarathonJsonProtocol._
import com.sumologic.marathon.client.model._
import spray.http._
import spray.httpx.SprayJsonSupport._
import scala.concurrent.{ExecutionContext, Future}
class ServerInfo private[client] (client: RestClient)
(implicit val system: ActorSystem, implicit val executor: ExecutionContext, implicit val timeout: Timeout) {
// Get info about the Marathon Instance.
def get(headers: List[HttpHeader] = List.empty): Future[model.ServerInfo] = {
client.get[model.ServerInfo](Marathon.Paths.Info, headers)
}
// Returns the current leader.
def leader(headers: List[HttpHeader] = List.empty): Future[Leader] = {
client.get[Leader](Marathon.Paths.Leader, headers)
}
// Causes the current leader to abdicate, triggering a new election.
def releaseLeader(headers: List[HttpHeader] = List.empty): Future[Message] = {
client.delete[Message](Marathon.Paths.Leader, headers)
}
}
| {
"content_hash": "dccd91a8fcaf63e2a69a15c717668f85",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 141,
"avg_line_length": 37.48275862068966,
"alnum_prop": 0.7405703771849126,
"repo_name": "SumoLogic/marathon-client",
"id": "ba26cbd65dd388da2c82d187a7785ff969720d32",
"size": "1893",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/scala/com/sumologic/marathon/client/ServerInfo.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "37142"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>GridPanel demo</title>
<!--Ext and ux styles -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/extjs/6.2.0/classic/theme-triton/resources/theme-triton-all.css" rel="stylesheet" type="text/css" />
<!--Ext JS includes -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/extjs/6.2.0/ext-all.js" crossorigin="anonymous" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/extjs/6.2.0/classic/theme-triton/theme-triton.js" crossorigin="anonymous" type="text/javascript"></script>
<!--Carto and styles -->
<link rel="stylesheet" href="https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/themes/css/cartodb.css" />
<script src="https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/cartodb.js"></script>
<!--Application files-->
<script src="gridpanel-example2.js" type="text/javascript"></script>
</head>
<body>
</body>
</html> | {
"content_hash": "c52e6a34e86e5c8090abb98e49e52385",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 162,
"avg_line_length": 40.03846153846154,
"alnum_prop": 0.6868395773294909,
"repo_name": "CrestoneDigital/extjs-carto",
"id": "362c0101b68a33d36dda7e23f3b720791e5ab13d",
"size": "1041",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/gridpanel/gridpanel-example2.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "2105"
},
{
"name": "JavaScript",
"bytes": "119047"
},
{
"name": "Ruby",
"bytes": "56"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wind.Geometry.Vectors;
namespace Macaw.Utilities
{
public class mSampleBitmap
{
Bitmap bmp = null;
Color color = Color.White;
public mSampleBitmap()
{
}
public mSampleBitmap(Bitmap SourceBitmap)
{
bmp = SourceBitmap;
}
public Color Sample(double X, double Y)
{
return bmp.GetPixel((int)(bmp.Width * X), bmp.Height-(int)(bmp.Height * Y)-1);
}
}
}
| {
"content_hash": "056246022feaa36917a07f3df03e2ff4",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 90,
"avg_line_length": 19.40625,
"alnum_prop": 0.5974235104669887,
"repo_name": "interopxyz/Aviary",
"id": "caad397183a55e6a7a3d45a877d983387de1d1cc",
"size": "623",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Macaw/Utilities/mSampleBitmap.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "2042749"
}
],
"symlink_target": ""
} |
`laravel-admin` has built-in` RBAC` permissions control module, expand the left sidebar `Auth`, you can see user, permissions and roles management panel, the use of permissions control as follows:
## Route permission
In the `laravel-admin 1.5`, the permissions and routes are bound together, in the edit permission page which set the current permissions can access the routing, in the `HTTP method` select box to select the method of access to the path, in the `HTTP path` textarea fill in the path to access.
For example, to add a permission, the permission can access the path `/admin/users` in GET method, then `HTTP method` select `GET`, `HTTP path` fill in `/users`.
If you want to access all paths with the prefix `/admin/users`, then the `HTTP path` fill in `/users*`, if the permissions include multiple access paths, wrap the line for each path.
## Page permission
If you want to control the user's permissions in the page, you can refer to the following example
### example1
For example, there is now a scene, here is a article module, we use create articles as an example
At first open `http://localhost/admi/auth/permissions`, fill up slug field with text `create-post`, and `Create post` in name field, then assign this permission to some roles.
In your controller action:
```php
use Encore\Admin\Auth\Permission;
class PostController extends Controller
{
public function create()
{
// check permission, only the roles with permission `create-post` can visit this action
Permission::check('create-post');
}
}
```
### example2
If you want to control the page elements of the user's display, then you need to first define permissions, such as `delete-image` and `view-title-column`, respectively, to control the permissions to delete pictures and display a column in grid, then assign these two permissions to roles, add following code to the grid:
```php
$grid->actions(function ($actions) {
// The roles with this permission will not able to see the delete button in actions column.
if (!Admin::user()->can('delete-image')) {
$actions->disableDelete();
}
});
// Only roles with permission `view-title-column` can view this column in grid
if (Admin::user()->can('view-title-column')) {
$grid->column('title');
}
```
## Other methods
Get current user object.
```php
Admin::user();
```
Get current user id.
```php
Admin::user()->id;
```
Get user's roles.
```php
Admin::user()->roles;
```
Get user's permissions.
```php
Admin::user()->permissions;
```
User is role.
```php
Admin::user()->isRole('developer');
```
User has permission.
```php
Admin::user()->can('create-post');
```
User don't has permission.
```php
Admin::user()->cannot('delete-post');
```
Is user super administrator.
```php
Admin::user()->isAdministrator();
```
Is user in one of roles.
```php
Admin::user()->inRoles(['editor', 'developer']);
```
## Permission middleware
You can use permission middleware in the routes to control the routing permission
```php
// Allow roles `administrator` and `editor` access the routes under group.
Route::group([
'middleware' => 'admin.permission:allow,administrator,editor',
], function ($router) {
$router->resource('users', UserController::class);
...
});
// Deny roles `developer` and `operator` access the routes under group.
Route::group([
'middleware' => 'admin.permission:deny,developer,operator',
], function ($router) {
$router->resource('users', UserController::class);
...
});
// User has permission `edit-post`、`create-post` and `delete-post` can access routes under group.
Route::group([
'middleware' => 'admin.permission:check,edit-post,create-post,delete-post',
], function ($router) {
$router->resource('posts', PostController::class);
...
});
```
The usage of permission middleware is just as same as other middleware.
| {
"content_hash": "8bb7420399b8c2dd66d1d823e825d3b0",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 320,
"avg_line_length": 28.007194244604317,
"alnum_prop": 0.7025430259440021,
"repo_name": "never615/laravel-admin",
"id": "dc7bfc206ad798223821fcc7c355013befa34f66",
"size": "3915",
"binary": false,
"copies": "3",
"ref": "refs/heads/1.5_master",
"path": "docs/en/permission.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Blade",
"bytes": "156379"
},
{
"name": "CSS",
"bytes": "157087"
},
{
"name": "JavaScript",
"bytes": "218363"
},
{
"name": "PHP",
"bytes": "1125468"
}
],
"symlink_target": ""
} |
var assert = require("assert");
var _ = require('../bower_components/lodash/lodash');
var WEBSOCKET_SERVICE = 'http://localhost:5280/http-bind';
var Logger = require('../src/logger');
var HaikuConnection = require('../src/haiku-connection');
var HaikuChatRoom = require('../src/haiku-chat-room');
var adminuser = "spring@dev.spring.co.nz";
var adminpassword = "spring";
var user1 = "atestuser@dev.spring.co.nz";
var user2 = "atestuser2@dev.spring.co.nz";
var password = "testing";
var user1Nick = "tester1";
var user2Nick = "tester2";
var roomName = "mamtest";
var chatService = "conference.dev.spring.co.nz";
var fullRoomName = roomName + "@" + chatService;
var destroyMsg = "Done with test";
var disconnect = function(done, err, h1, h2) {
if(h1) h1.disconnect();
if(h2) h2.disconnect();
setTimeout(() => {
if(err) done(err);
else done();
}, 500);
}
describe("muc", function(){
describe("good scenarios", function(){
it("should report chat services", function(done){
this.timeout(10000);
new HaikuConnection(user1, password, WEBSOCKET_SERVICE)
.then(haiku => haiku.listChatServers()
.then(servers => {
if(servers.indexOf(chatService) >=0 ) disconnect(done, null, haiku);
disconnect(done, "Couldn't find conference server", haiku);
})
)
.catch(err => done(err));
});
// it('should report chat rooms', function(done){
// this.timeout(10000);
// new HaikuConnection(adminuser, adminpassword, WEBSOCKET_SERVICE, h => {}, new Logger(Strophe.LogLevel.INFO, user1))
// .then(haiku => { haiku.createNewChatRoom(roomName, "admin", chatService, true); return haiku; })
// .then(haiku => haiku.listChatRooms(chatService).then(chatrooms => {
// assert.ok(_.any(chatrooms, c => c.id == fullRoomName));
// disconnect(done, null, haiku);
// }))
// .catch(err => done(err));
// });
describe("chatting", function(){
var createRoom = function(){
return new HaikuConnection(adminuser, adminpassword, WEBSOCKET_SERVICE)
.then(haiku => haiku.createNewChatRoom(roomName, "admin", chatService, true).then(() => haiku.disconnect()));
};
var destroyRoom = function(){
return new HaikuConnection(adminuser, adminpassword, WEBSOCKET_SERVICE)
.then(haiku => haiku.destroyChatRoom(roomName, chatService, destroyMsg).then(() => haiku.disconnect()));
};
var chatTest = function(done, cb) {
createRoom().then(() => cb())
.then(() => destroyRoom())
.then(() => done())
.catch(err => done(err));
}
it("should connect", function(done){
this.timeout(20000);
chatTest(done, () =>
new HaikuChatRoom(user1, password, WEBSOCKET_SERVICE, fullRoomName, user1Nick)
.then(muc => { assert.equal(muc.nickname, user1Nick); return muc.leave(); })
);
});
it("should leave", function(done){
this.timeout(20000);
chatTest(done, () =>
new HaikuChatRoom(user1, password, WEBSOCKET_SERVICE, fullRoomName, user1Nick)
.then(muc => muc.leave())
);
});
it("should have roster stream", function(done) {
this.timeout(20000);
var muc2 = null;
chatTest(done, () =>
new HaikuChatRoom(user1, password, WEBSOCKET_SERVICE, fullRoomName, user1Nick)
.then(muc => {
return new Promise((resolve) => {
muc.createRosterStream().onValue(v => {
if(v.user == user2Nick && v.status == 'available') {
setTimeout( () => {
Promise.all([
muc.leave(),
muc2.leave()
]).then(() => resolve());
}, 1000);
}
});
new HaikuChatRoom(user2, password, WEBSOCKET_SERVICE, fullRoomName, user2Nick).then(m2 => { muc2 = m2; });
});
})
);
});
it("should have delayed roster stream", function(done) {
this.timeout(20000);
var muc2 = null;
chatTest(done, () =>
Promise.all([
new HaikuChatRoom(user1, password, WEBSOCKET_SERVICE, fullRoomName, user1Nick),
new HaikuChatRoom(user2, password, WEBSOCKET_SERVICE, fullRoomName, user2Nick)
])
.then(haikus => {
return new Promise(resolve => {
setTimeout(() => {
haikus[0].createRosterStream().onValue(v => {
if(v.user == user2Nick && v.status == 'available') {
Promise.all([
haikus[0].leave(),
haikus[1].leave()
]).then(() => resolve());
}
});
}, 2000);
});
})
);
});
it("should have leave notification", function(done) {
this.timeout(20000);
chatTest(done, () =>
new HaikuChatRoom(user1, password, WEBSOCKET_SERVICE, fullRoomName, user1Nick )
.then(muc => {
return new Promise((resolve) => {
muc.createRosterStream().onValue(v => {
if(v.user == user2Nick && v.status == 'unavailable') {
muc.leave().then(()=>resolve());
}
});
new HaikuChatRoom(user2, password, WEBSOCKET_SERVICE, fullRoomName, user2Nick)
.then(muc2 => muc2.leave())
});
})
);
});
it("should have status change notification", function(done) {
this.timeout(20000);
var status = "away";
var showMsg = "testMsg";
var muc2 = null;
chatTest(done, () =>
new HaikuChatRoom(user1, password, WEBSOCKET_SERVICE, fullRoomName, user1Nick )
.then(muc => {
return new Promise((resolve) => {
muc.createRosterStream().onValue(v => {
if(v.user == user2Nick && v.status == status && v.showMsg == showMsg) {
Promise.all([
muc.leave(),
muc2.leave()
]).then(()=>resolve());
}
});
new HaikuChatRoom(user2, password, WEBSOCKET_SERVICE, fullRoomName, user2Nick)
.then(m2 => { muc2 = m2; muc2.setStatus(status, showMsg); })
});
})
);
});
it("should have group chat", function(done) {
this.timeout(20000);
var muc2 = null;
var message = "test message";
chatTest(done, () =>
new HaikuChatRoom(user1, password, WEBSOCKET_SERVICE, fullRoomName, user1Nick, false )
.then(muc => {
return new Promise((resolve) => {
muc.createGroupChatStream().onValue(v => {
if(v.from == user2Nick && v.message == message && v.id) {
Promise.all([
muc.leave(),
muc2.leave()
]).then(()=>resolve());
}
});
new HaikuChatRoom(user2, password, WEBSOCKET_SERVICE, fullRoomName, user2Nick, false)
.then(m2 => { muc2 = m2; muc2.sendGroupChat(message); muc2.sendGroupChat(message); })
});
})
);
});
it("should support multiple subscribers in group chat", function(done){
this.timeout(20000);
var hadOne = false;
var hadTwo = false;
var muc2 = null;
var message = "test message";
chatTest(done, () =>
new HaikuChatRoom(user1, password, WEBSOCKET_SERVICE, fullRoomName, user1Nick, false )
.then(muc => {
return new Promise((resolve, reject) => {
muc.createGroupChatStream().onValue(v => {
hadOne = true;
});
muc.createGroupChatStream().onValue(v => {
hadTwo = true;
});
new HaikuChatRoom(user2, password, WEBSOCKET_SERVICE, fullRoomName, user2Nick, false)
.then(m2 => { muc2 = m2; muc2.sendGroupChat(message); })
.then(() => {
setTimeout(() => Promise.all([
muc.leave(),
muc2.leave()
]).then(()=> (hadOne && hadTwo) ? resolve() : reject("Didn't have both streams"))
, 3000);
})
});
})
);
});
it("should have group chat unsubscribe", function(done){
this.timeout(20000);
var muc2 = null;
var message = "test message";
chatTest(done, () =>
new HaikuChatRoom(user1, password, WEBSOCKET_SERVICE, fullRoomName, user1Nick, false )
.then(muc => {
return new Promise((resolve, reject) => {
var msgCount = 0;
var unsub = muc.createGroupChatStream().onValue(v => {
if(msgCount == 1) {
Promise.all([
muc.leave(),
muc2.leave()
]).then(()=>reject("Shouldn't have received message!"));
}
else {
unsub();
msgCount++;
}
});
new HaikuChatRoom(user2, password, WEBSOCKET_SERVICE, fullRoomName, user2Nick, false)
.then(m2 => { muc2 = m2; muc2.sendGroupChat(message); })
.then(m2 => { setTimeout( () => muc2.sendGroupChat(message), 1000); })
.then(() => {
setTimeout(() => Promise.all([
muc.leave(),
muc2.leave()
]).then(()=>resolve())
, 3000);
})
});
})
);
});
it("shouldn't double after group chat unsubscribe", function(done){
this.timeout(20000);
var muc2 = null;
var message = "test message";
var msgCount = 0;
chatTest(done, () =>
new HaikuChatRoom(user1, password, WEBSOCKET_SERVICE, fullRoomName, user1Nick, false )
.then(muc => {
return new Promise((resolve, reject) => {
var unsub = muc.createGroupChatStream().onValue(v => {
unsub();
msgCount++;
muc.createGroupChatStream().onValue(v => {
msgCount++
if(msgCount >= 3) {
Promise.all([
muc.leave(),
muc2.leave()
]).then(()=>reject("Shouldn't have received message!"));
}
else {
setTimeout(() => Promise.all([
muc.leave(),
muc2.leave()
]).then(()=>resolve())
, 3000);
}
});
muc2.sendGroupChat(message);
});
new HaikuChatRoom(user2, password, WEBSOCKET_SERVICE, fullRoomName, user2Nick, false)
.then(m2 => { muc2 = m2; muc2.sendGroupChat(message); })
});
})
);
});
it("should have private chat", function(done) {
this.timeout(10000);
var muc2 = null;
var message = "test message";
chatTest(done, () =>
new HaikuChatRoom(user1, password, WEBSOCKET_SERVICE, fullRoomName, user1Nick, false )
.then(muc => {
return new Promise((resolve, reject) => {
muc.createGroupChatStream().onValue(v => {
muc.leave();
muc2.leave();
reject("Should have been a private chat");
});
muc.createPrivateChatStream().onValue(v => {
if(v.from == user2Nick && v.message == message) {
Promise.all([
muc.leave(),
muc2.leave()
]).then(()=>resolve());
}
});
new HaikuChatRoom(user2, password, WEBSOCKET_SERVICE, fullRoomName, user2Nick, false)
.then(m2 => { muc2 = m2; muc2.sendPrivateChat(user1Nick, message); })
});
})
);
});
it("should have chat history", function(done){
this.timeout(10000);
var time = new Date().toISOString();
chatTest(done, () =>
new HaikuChatRoom(user1, password, WEBSOCKET_SERVICE, fullRoomName, user1Nick, false )
.then(muc => {
var msg = "HaikuChatRoom test message";
var numMessages = 10;
var time = new Date().toISOString();
var msgs = [];
for (var i = 0; i < 10; i++) {
muc.sendGroupChat(msg + i);
};
return new Promise((resolve, reject) => {
new HaikuChatRoom(user2, password, WEBSOCKET_SERVICE, fullRoomName, user2Nick, true)
.then(muc2 => {
var totalRead = 0;
muc2.createGroupChatStream({start: time}).onValue(v => {
if(v.from == user1Nick && v.message.indexOf(msg) >= 0 && v.id) totalRead++;
if(totalRead == 10) {
Promise.all([
muc.leave(),
muc2.leave()
]).then(()=>resolve());
}
});
});
});
})
);
});
describe("out of band", function() {
it("should have group chat", function(done){
this.timeout(10000);
var url = 'https://d18l82el6cdm1i.cloudfront.net/image_optimizer/c29cae44a944374258170057f8223712b5fec498.jpg';
var desc = 'space shuttle';
chatTest(done, () =>
Promise.all([
new HaikuChatRoom(user1, password, WEBSOCKET_SERVICE, fullRoomName, user1Nick),
new HaikuChatRoom(user2, password, WEBSOCKET_SERVICE, fullRoomName, user2Nick)
])
.then(mucs => {
return new Promise((resolve, reject) => {
mucs[0].createGroupChatStream().onValue( v => {
var err;
if(v.from != user2Nick) err = "Not from user2";
if(v.attachmentType != 'image') err = "Type not image";
if(v.url != url) err = "Url not ";
if(v.ext != 'jpg') err = "Extension not jpg";
if(v.desc != desc) err = "Description not " + desc;
Promise.all([
mucs[0].leave(),
mucs[1].leave()
]).then(()=> {
if(!err) resolve();
else reject(err);
});
});
mucs[1].sendGroupImage(url, desc);
});
})
.catch(err => done(err))
);
});
it("should have private chat", function(done){
this.timeout(10000);
var url = 'https://d18l82el6cdm1i.cloudfront.net/image_optimizer/c29cae44a944374258170057f8223712b5fec498.jpg';
var desc = 'space shuttle';
chatTest(done, () =>
Promise.all([
new HaikuChatRoom(user1, password, WEBSOCKET_SERVICE, fullRoomName, user1Nick),
new HaikuChatRoom(user2, password, WEBSOCKET_SERVICE, fullRoomName, user2Nick)
])
.then(mucs => {
return new Promise((resolve, reject) => {
mucs[0].createPrivateChatStream().onValue( v => {
var err;
if(v.from != user2Nick) err = "Not from user2";
if(v.attachmentType != 'image') err = "Type not image";
if(v.url != url) err = "Url not ";
if(v.ext != 'jpg') err = "Extension not jpg";
if(v.desc != desc) err = "Description not " + desc;
Promise.all([
mucs[0].leave(),
mucs[1].leave()
]).then(()=> {
if(!err) resolve();
else reject(err);
});
});
mucs[1].sendPrivateImage(user1Nick, url, desc);
});
})
.catch(err => done(err))
);
});
it("should have group history", function(done){
this.timeout(10000);
var time = new Date().toISOString();
var url = 'https://d18l82el6cdm1i.cloudfront.net/image_optimizer/c29cae44a944374258170057f8223712b5fec498.jpg';
var desc = 'space shuttle';
var totalRead = 0;
chatTest(done, () =>
new HaikuChatRoom(user1, password, WEBSOCKET_SERVICE, fullRoomName, user1Nick, false )
.then(muc => {
var numMessages = 2;
var msgs = [];
for (var i = 0; i < numMessages; i++) {
muc.sendGroupImage(url, desc);
};
return new Promise((resolve, reject) => {
new HaikuChatRoom(user2, password, WEBSOCKET_SERVICE, fullRoomName, user2Nick, true)
.then(muc2 => {
var whenDone = () => {
if(totalRead == numMessages) {
Promise.all([
muc.leave(),
muc2.leave()
]).then(()=>resolve());
}
}
muc2.createGroupChatStream({start: time, onHistoryDone: whenDone }).onValue(v => {
if( v.from == user1Nick &&
v.attachmentType == 'image' &&
v.type == 'groupchat' &&
v.url == url &&
v.ext == 'jpg' &&
v.desc == desc ) totalRead++;
});
});
});
})
);
});
});
});
});
describe("error scenarios", function(){
//bad conference server
//unauth room creation
//unauth room destruction
});
}); | {
"content_hash": "d9e1e948708d954d4c4834a0329fb24b",
"timestamp": "",
"source": "github",
"line_count": 514,
"max_line_length": 121,
"avg_line_length": 31.14396887159533,
"alnum_prop": 0.5438530734632684,
"repo_name": "springnz/haiku",
"id": "b056bd876dbd323de48d44ecaf23fd2a52dda744",
"size": "16008",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/muc_tests.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "59002"
}
],
"symlink_target": ""
} |
package com.syncano.library.simple;
import com.syncano.library.Syncano;
import com.syncano.library.api.IncrementBuilder;
import com.syncano.library.api.Response;
import com.syncano.library.api.SendRequest;
import com.syncano.library.callbacks.SyncanoCallback;
import com.syncano.library.data.Entity;
import com.syncano.library.data.SyncanoObject;
import com.syncano.library.offline.OfflineDeleteRequest;
import com.syncano.library.offline.OfflineFetchRequest;
import com.syncano.library.offline.OfflineMode;
import com.syncano.library.offline.OfflineRequest;
import com.syncano.library.offline.OfflineSaveRequest;
import java.util.HashSet;
/**
* It could be a part of code in SyncanoObject class but this class was made to divide pure data kept
* by SyncanoObject and logic behind building request affecting this specific object.
* Only SyncanoObject can inherit this class.
*/
public abstract class ObjectRequestBuilder extends Entity {
private Syncano syncano;
private IncrementBuilder incrementBuilder = new IncrementBuilder();
private HashSet<String> fieldsToClear = new HashSet<>();
private OfflineMode mode = null;
private Boolean cleanStorageOnSuccessDownload = null;
private Boolean saveDownloadedDataToStorage = null;
private SyncanoCallback<? extends SyncanoObject> backgroundCallback;
public <T extends SyncanoObject> T clearField(String fieldName) {
fieldsToClear.add(fieldName);
return (T) this;
}
public <T extends SyncanoObject> T removeFromClearList(String fieldName) {
fieldsToClear.remove(fieldName);
return (T) this;
}
public boolean isOnClearList(String fieldName) {
return fieldsToClear.contains(fieldName);
}
public boolean hasAnyFieldsToClear() {
return !fieldsToClear.isEmpty();
}
public IncrementBuilder getIncrementBuilder() {
return incrementBuilder;
}
public <T extends SyncanoObject> T increment(String fieldName, int value) {
incrementBuilder.increment(fieldName, value);
return (T) this;
}
public <T extends SyncanoObject> T decrement(String fieldName, int value) {
incrementBuilder.decrement(fieldName, value);
return (T) this;
}
public Syncano getSyncano() {
if (syncano == null) {
return Syncano.getInstance();
}
return syncano;
}
public <T extends SyncanoObject> T on(Syncano syncano) {
this.syncano = syncano;
return (T) this;
}
public <T extends SyncanoObject> Response<T> save() {
OfflineSaveRequest<T> req = prepareSaveRequest(true);
return req.send();
}
public <T extends SyncanoObject> void save(SyncanoCallback<T> callback) {
OfflineSaveRequest<T> req = prepareSaveRequest(false);
req.sendAsync(callback);
}
public <T extends SyncanoObject> Response<T> delete() {
OfflineDeleteRequest<T> req = prepareDeleteRequest();
return req.send();
}
public <T extends SyncanoObject> void delete(SyncanoCallback<T> callback) {
OfflineDeleteRequest<T> req = prepareDeleteRequest();
req.sendAsync(callback);
}
public <T extends SyncanoObject> Response<T> fetch() {
OfflineFetchRequest<T> req = prepareFetchRequest();
return req.send();
}
public <T extends SyncanoObject> void fetch(SyncanoCallback<T> callback) {
OfflineFetchRequest<T> req = prepareFetchRequest();
req.sendAsync(callback);
}
public void resetRequestBuildingFields() {
incrementBuilder = new IncrementBuilder();
fieldsToClear = new HashSet<>();
mode = null;
cleanStorageOnSuccessDownload = null;
saveDownloadedDataToStorage = null;
}
private <T extends SyncanoObject> void decorateOfflineRequest(OfflineRequest<T> request) {
if (mode != null) {
request.mode(mode);
}
if (cleanStorageOnSuccessDownload != null) {
request.cleanStorageOnSuccessDownload(cleanStorageOnSuccessDownload);
}
if (saveDownloadedDataToStorage != null) {
request.saveDownloadedDataToStorage(saveDownloadedDataToStorage);
}
request.setBackgroundCallback((SyncanoCallback<T>) backgroundCallback);
}
private <T extends SyncanoObject> OfflineSaveRequest<T> prepareSaveRequest(boolean updateGivenObject) {
SendRequest<T> onlineRequest;
if (getId() == null) {
onlineRequest = getSyncano().createObject((T) this, updateGivenObject);
} else {
onlineRequest = getSyncano().updateObject((T) this, updateGivenObject);
}
OfflineSaveRequest<T> offlineRequest = new OfflineSaveRequest<>(onlineRequest);
decorateOfflineRequest(offlineRequest);
return offlineRequest;
}
private <T extends SyncanoObject> OfflineFetchRequest<T> prepareFetchRequest() {
OfflineFetchRequest<T> offlineRequest = new OfflineFetchRequest<>(getSyncano().getObject((T) this));
decorateOfflineRequest(offlineRequest);
return offlineRequest;
}
private <T extends SyncanoObject> OfflineDeleteRequest<T> prepareDeleteRequest() {
OfflineDeleteRequest<T> offlineRequest = new OfflineDeleteRequest<>(getSyncano().deleteObject((T) this));
decorateOfflineRequest(offlineRequest);
return offlineRequest;
}
public ObjectRequestBuilder mode(OfflineMode mode) {
this.mode = mode;
return this;
}
public ObjectRequestBuilder cleanStorageOnSuccessDownload(boolean clean) {
this.cleanStorageOnSuccessDownload = clean;
return this;
}
public ObjectRequestBuilder saveDownloadedDataToStorage(boolean save) {
this.saveDownloadedDataToStorage = save;
return this;
}
public ObjectRequestBuilder backgroundCallback(SyncanoCallback<? extends SyncanoObject> callback) {
this.backgroundCallback = callback;
return this;
}
}
| {
"content_hash": "7c52874c79bf53f72818297bb621ab41",
"timestamp": "",
"source": "github",
"line_count": 170,
"max_line_length": 113,
"avg_line_length": 35.48823529411764,
"alnum_prop": 0.6996519144704128,
"repo_name": "Syncano/syncano-android",
"id": "d7a34412a97a1e23f9f57d79cfdd34c16496c2f5",
"size": "6033",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "library/src/main/java/com/syncano/library/simple/ObjectRequestBuilder.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "634674"
}
],
"symlink_target": ""
} |
Maven project for Google App Engine with Jersey, Jackson, and JDO dependencies.
| {
"content_hash": "d4f678176ee351181107ce45753c03d6",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 79,
"avg_line_length": 80,
"alnum_prop": 0.8125,
"repo_name": "kerafill1116/appengine-jersey-jackson-jdo",
"id": "a9ece8cb1196c7e1a149cf71ffdec00778a5d555",
"size": "111",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/**
* Created by thomas on 02/09/17.
*/
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/reduce';
export interface Field {
readonly name: string;
readonly type: any;
value?: any
subtype?: 'html'|'choices'|'image';
choices?: string[];
relation?: Entity;
required?: boolean; // used when parsing, in the update/creation page
hiddenFromList?: boolean // if field is shown from the list view
hiddenFromDetail?: boolean // if field is shown from the list view
}
export interface QueryParamsInterface {
sort: string;
limit: number;
skip: number;
order: number;
}
export class Entity {
private _id: string;
public constructor(public title: string,
public fields: Field[],
private _materialIcon: string = '') {
// check duplicate field name
for (let field of fields){
if (fields.filter(f => f.name == field.name).length > 1)
throw `Duplicate field name '${field.name}' in Entity: ${title}`;
}
}
public clone(): Entity{
return new Entity(this.title, this.fields, this._materialIcon);
}
public parse(jsonData: any): void {
this._id = jsonData._id || jsonData._id;
// if (!this._id)
// throw Entity.getParsingErrorMessage('_id', jsonData);jsonData
// match each item with one field
for (let field of this.fields){
if (!(field.name in jsonData))
throw `Can't find ${field.name} when parsing object:\n\t ${JSON.stringify(jsonData, null, 1)}`;
if (field.type instanceof Entity){
let childEntity = field.type;
childEntity.parse(jsonData[field.name]);
}
else
field.value = jsonData[field.name] || '';
}
}
// return a json object
public toDict(): any{
let outputJson: any = {'id': this._id};
for (let field of this.fields){
if (field.type == 'string')
outputJson[field.name] = field.value;
else if (field.type == 'float' || field.type == 'number')
outputJson[field.name] = parseFloat(field.value);
else if (field.type == 'int')
outputJson[field.name] = parseInt(field.value);
else if (field.type == 'date')
outputJson[field.name] = new Date(field.value);
else if (field.type instanceof Entity)
outputJson[field.name] = Object.values(field.type.toDict()).filter(x => x);
}
return outputJson;
}
get materialIcon(): string {
return this._materialIcon;
}
get id(): string {
return this._id;
}
}
| {
"content_hash": "8e71f720ead3d9b4d92f6d14a61ccf33",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 104,
"avg_line_length": 27.01063829787234,
"alnum_prop": 0.6132335565183143,
"repo_name": "Thomas-Webber/webberAdmin",
"id": "b8fb072c41a225005016b7b7ccc05b97285b08e4",
"size": "2539",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/entities/entity.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3194"
},
{
"name": "HTML",
"bytes": "6006"
},
{
"name": "JavaScript",
"bytes": "1645"
},
{
"name": "TypeScript",
"bytes": "34695"
}
],
"symlink_target": ""
} |
using Serenity;
using Serenity.ComponentModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
namespace CoinNews.Northwind
{
public partial class EmployeeListFormatterAttribute : CustomFormatterAttribute
{
public const string Key = "CoinNews.Northwind.EmployeeListFormatter";
public EmployeeListFormatterAttribute()
: base(Key)
{
}
}
}
| {
"content_hash": "c0456419e753f21564ef126809a8838b",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 82,
"avg_line_length": 22.6,
"alnum_prop": 0.7212389380530974,
"repo_name": "knifecaojia/CoinsPro",
"id": "4221d52ef52669ea67ade764d540f79c8b25e71f",
"size": "454",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Src/YTWL/WeiXin/CoinNews/CoinNews/CoinNews/CoinNews.Web/Imports/ClientTypes/Northwind.EmployeeListFormatterAttribute.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "85487"
},
{
"name": "Batchfile",
"bytes": "129"
},
{
"name": "C#",
"bytes": "4102154"
},
{
"name": "CSS",
"bytes": "2438620"
},
{
"name": "HTML",
"bytes": "2000982"
},
{
"name": "JavaScript",
"bytes": "17880569"
},
{
"name": "PLSQL",
"bytes": "606471"
},
{
"name": "PLpgSQL",
"bytes": "901205"
},
{
"name": "PowerShell",
"bytes": "3737"
},
{
"name": "Python",
"bytes": "121482"
},
{
"name": "TypeScript",
"bytes": "332184"
}
],
"symlink_target": ""
} |
<?php
namespace Assetic\Test\Extension\Twig;
use Assetic\Factory\AssetFactory;
use Assetic\Extension\Twig\AsseticExtension;
use Assetic\Asset\AssetCollection;
use Assetic\Asset\FileAsset;
class AsseticExtensionTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Assetic\AssetManager
*/
private $am;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Assetic\FilterManager
*/
private $fm;
/**
* @var AssetFactory
*/
private $factory;
/**
* @var \Twig_Environment
*/
private $twig;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Assetic\ValueSupplierInterface
*/
private $valueSupplier;
protected function setUp()
{
if (!class_exists('Twig_Environment')) {
$this->markTestSkipped('Twig is not installed.');
}
$this->am = $this->getMock('Assetic\\AssetManager');
$this->fm = $this->getMock('Assetic\\FilterManager');
$this->valueSupplier = $this->getMock('Assetic\ValueSupplierInterface');
$this->factory = new AssetFactory(__DIR__.'/templates');
$this->factory->setAssetManager($this->am);
$this->factory->setFilterManager($this->fm);
$this->twig = new \Twig_Environment();
$this->twig->setLoader(new \Twig_Loader_Filesystem(__DIR__.'/templates'));
$this->twig->addExtension(new AsseticExtension($this->factory, array(), $this->valueSupplier));
}
public function testReference()
{
$asset = $this->getMock('Assetic\\Asset\\AssetInterface');
$this->am->expects($this->any())
->method('get')
->with('foo')
->will($this->returnValue($asset));
$xml = $this->renderXml('reference.twig');
$this->assertEquals(1, count($xml->asset));
$this->assertStringStartsWith('css/', (string) $xml->asset['url']);
}
public function testGlob()
{
$xml = $this->renderXml('glob.twig');
$this->assertEquals(1, count($xml->asset));
$this->assertStringStartsWith('css/', (string) $xml->asset['url']);
}
public function testAbsolutePath()
{
$xml = $this->renderXml('absolute_path.twig');
$this->assertEquals(1, count($xml->asset));
$this->assertStringStartsWith('css/', (string) $xml->asset['url']);
}
public function testFilters()
{
$filter = $this->getMock('Assetic\\Filter\\FilterInterface');
$this->fm->expects($this->at(0))
->method('get')
->with('foo')
->will($this->returnValue($filter));
$this->fm->expects($this->at(1))
->method('get')
->with('bar')
->will($this->returnValue($filter));
$xml = $this->renderXml('filters.twig');
$this->assertEquals(1, count($xml->asset));
$this->assertStringStartsWith('css/', (string) $xml->asset['url']);
}
public function testOptionalFilter()
{
$filter = $this->getMock('Assetic\\Filter\\FilterInterface');
$this->fm->expects($this->once())
->method('get')
->with('foo')
->will($this->returnValue($filter));
$xml = $this->renderXml('optional_filter.twig');
$this->assertEquals(1, count($xml->asset));
$this->assertStringStartsWith('css/', (string) $xml->asset['url']);
}
public function testOutputPattern()
{
$xml = $this->renderXml('output_pattern.twig');
$this->assertEquals(1, count($xml->asset));
$this->assertStringStartsWith('css/packed/', (string) $xml->asset['url']);
$this->assertStringEndsWith('.css', (string) $xml->asset['url']);
}
public function testOutput()
{
$xml = $this->renderXml('output_url.twig');
$this->assertEquals(1, count($xml->asset));
$this->assertEquals('explicit_url.css', (string) $xml->asset['url']);
}
public function testMixture()
{
$asset = $this->getMock('Assetic\\Asset\\AssetInterface');
$this->am->expects($this->any())
->method('get')
->with('foo')
->will($this->returnValue($asset));
$xml = $this->renderXml('mixture.twig');
$this->assertEquals(1, count($xml->asset));
$this->assertEquals('packed/mixture', (string) $xml->asset['url']);
}
public function testDebug()
{
$filter = $this->getMock('Assetic\\Filter\\FilterInterface');
$this->fm->expects($this->once())
->method('get')
->with('bar')
->will($this->returnValue($filter));
$xml = $this->renderXml('debug.twig');
$this->assertEquals(2, count($xml->asset));
$this->assertStringStartsWith('css/packed_', (string) $xml->asset[0]['url']);
$this->assertStringEndsWith('.css', (string) $xml->asset[0]['url']);
}
public function testCombine()
{
$filter = $this->getMock('Assetic\\Filter\\FilterInterface');
$this->fm->expects($this->once())
->method('get')
->with('bar')
->will($this->returnValue($filter));
$xml = $this->renderXml('combine.twig');
$this->assertEquals(1, count($xml->asset));
$this->assertEquals('css/packed.css', (string) $xml->asset[0]['url']);
}
public function testImage()
{
$xml = $this->renderXml('image.twig');
$this->assertEquals(1, count($xml->image));
$this->assertStringEndsWith('.png', (string) $xml->image[0]['url']);
}
public function testFilterFunction()
{
$filter = $this->getMock('Assetic\\Filter\\FilterInterface');
$this->fm->expects($this->once())
->method('get')
->with('some_filter')
->will($this->returnValue($filter));
$this->twig->addExtension(new AsseticExtension($this->factory, array(
'some_func' => array(
'filter' => 'some_filter',
'options' => array('output' => 'css/*.css'),
),
)));
$xml = $this->renderXml('function.twig');
$this->assertEquals(1, count($xml->asset));
$this->assertStringEndsWith('.css', (string) $xml->asset[0]['url']);
}
public function testVariables()
{
$this->valueSupplier->expects($this->once())
->method('getValues')
->will($this->returnValue(array('foo' => 'a', 'bar' => 'b')));
$xml = $this->renderXml('variables.twig');
$this->assertEquals(2, $xml->url->count());
$this->assertEquals("js/7d0828c.a.b_foo_1.js", (string) $xml->url[0]);
$this->assertEquals("js/7d0828c.a.b_variable_input._2.js", (string) $xml->url[1]);
}
public function testMultipleSameVariableValues()
{
$vars = array('locale');
$asset = new FileAsset(__DIR__.'/../Fixture/messages.{locale}.js', array(), null, null, $vars);
$coll = new AssetCollection(array($asset), array(), null, $vars);
$coll->setTargetPath('output.{locale}.js');
$coll->setValues(array('locale' => 'en'));
foreach($coll as $asset) {
$this->assertEquals('output.{locale}_messages._1.js', $asset->getTargetPath(), 'targetPath must not contain several time the same variable');
}
}
/**
* @expectedException \Twig_Error_Syntax
*/
public function testUnclosedTag()
{
$this->renderXml('unclosed_tag.twig');
}
private function renderXml($name, $context = array())
{
return new \SimpleXMLElement($this->twig->loadTemplate($name)->render($context));
}
}
| {
"content_hash": "2f2151ae01b7b40e1231e0a8d86ef140",
"timestamp": "",
"source": "github",
"line_count": 242,
"max_line_length": 153,
"avg_line_length": 31.84710743801653,
"alnum_prop": 0.5648112105877774,
"repo_name": "Ismailmehri/zcom-dev",
"id": "3d3cf25a59aa7277b0a6a83ac49c4b0c116435c2",
"size": "7948",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "vendor/kriswallsmith/assetic/tests/Assetic/Test/Extension/Twig/AsseticExtensionTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3073"
},
{
"name": "CSS",
"bytes": "66189"
},
{
"name": "JavaScript",
"bytes": "68767"
},
{
"name": "PHP",
"bytes": "211113"
},
{
"name": "Shell",
"bytes": "1002"
}
],
"symlink_target": ""
} |
require 'uri'
require 'awesome_spawn'
module MiqCockpit
class WS
DEFAULT_PORT = 9002
# Used when the cockpit-ws worker is not enabled
COCKPIT_PUBLIC_PORT = 9090
MIQ_REDIRECT_URL = "/dashboard/cockpit_redirect".freeze
COCKPIT_WS_PATH = '/usr/libexec/cockpit-ws'.freeze
COCKPIT_SSH_PATH = '/usr/libexec/cockpit-ssh'.freeze
attr_accessor :config_dir, :cockpit_dir
def self.can_start_cockpit_ws?
MiqEnvironment::Command.is_linux? &&
File.exist?(COCKPIT_WS_PATH) &&
File.exist?(COCKPIT_SSH_PATH)
end
def self.direct_url(address)
URI::HTTP.build(:host => address,
:port => MiqCockpit::WS::COCKPIT_PUBLIC_PORT)
end
def self.server_address(miq_server)
address = miq_server.ipaddress
if miq_server.hostname && (::Settings.webservices.contactwith == 'hostname' || !address)
address = miq_server.hostname
end
address
end
def self.current_ui_server?(miq_server)
return false unless MiqServer.my_server == miq_server
miq_server.has_active_userinterface
end
def self.url_from_server(miq_server, opts)
opts ||= {}
# Assume we are using apache unless we are the only server
has_apache = current_ui_server?(miq_server) ? MiqEnvironment::Command.supports_apache? : true
cls = has_apache ? URI::HTTPS : URI::HTTP
cls.build(:host => server_address(miq_server),
:port => has_apache ? nil : opts[:port] || DEFAULT_PORT,
:path => MiqCockpit::ApacheConfig.url_root)
end
def self.url(miq_server, opts, address)
return MiqCockpit::WS.direct_url(address) if miq_server.nil?
opts ||= {}
url = if opts[:external_url]
URI.parse(opts[:external_url])
else
url_from_server(miq_server, opts)
end
# Make sure we have a path that ends in a /
url.path = MiqCockpit::ApacheConfig.url_root if url.path.empty?
url.path = "#{url.path}/" unless url.path.end_with?("/")
# Add address to path if needed, note this is a path
# not a querystring
url.path = "#{url.path}=#{address}" if address
url
end
def initialize(opts = {})
@opts = opts || {}
@config_dir = Rails.root.join("config").to_s
@cockpit_conf_dir = File.join(@config_dir, "cockpit")
FileUtils.mkdir_p(@cockpit_conf_dir)
end
def command(address)
args = { :port => @opts[:port] || DEFAULT_PORT.to_s }
if address
args[:address] = address
end
args[:no_tls] = nil
AwesomeSpawn.build_command_line(COCKPIT_WS_PATH, args)
end
def save_config
fname = File.join(@cockpit_conf_dir, "cockpit.conf")
update_config
File.write(fname, @config)
AwesomeSpawn.run!("restorecon -R -v #{@cockpit_conf_dir}")
end
def web_ui_url
if @opts[:web_ui_url]
url = URI.parse(@opts[:web_ui_url])
else
server = MiqRegion.my_region.try(:remote_ui_miq_server)
unless server.nil?
opts = { :port => 3000 }
url = MiqCockpit::WS.url_from_server(server, opts)
end
end
if url.nil?
ret = MiqCockpit::WS::MIQ_REDIRECT_URL
else
# Force the dashboard redirect path
url.path = MiqCockpit::WS::MIQ_REDIRECT_URL
ret = url.to_s
end
ret
end
def update_config
title = @opts[:title] || "ManageIQ Cockpit"
login_command = File.join("/usr", "bin", "cockpit-auth-miq")
@config = <<-END_OF_CONFIG
[Webservice]
LoginTitle = #{title}
UrlRoot = #{MiqCockpit::ApacheConfig::URL_ROOT}
ProtocolHeader = X-Forwarded-Proto
[Negotiate]
Action = none
[Basic]
Action = none
[Bearer]
Action = remote-login-ssh
[SSH-Login]
command = #{login_command}
authFD=10
[OAuth]
Url = #{web_ui_url}
END_OF_CONFIG
@config
end
def setup_ssl
dir = File.join(@cockpit_conf_dir, "ws-certs.d")
FileUtils.mkdir_p(dir)
cert = File.open('certs/server.cer') { |f| OpenSSL::X509::Certificate.new(f).to_pem }
key = File.open('certs/server.cer.key') { |f| OpenSSL::PKey::RSA.new(f).to_pem }
contents = [cert, key].join("\n")
File.write(File.join(dir, "0-miq.cert"), contents)
end
end
class ApacheConfig
URL_ROOT = "cws".freeze
def self.url_root
"/#{URL_ROOT}/"
end
end
end
| {
"content_hash": "94f639e02671ef996ca82bdc8c939a8a",
"timestamp": "",
"source": "github",
"line_count": 164,
"max_line_length": 99,
"avg_line_length": 26.932926829268293,
"alnum_prop": 0.6042562825447136,
"repo_name": "billfitzgerald0120/manageiq",
"id": "3f720278ab712aed35b684b264bcf9149ad06082",
"size": "4417",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/miq_cockpit.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3042"
},
{
"name": "Dockerfile",
"bytes": "1476"
},
{
"name": "HTML",
"bytes": "2167"
},
{
"name": "JavaScript",
"bytes": "183"
},
{
"name": "Ruby",
"bytes": "7861678"
},
{
"name": "Shell",
"bytes": "22687"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe AgentAutocompleteController do
before :each do
allow(controller).to receive(:go_config_service).and_return(@go_config_service = Object.new)
allow(controller).to receive(:environment_config_service).and_return(@environment_config_service = Object.new)
allow(controller).to receive(:agent_service).and_return(@agent_service = Object.new)
end
describe :routes do
it "should resolve the path" do
expect(:get => '/agents/filter_autocomplete/resource').to route_to(:controller => "agent_autocomplete", :action => 'resource')
expect(agent_filter_autocomplete_path(:action => "os")).to eq("/agents/filter_autocomplete/os")
end
it "should accept only the defined actions" do
expect(:get => "agents/filter_autocomplete/foo").to route_to(:controller => "application", :action => 'unresolved', :url => "agents/filter_autocomplete/foo")
end
end
describe :actions do
before do
allow(@go_config_service).to receive(:checkConfigFileValid).and_return(com.thoughtworks.go.config.validation.GoConfigValidity.valid())
end
describe :resource do
it "should return all resources starting with given query string" do
expect(@go_config_service).to receive(:getResourceList).and_return(java.util.Arrays.asList(["linux", "windows"].to_java(java.lang.String)))
get "resource", :q => "li"
expect(response.body).to eq("linux")
end
end
describe :status do
it "should return all types of agent status" do
get "status", :q => ""
expect(response.body).to eq("pending\nlostcontact\nmissing\nbuilding\ncancelled\nidle\ndisabled")
end
it "should return agent status starting with given query string" do
get "status", :q => "bu"
expect(response.body).to eq("building")
end
it "should return case insensitive status starting with given query string" do
get "status", :q => "bUi"
expect(response.body).to eq("building")
end
end
describe :environment do
it "should return all environments" do
env_list = java.util.Arrays.asList([CaseInsensitiveString.new("prod"), CaseInsensitiveString.new("testing"), CaseInsensitiveString.new("staging")].to_java(CaseInsensitiveString))
expect(@environment_config_service).to receive(:environmentNames).and_return(env_list)
get "environment", :q => ""
expect(response.body).to eq("prod\ntesting\nstaging")
end
it "should return all environments starting with a query string" do
env_list = java.util.Arrays.asList([CaseInsensitiveString.new("prod"), CaseInsensitiveString.new("testing"), CaseInsensitiveString.new("staging")].to_java(CaseInsensitiveString))
expect(@environment_config_service).to receive(:environmentNames).and_return(env_list)
get "environment", :q => "test"
expect(response.body).to eq("testing")
end
end
describe :name do
it "should return all unique agent hostnames" do
expect(@agent_service).to receive(:getUniqueAgentNames).and_return(java.util.Arrays.asList(["dev-agent", "test-linux-agent", "test-win-agent"].to_java(java.lang.String)))
get "name", :q => ""
expect(response.body).to eq("dev-agent\ntest-linux-agent\ntest-win-agent")
end
it "should return all unique agent hostnames starting with given query string" do
expect(@agent_service).to receive(:getUniqueAgentNames).and_return(java.util.Arrays.asList(["dev-agent", "test-linux-agent", "test-win-agent"].to_java(java.lang.String)))
get "name", :q => "te"
expect(response.body).to eq("test-linux-agent\ntest-win-agent")
end
end
describe :ip do
it "should return all agent ip addresses" do
expect(@agent_service).to receive(:getUniqueIPAddresses).and_return(java.util.Arrays.asList(["10.11.12.13", "11.13.14.15"].to_java(java.lang.String)))
get "ip", :q => ""
expect(response.body).to eq("10.11.12.13\n11.13.14.15")
end
it "should return all agent ip addresses starting with a given query string" do
expect(@agent_service).to receive(:getUniqueIPAddresses).and_return(java.util.Arrays.asList(["10.11.12.13", "11.13.14.15"].to_java(java.lang.String)))
get "ip", :q => "11."
expect(response.body).to eq("11.13.14.15")
end
end
describe :os do
it "should return all agent operating systems" do
expect(@agent_service).to receive(:getUniqueAgentOperatingSystems).and_return(java.util.Arrays.asList(["linux", "windows"].to_java(java.lang.String)))
get "os", :q => ""
expect(response.body).to eq("linux\nwindows")
end
it "should return all agent operating systems starting with a given query string" do
expect(@agent_service).to receive(:getUniqueAgentOperatingSystems).and_return(java.util.Arrays.asList(["linux", "windows"].to_java(java.lang.String)))
get "os", :q => "li"
expect(response.body).to eq("linux")
end
end
end
end
| {
"content_hash": "536d33cce78310404e75630538051302",
"timestamp": "",
"source": "github",
"line_count": 118,
"max_line_length": 186,
"avg_line_length": 43.16949152542373,
"alnum_prop": 0.6721633294071456,
"repo_name": "sghill/gocd",
"id": "6cd503679b99b6926599ed26dd5aacd770129df5",
"size": "5827",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/webapp/WEB-INF/rails.new/spec/controllers/agent_autocomplete_controller_spec.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "8229"
},
{
"name": "CSS",
"bytes": "527466"
},
{
"name": "FreeMarker",
"bytes": "182"
},
{
"name": "HTML",
"bytes": "642918"
},
{
"name": "Java",
"bytes": "15199526"
},
{
"name": "JavaScript",
"bytes": "2736266"
},
{
"name": "NSIS",
"bytes": "19022"
},
{
"name": "PowerShell",
"bytes": "743"
},
{
"name": "Ruby",
"bytes": "2661293"
},
{
"name": "SQLPL",
"bytes": "9050"
},
{
"name": "Shell",
"bytes": "239120"
},
{
"name": "XSLT",
"bytes": "147495"
}
],
"symlink_target": ""
} |
package com.gcarrillo.android.weatherclient.network.apimodel;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Coord {
@SerializedName("lon")
@Expose
private Double lon;
@SerializedName("lat")
@Expose
private Double lat;
public Double getLon() {
return lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
}
| {
"content_hash": "be8921df8b56527cca4e9c750acfa094",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 61,
"avg_line_length": 17.967741935483872,
"alnum_prop": 0.6319569120287253,
"repo_name": "MrArizona/Weather-Client-MVP",
"id": "1eaec4527dc15272e91bbc19bd6de541bae72901",
"size": "558",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/gcarrillo/android/weatherclient/network/apimodel/Coord.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "27814"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Portfolio Item</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/portfolio-item.css" rel="stylesheet">
<!-- 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/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
</button>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
<a href="../index.html">Back</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<!-- Page Content -->
<div class="container">
<!-- Portfolio Item Heading -->
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Portfolio Item
<small>Mason</small>
</h1>
</div>
</div>
<!-- /.row -->
<!-- Portfolio Item Row -->
<div class="row">
<div class="col-md-8">
<img class="img-responsive" src="img/pic2.jpg" alt="" height="500px" width="750px">
</div>
<div class="col-md-4">
<h3>Project Description</h3>
<p>This picture was taken during a studio lab where we had to replicate differnt styles of picture taking, this is a butterfly style.</p>
</div>
</div>
<hr>
<!-- Footer -->
<footer>
<div class="row">
<div class="col-lg-12">
<p>Copyright © Ian Kelly 2016</p>
</div>
</div>
<!-- /.row -->
</footer>
</div>
<!-- /.container -->
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "4cec062f84655befbba79fa0e3b413ea",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 153,
"avg_line_length": 31.58653846153846,
"alnum_prop": 0.4873668188736682,
"repo_name": "Iankelly451/assignment-2",
"id": "dde8bd14a79f8ab52edbc531ace4ec3b6997f0cc",
"size": "3285",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "imagepages/imagepage2.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "114687"
},
{
"name": "HTML",
"bytes": "83046"
}
],
"symlink_target": ""
} |
new_version="$1"
old_version="$(git tag | grep -E 'v.*\..*\..*' | sort -V | tail -n 1 | sed -E 's/v(.*)/\1/')"
version_file=setup.py
if [[ $(git branch --show-current) != 'master' ]]; then
echo 'Not on dev branch'
exit -1
fi
echo "Upgrading from $old_version to $new_version"
upload_pypi() {
rm -r dist
python setup.py sdist bdist_wheel
python3 -m twine upload --repository pypi dist/*
}
change_version() {
sed -i -E "s/version=\"$1\"/version=\"$2\"/" $version_file
}
# Change source version
change_version $old_version $new_version
# Create git commit and tag
git commit -a -m "Version $new_version"
git tag -a "v$new_version" -m "Version $new_version"
# Confirm before pushing
read -p "Creating new release $new_version, finalize? (y/N)" -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
git push origin "v$new_version"
git push
upload_pypi
echo 'Release finalized'
else
git tag -d "v$new_version"
change_version $new_version $old_version
echo 'Aborted'
fi
| {
"content_hash": "bbd86e0bd25575e7f784a42cf6b38bd3",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 93,
"avg_line_length": 24.70731707317073,
"alnum_prop": 0.633761105626851,
"repo_name": "KillianMeersman/telemeter",
"id": "d63bb23b1fca2b536b3a070250aa021880fbf326",
"size": "1026",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "release.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "8097"
},
{
"name": "Shell",
"bytes": "1026"
}
],
"symlink_target": ""
} |
package org.ema.activities;
import android.app.FragmentManager;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.util.List;
import org.ema.activities.admin.MenuActivity;
import org.ema.activities.admin.NewAdminPassword;
import org.ema.activities.student.StudentMenuActivity;
import org.ema.dialogs.ResetPasswordDialog;
import org.ema.entities.Admin;
import org.ema.entities.Student;
import org.ema.util.HashCodes;
import io.realm.Realm;
import io.realm.RealmQuery;
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "LoginActivity";
private Realm realm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(org.ema.R.layout.activity_login);
this.realm = Realm.getDefaultInstance();
}
public void login(View view){
EditText usernameET = (EditText)findViewById(org.ema.R.id.newName);
String username = usernameET.getText().toString();
EditText passwordET = (EditText)findViewById(org.ema.R.id.passwordTxt);
String password = HashCodes.get_SHA_512_SecurePassword(passwordET.getText().toString(),"eMobileActivities");
RealmQuery<Admin> query = realm.where(Admin.class);
query.equalTo("name",username);
query.equalTo("password",password);
List<Admin> admins = query.findAll();
if(admins.size() > 0){
//reset password?
Intent intent;
if(admins.get(0).getChangePassword()){
intent = new Intent(this,NewAdminPassword.class);
}else{
intent = new Intent(this,MenuActivity.class);
}
startActivity(intent);
}else{
RealmQuery<Student> queryStudent = realm.where(Student.class);
queryStudent.equalTo("nickname",username);
queryStudent.equalTo("password",password);
List<Student> students = queryStudent.findAll();
if(students.size() > 0 && students.get(0) != null){
//TODO send student to start content
Intent intent = new Intent(this,StudentMenuActivity.class);
intent.putExtra("studentId", students.get(0).getId());
startActivity(intent);
}else{
TextView info = (TextView) findViewById(org.ema.R.id.information);
info.setTextColor(Color.RED);
info.setText(org.ema.R.string.checkDataTyped);
info.setBackgroundColor(Color.TRANSPARENT);
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
realm.close();
}
public void resetPassword(View view){
FragmentManager fm = getFragmentManager();
ResetPasswordDialog dialog = new ResetPasswordDialog();
dialog.show(fm,"");
}
}
| {
"content_hash": "8967484b1c0173339b22c6e314fc61cb",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 116,
"avg_line_length": 36.666666666666664,
"alnum_prop": 0.6564935064935065,
"repo_name": "samuelyuri/E-MobileActivities",
"id": "a0504b2a80b3bf579d9771da72536ebcf396ebac",
"size": "3080",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/org/ema/activities/LoginActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "152045"
}
],
"symlink_target": ""
} |
<?php
/**
* For fetching data by URL.
*
* http://php.net/manual/en/function.curl-setopt.php
*
* @author Chris Ullyott <contact@chrisullyott.com>
*/
class Curl
{
/**
* An array of default options for Curl.
*
* @var array
*/
private $defaultOpts = array(
CURLOPT_VERBOSE => false,
CURLOPT_HEADER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true
);
/**
* The URL to request from.
*
* @var string
*/
private $url;
/**
* The HTTP code from the request.
*
* @var integer
*/
private $httpCode;
/**
* The headers of the request.
*
* @var array
*/
private $headers;
/**
* The body of the request.
*
* @var string
*/
private $body;
/**
* Constructor.
*
* @param string $url The URL to request from
*/
public function __construct($url)
{
$this->url = $url;
$this->fetch();
}
/**
* Gets the array of default options for Curl.
*
* @return array
*/
public function getDefaultOpts()
{
return $this->defaultOpts;
}
/**
* Gets the URL to request from.
*
* @return string
*/
public function getUrl()
{
return $this->url;
}
/**
* Sets the HTTP code from the request.
*
* @param integer $httpCode The http code
* @return self
*/
public function setHttpCode($httpCode)
{
$this->httpCode = $httpCode;
return $this;
}
/**
* Gets the HTTP code from the request.
*
* @return integer
*/
public function getHttpCode()
{
return $this->httpCode;
}
/**
* Sets the headers of the request.
*
* @param array $headers The headers
* @return self
*/
public function setHeaders(array $headers)
{
$this->headers = $headers;
return $this;
}
/**
* Gets the headers of the request.
*
* @return array
*/
public function getHeaders()
{
return $this->headers;
}
/**
* Sets the body of the request.
*
* @param string $body The body
* @return self
*/
public function setBody($body)
{
$this->body = $body;
return $this;
}
/**
* Gets the body of the request.
*
* @return string
*/
public function getBody()
{
return $this->body;
}
/**
* Return an array of information about this request excluding the body. If the
* request wasn't successful, go ahead and provide the body, as it might contain
* a helpful message if an error occurred.
*
* @return array
*/
public function getInfo()
{
$info = array(
'http_code' => $this->getHttpCode(),
'headers' => $this->getHeaders()
);
if (!$this->isSuccessful()) {
$info['body'] = $this->getBody();
}
return $info;
}
/**
* Fetch data from the URL.
*
* @return self
*/
private function fetch()
{
$curl = curl_init();
$opts = $this->getDefaultOpts() + array(CURLOPT_URL => $this->getUrl());
curl_setopt_array($curl, $opts);
$response = curl_exec($curl);
if (!curl_errno($curl)) {
$headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$this->setHttpCode(curl_getinfo($curl, CURLINFO_HTTP_CODE));
$this->setHeaders(self::parseHeaders($response, $headerSize));
$this->setBody(self::parseBody($response, $headerSize));
}
curl_close($curl);
return $this;
}
/**
* Determine whether a request was successful by HTTP code. Here, success means
* HTTP codes 2xx and 3xx.
*
* @return boolean
*/
public function isSuccessful()
{
return in_array(substr($this->getHttpCode(), 0, 1), array(2, 3));
}
/**
* Parse the headers from a Curl response.
*
* @param string $response The entire Curl response
* @param integer $headerSize The size of the headers of the response
* @return array
*/
private static function parseHeaders($response, $headerSize)
{
$headers = array();
$headerString = trim(substr($response, 0, $headerSize));
$headerLines = explode("\n", $headerString);
foreach ($headerLines as $line) {
list($key, $val) = explode(':', $line, 2);
$headers[trim($key)] = trim($val);
}
return $headers;
}
/**
* Parse the body from a Curl response.
*
* @param string $response The entire Curl response
* @param integer $headerSize The size of the headers of the response
* @return string
*/
private static function parseBody($response, $headerSize)
{
return trim(substr($response, $headerSize));
}
}
| {
"content_hash": "1d2e87956e499f16595a8f7859c9d5c1",
"timestamp": "",
"source": "github",
"line_count": 243,
"max_line_length": 84,
"avg_line_length": 20.80658436213992,
"alnum_prop": 0.5270965189873418,
"repo_name": "chrisullyott/wayback-cache",
"id": "c08516fdca0ef4dbe8460ee05fb12932a6dbe0f5",
"size": "5056",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Library/Utility/Curl.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "22366"
}
],
"symlink_target": ""
} |
一段完整的Android平台上短信功能的接口源码,利用扩展的API可以通过js实现如下功能:
1. getContentUris():读取短信相关的所有数据库表的Uri地址;
2. get(int number):读取若干条短信;
3. getUnread(int number):读取若干条未读短信;
4. getRead(int number):读取若干条已读短信;
5. getInbox(int number):从收件箱读取若干条短信;
6. getSent(int number):读取若干条已发短信;
7. getByThread(int threadID):读取会话中所有短信;
8. getThreads(int number):读取若干条会话;
9. getData(String selection, int number):根据条件读取若干条短信。
源码如下,分享出来:
```
[Tags]/*
[Tags]* Licensed under the Rexsee License, Version 1.0 (the "License");
[Tags]* you may not use this file except in compliance with the License.
[Tags]* You may obtain a copy of the License at
[Tags]*
[Tags]* Unless required by applicable law or agreed to in writing, software
[Tags]* distributed under the License is distributed on an "AS IS" BASIS,
[Tags]* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
[Tags]* See the License for the specific language governing permissions and
[Tags]* limitations under the License.
[Tags]*/
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
public class RexseeSMS implements JavascriptInterface {
private static final String INTERFACE_NAME = "SMS";
@Override
public String getInterfaceName() {
return mBrowser.application.resources.prefix + INTERFACE_NAME;
}
@Override
public JavascriptInterface getInheritInterface(RexseeBrowser childBrowser) {
return this;
}
@Override
public JavascriptInterface getNewInterface(RexseeBrowser childBrowser) {
return new RexseeSMS(childBrowser);
}
public static final String CONTENT_URI_SMS = "content://sms";
public static final String CONTENT_URI_SMS_INBOX = "content://sms/inbox";
public static final String CONTENT_URI_SMS_SENT = "content://sms/sent";
public static final String CONTENT_URI_SMS_CONVERSATIONS = "content://sms/conversations";
public static String[] SMS_COLUMNS = new String[] { "_id", // 0
"thread_id", // 1
"address", // 2
"person", // 3
"date", // 4
"body", // 5
"read", // 6; 0:not read 1:read; default is 0
"type", // 7; 0:all 1:inBox 2:sent 3:draft 4:outBox 5:failed
// 6:queued
"service_center" // 8
};
public static String[] THREAD_COLUMNS = new String[] { "thread_id",
"msg_count", "snippet", };
private final Context mContext;
private final RexseeBrowser mBrowser;
public RexseeSMS(RexseeBrowser browser) {
mBrowser = browser;
mContext = browser.getContext();
}
// JavaScript Interface
public String getContentUris() {
String rtn = "{";
rtn += "\"sms\":\"" + CONTENT_URI_SMS + "\"";
rtn += ",\"inbox\":\"" + CONTENT_URI_SMS_INBOX + "\"";
rtn += ",\"sent\":\"" + CONTENT_URI_SMS_SENT + "\"";
rtn += ",\"conversations\":\"" + CONTENT_URI_SMS_CONVERSATIONS + "\"";
rtn += "}";
return rtn;
}
public String get(int number) {
return getData(null, number);
}
public String getUnread(int number) {
return getData("type=1 AND read=0", number);
}
public String getRead(int number) {
return getData("type=1 AND read=1", number);
}
public String getInbox(int number) {
return getData("type=1", number);
}
public String getSent(int number) {
return getData("type=2", number);
}
public String getByThread(int thread) {
return getData("thread_id=" + thread, 0);
}
public String getData(String selection, int number) {
Cursor cursor = null;
ContentResolver contentResolver = mContext.getContentResolver();
try {
if (number > 0) {
cursor = contentResolver.query(Uri.parse(CONTENT_URI_SMS),
SMS_COLUMNS, selection, null, "date desc limit
+ number);
} else {
cursor = contentResolver.query(Uri.parse(CONTENT_URI_SMS),
SMS_COLUMNS, selection, null, "date desc");
}
if (cursor == null || cursor.getCount() == 0)
return "[]";
String rtn = "";
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
if (i > 0)
rtn += ",";
rtn += "{";
rtn += "\"_id\":" + cursor.getString(0);
rtn += ",\"thread_id\":" + cursor.getString(1);
rtn += ",\"address\":\"" + cursor.getString(2) + "\"";
rtn += ",\"person\":\
+ ((cursor.getString(3) == null) ? "" : cursor
.getString(3)) + "\"";
rtn += ",\"date\":" + cursor.getString(4);
rtn += ",\"body\":\"" + Escape.escape(cursor.getString(5))
+ "\"";
rtn += ",\"read\":
+ ((cursor.getInt(6) == 1) ? "true" : "false");
rtn += ",\"type\":" + cursor.getString(7);
rtn += ",\"service_center\":" + cursor.getString(8);
rtn += "}";
}
return "[" + rtn + "]";
} catch (Exception e) {
mBrowser.exception(getInterfaceName(), e);
return "[]";
}
}
public String getThreads(int number) {
Cursor cursor = null;
ContentResolver contentResolver = mContext.getContentResolver();
try {
if (number > 0) {
cursor = contentResolver.query(
Uri.parse(CONTENT_URI_SMS_CONVERSATIONS),
THREAD_COLUMNS, null, null, "thread_id desc limit
+ number);
} else {
cursor = contentResolver.query(
Uri.parse(CONTENT_URI_SMS_CONVERSATIONS),
THREAD_COLUMNS, null, null, "thread_id desc");
}
if (cursor == null || cursor.getCount() == 0)
return "[]";
String rtn = "";
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
if (i > 0)
rtn += ",";
rtn += "{";
rtn += "\"thread_id\":" + cursor.getString(0);
rtn += ",\"msg_count\":" + cursor.getString(1);
rtn += ",\"snippet\":\"" + Escape.escape(cursor.getString(2))
+ "\"";
rtn += "}";
}
return "[" + rtn + "]";
} catch (Exception e) {
mBrowser.exception(getInterfaceName(), e);
return "[]";
}
}
}
``` | {
"content_hash": "85d91c354ec24420c20b40978815f872",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 90,
"avg_line_length": 33.541666666666664,
"alnum_prop": 0.6354924578527062,
"repo_name": "EManual/EManual.github.io",
"id": "bc9f4927f3a351f5e8eb1da5de8e92395e9b3049",
"size": "5935",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "android-tmp/android_component/Content Provider/0011-Android短信功能实现源码.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "76677"
},
{
"name": "HTML",
"bytes": "91835"
},
{
"name": "JavaScript",
"bytes": "28126"
},
{
"name": "Python",
"bytes": "17307"
}
],
"symlink_target": ""
} |
namespace PatientManagement.Administration.Endpoints
{
using Serenity;
using Serenity.Data;
using Serenity.Services;
using System.Data;
using Microsoft.AspNetCore.Mvc;
using MyRepository = Repositories.ExternalAccessRepository;
using MyRow = Entities.ExternalAccessRow;
[Route("Services/Administration/ExternalAccess/[action]")]
[ConnectionKey(typeof(MyRow)), ServiceAuthorize(typeof(MyRow))]
public class ExternalAccessController : ServiceEndpoint
{
[HttpPost, AuthorizeCreate(typeof(MyRow))]
public SaveResponse Create(IUnitOfWork uow, SaveRequest<MyRow> request)
{
return new MyRepository().Create(uow, request);
}
[HttpPost, AuthorizeUpdate(typeof(MyRow))]
public SaveResponse Update(IUnitOfWork uow, SaveRequest<MyRow> request)
{
return new MyRepository().Update(uow, request);
}
[HttpPost, AuthorizeDelete(typeof(MyRow))]
public DeleteResponse Delete(IUnitOfWork uow, DeleteRequest request)
{
return new MyRepository().Delete(uow, request);
}
public RetrieveResponse<MyRow> Retrieve(IDbConnection connection, RetrieveRequest request)
{
return new MyRepository().Retrieve(connection, request);
}
public ListResponse<MyRow> List(IDbConnection connection, ListRequest request)
{
return new MyRepository().List(connection, request);
}
}
}
| {
"content_hash": "3b04e007d2387a0eea6c23d8aca1ff65",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 98,
"avg_line_length": 34.11363636363637,
"alnum_prop": 0.6722185209860093,
"repo_name": "Magik3a/PatientManagement_Admin",
"id": "e878dc9ee4bcc9de89c77073be1d312ea2ae7746",
"size": "1503",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PatientManagement/PatientManagement.Web/Modules/Administration/ExternalAccess/ExternalAccessEndpoint.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1143"
},
{
"name": "C#",
"bytes": "1630015"
},
{
"name": "CSS",
"bytes": "3093746"
},
{
"name": "CoffeeScript",
"bytes": "103432"
},
{
"name": "Dockerfile",
"bytes": "400"
},
{
"name": "HTML",
"bytes": "1276856"
},
{
"name": "JavaScript",
"bytes": "14922709"
},
{
"name": "Makefile",
"bytes": "1369"
},
{
"name": "PHP",
"bytes": "1738"
},
{
"name": "PowerShell",
"bytes": "4761"
},
{
"name": "Shell",
"bytes": "3020"
},
{
"name": "TypeScript",
"bytes": "407622"
}
],
"symlink_target": ""
} |
#include "bgp/inetmcast/inetmcast_route.h"
#include "bgp/inetmcast/inetmcast_table.h"
using namespace std;
InetMcastPrefix::InetMcastPrefix() {
}
InetMcastPrefix InetMcastPrefix::FromString(const string &str,
boost::system::error_code *errorp) {
InetMcastPrefix prefix;
size_t pos1 = str.rfind(':');
if (pos1 == string::npos) {
if (errorp != NULL) {
*errorp = make_error_code(boost::system::errc::invalid_argument);
}
return prefix;
}
string rd_str = str.substr(0, pos1);
boost::system::error_code rd_err;
prefix.rd_ = RouteDistinguisher::FromString(rd_str, &rd_err);
if (rd_err != 0) {
if (errorp != NULL) {
*errorp = rd_err;
}
return prefix;
}
size_t pos2 = str.rfind(',');
if (pos2 == string::npos) {
if (errorp != NULL) {
*errorp = make_error_code(boost::system::errc::invalid_argument);
}
return prefix;
}
string group_str = str.substr(pos1 + 1, pos2 - pos1 -1);
boost::system::error_code group_err;
prefix.group_ = Ip4Address::from_string(group_str, group_err);
if (group_err != 0) {
if (errorp != NULL) {
*errorp = group_err;
}
return prefix;
}
string source_str = str.substr(pos2 + 1, string::npos);
boost::system::error_code source_err;
prefix.source_ = Ip4Address::from_string(source_str, source_err);
if (source_err != 0) {
if (errorp != NULL) {
*errorp = source_err;
}
return prefix;
}
return prefix;
}
string InetMcastPrefix::ToString() const {
string repr = rd_.ToString();
repr += ":" + group_.to_string();
repr += "," + source_.to_string();
return repr;
}
InetMcastRoute::InetMcastRoute(const InetMcastPrefix &prefix)
: prefix_(prefix) {
}
int InetMcastRoute::CompareTo(const Route &rhs) const {
const InetMcastRoute &other = static_cast<const InetMcastRoute &>(rhs);
int res = prefix_.route_distinguisher().CompareTo(
other.prefix_.route_distinguisher());
if (res != 0) {
return res;
}
Ip4Address lgroup = prefix_.group();
Ip4Address rgroup = other.prefix_.group();
if (lgroup < rgroup) {
return -1;
}
if (lgroup > rgroup) {
return 1;
}
Ip4Address lsource = prefix_.source();
Ip4Address rsource = other.prefix_.source();
if (lsource < rsource) {
return -1;
}
if (lsource > rsource) {
return 1;
}
return 0;
}
string InetMcastRoute::ToString() const {
return prefix_.ToString();
}
void InetMcastRoute::SetKey(const DBRequestKey *reqkey) {
const InetMcastTable::RequestKey *key =
static_cast<const InetMcastTable::RequestKey *>(reqkey);
prefix_ = key->prefix;
}
void InetMcastRoute::BuildProtoPrefix(BgpProtoPrefix *prefix,
uint32_t label) const {
}
void InetMcastRoute::BuildBgpProtoNextHop(std::vector<uint8_t> &nh,
IpAddress nexthop) const {
}
DBEntryBase::KeyPtr InetMcastRoute::GetDBRequestKey() const {
InetMcastTable::RequestKey *key =
new InetMcastTable::RequestKey(GetPrefix(), NULL);
return KeyPtr(key);
}
| {
"content_hash": "a25aee0439391f52162061cfd98e4026",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 77,
"avg_line_length": 25.951612903225808,
"alnum_prop": 0.6047234307022996,
"repo_name": "safchain/contrail-controller",
"id": "a0611273fd7d3148fe39848067fa8dcdbb0bad02",
"size": "3290",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/bgp/inetmcast/inetmcast_route.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
return [
/*
|--------------------------------------------------------------------------
| PDO Fetch Style
|--------------------------------------------------------------------------
|
| By default, database results will be returned as instances of the PHP
| stdClass object; however, you may desire to retrieve records in an
| array format for simplicity. Here you can tweak the fetch style.
|
*/
'fetch' => PDO::FETCH_OBJ,
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => env('DB_CONNECTION', 'mysql'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
],
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => 'itracker_',
'strict' => true,
'engine' => null,
],
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
'sslmode' => 'prefer',
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'cluster' => false,
'default' => [
'host' => env('REDIS_HOST', 'localhost'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
],
],
];
| {
"content_hash": "81cd351da04b863dd62085493c456648",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 79,
"avg_line_length": 32.85950413223141,
"alnum_prop": 0.42932595573440646,
"repo_name": "joshmassey/sga-itracker",
"id": "fd2f1971a0cef06bae799696c48a78ecc3c6deea",
"size": "3976",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config/database.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "158"
},
{
"name": "CSS",
"bytes": "604713"
},
{
"name": "HTML",
"bytes": "2269409"
},
{
"name": "JavaScript",
"bytes": "2939969"
},
{
"name": "Makefile",
"bytes": "4561"
},
{
"name": "PHP",
"bytes": "4333"
}
],
"symlink_target": ""
} |
package com.google.javascript.jscomp.transpile;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Answers.RETURNS_SMART_NULLS;
import static org.mockito.Mockito.when;
import com.google.javascript.jscomp.bundle.TranspilationException;
import java.nio.file.Path;
import java.nio.file.Paths;
import junit.framework.TestCase;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/** Tests for {@link BaseTranspiler}. */
public final class BaseTranspilerTest extends TestCase {
private Transpiler transpiler;
private BaseTranspiler.CompilerSupplier compiler;
@Mock(answer = RETURNS_SMART_NULLS) BaseTranspiler.CompilerSupplier mockCompiler;
private static final Path FOO_JS = Paths.get("foo.js");
private static final Path SOURCE_JS = Paths.get("source.js");
@Override
public void setUp() {
MockitoAnnotations.initMocks(this);
transpiler = new BaseTranspiler(mockCompiler, "es6_runtime");
compiler = new BaseTranspiler.CompilerSupplier();
}
// Tests for BaseTranspiler
public void testTranspiler_transpile() {
when(mockCompiler.compile(FOO_JS, "bar"))
.thenReturn(new BaseTranspiler.CompileResult("result", true, "srcmap"));
assertThat(transpiler.transpile(FOO_JS, "bar"))
.isEqualTo(new TranspileResult(FOO_JS, "bar", "result", "srcmap"));
}
public void testTranspiler_noTranspilation() {
when(mockCompiler.compile(FOO_JS, "bar"))
.thenReturn(new BaseTranspiler.CompileResult("result", false, "srcmap"));
assertThat(transpiler.transpile(FOO_JS, "bar"))
.isEqualTo(new TranspileResult(FOO_JS, "bar", "bar", ""));
}
public void testTranspiler_runtime() {
when(mockCompiler.runtime("es6_runtime")).thenReturn("$jscomp.es6();");
assertThat(transpiler.runtime()).isEqualTo("$jscomp.es6();");
}
// Tests for CompilerSupplier
public void testCompilerSupplier_compileChanged() {
BaseTranspiler.CompileResult result = compiler.compile(SOURCE_JS, "const x = () => 42;");
assertThat(result.source).isEqualTo("var x = function() {\n return 42;\n};\n");
assertThat(result.transpiled).isTrue();
assertThat(result.sourceMap)
.contains("\"mappings\":\"AAAA,IAAMA,IAAIA,QAAA,EAAM;AAAA,SAAA,EAAA;AAAA,CAAhB;;\"");
}
public void testCompilerSupplier_compileNoChange() {
BaseTranspiler.CompileResult result = compiler.compile(SOURCE_JS, "var x = 42;");
assertThat(result.source).isEqualTo("var x = 42;\n");
assertThat(result.transpiled).isFalse();
assertThat(result.sourceMap).isEmpty();
}
public void testCompilerSupplier_error() {
try {
compiler.compile(SOURCE_JS, "cons x = () => 42;");
fail("Expected an exception.");
} catch (TranspilationException expected) {}
}
public void testCompilerSupplier_runtime() {
String runtime = compiler.runtime("es6_runtime");
assertThat(runtime).contains("$jscomp.polyfill(\"Map\"");
assertThat(runtime).contains("$jscomp.makeIterator");
assertThat(runtime).contains("$jscomp.inherits");
}
}
| {
"content_hash": "527bb40e9b6dd37129cfa941d4e25377",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 93,
"avg_line_length": 36,
"alnum_prop": 0.7156862745098039,
"repo_name": "MatrixFrog/closure-compiler",
"id": "636dddd39c8147e8c7a43e675d252728a8835584",
"size": "3672",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/com/google/javascript/jscomp/transpile/BaseTranspilerTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "1765"
},
{
"name": "Java",
"bytes": "15578871"
},
{
"name": "JavaScript",
"bytes": "6493323"
},
{
"name": "Protocol Buffer",
"bytes": "8652"
},
{
"name": "Shell",
"bytes": "703"
}
],
"symlink_target": ""
} |
#include "texture.h"
#include "../glx/hardext.h"
#include "../glx/streaming.h"
#include "array.h"
#include "blit.h"
#include "decompress.h"
#include "debug.h"
#include "enum_info.h"
#include "fpe.h"
#include "framebuffers.h"
#include "gles.h"
#include "init.h"
#include "loader.h"
#include "matrix.h"
#include "pixel.h"
#include "raster.h"
KHASH_MAP_IMPL_INT(tex, gltexture_t *);
//#define DEBUG
#ifdef DEBUG
#define DBG(a) a
#else
#define DBG(a)
#endif
#ifndef GL_TEXTURE_STREAM_IMG
#define GL_TEXTURE_STREAM_IMG 0x8C0D
#endif
#ifdef TEXSTREAM
#include <EGL/egl.h>
#include <EGL/eglext.h>
#endif
static int inline nlevel(int size, int level) {
if(size) {
size>>=level;
if(!size) size=1;
}
return size;
}
// conversions for GL_ARB_texture_rectangle
void tex_coord_rect_arb(GLfloat *tex, int stride, GLsizei len,
GLsizei width, GLsizei height) {
if (!tex || !width || !height)
return;
GLfloat iwidth, iheight;
iwidth = 1.0f/width;
iheight = 1.0f/height;
if(!stride) stride=4;
for (int i = 0; i < len; i++) {
tex[0] *= iwidth;
tex[1] *= iheight;
tex += stride;
}
}
void tex_coord_npot(GLfloat *tex, GLsizei len,
GLsizei width, GLsizei height,
GLsizei nwidth, GLsizei nheight) {
if (!tex || !nwidth || !nheight)
return;
GLfloat wratio = (width / (GLfloat)nwidth);
GLfloat hratio = (height / (GLfloat)nheight);
for (int i = 0; i < len; i++) {
tex[0] *= wratio;
tex[1] *= hratio;
tex += 4;
}
}
void tex_coord_matrix(GLfloat *tex, GLsizei len, const GLfloat* mat) {
if (!tex || !len || !mat || hardext.esversion!=1)
return;
for (int i = 0; i < len; i++) {
vector_matrix(tex, mat, tex);
tex += 4;
}
}
/* Setup the texture coordinates
*
* Have to check is ARB_RECTANGLE is used
* Apply texture matrix if not identity
* Or some NPOT texture used
*/
int tex_setup_needchange(GLuint itarget) {
if(hardext.esversion>1) return 0; // no text ajustement on ES2
GLuint texunit = glstate->texture.client;
gltexture_t *bound = glstate->texture.bound[texunit][itarget];
// check if some changes are needed
if ((itarget == ENABLED_TEXTURE_RECTANGLE)
|| (hardext.esversion==1 && bound->adjust)
|| (hardext.esversion==1 && !globals4es.texmat && !glstate->texture_matrix[texunit]->identity)
)
return 1;
return 0;
}
void tex_setup_texcoord(GLuint len, int changes, GLuint itarget, vertexattrib_t* ptr) {
LOAD_GLES_FPE(glTexCoordPointer);
GLuint texunit = glstate->texture.client;
gltexture_t *bound = glstate->texture.bound[texunit][itarget];
if (changes) {
// first convert to GLfloat, without normalization
if(glstate->helper_texlen[texunit]<len) {
if(glstate->helper_tex[texunit]) free(glstate->helper_tex[texunit]);
glstate->helper_tex[texunit] = malloc(4*sizeof(GLfloat)*len);
glstate->helper_texlen[texunit] = len;
}
copy_gl_pointer_tex_noalloc(glstate->helper_tex[texunit], ptr, 4, 0, len);
// Normalize if needed
if (itarget == ENABLED_TEXTURE_RECTANGLE)
tex_coord_rect_arb(glstate->helper_tex[texunit], 4, len, bound->width, bound->height);
// Apply transformation matrix if any
if (!(globals4es.texmat || glstate->texture_matrix[texunit]->identity))
tex_coord_matrix(glstate->helper_tex[texunit], len, getTexMat(texunit));
// NPOT adjust
if (bound->adjust)
tex_coord_npot(glstate->helper_tex[texunit], len, bound->width, bound->height, bound->nwidth, bound->nheight);
// All done, setup the texcoord array now
gles_glTexCoordPointer(4, GL_FLOAT, 0, glstate->helper_tex[texunit]);
} else {
gles_glTexCoordPointer(ptr->size, ptr->type, ptr->stride, ptr->pointer);
}
}
gltexture_t* gl4es_getCurrentTexture(GLenum target) {
GLuint itarget = what_target(target);
return glstate->texture.bound[glstate->texture.active][itarget];
}
gltexture_t* gl4es_getTexture(GLenum target, GLuint texture) {
// Get a texture based on glID
gltexture_t* tex = NULL;
if (texture == 0) return glstate->texture.zero; // texture 0 is a texture mostly like any other... it is not "unbind" texture in fact, but it's not shared
int ret;
khint_t k;
khash_t(tex) *list = glstate->texture.list;
k = kh_get(tex, list, texture);
if (k == kh_end(list)){
LOAD_GLES(glGenTextures);
k = kh_put(tex, list, texture, &ret);
tex = kh_value(list, k) = malloc(sizeof(gltexture_t));
memset(tex, 0, sizeof(gltexture_t));
tex->texture = texture;
if (texture)
gles_glGenTextures(1, &tex->glname);
else
tex->glname = 0; // special case for texture n# 0
DBG(printf("getTexture(%s, %u), failed, creating texture %u\n", PrintEnum(target), texture, tex->glname);)
tex->target = target;
tex->adjustxy[0] = tex->adjustxy[1] = 1.f;
tex->mipmap_auto = (globals4es.automipmap==1);
tex->mipmap_need = (globals4es.automipmap==1)?1:0;
tex->streamingID = -1;
init_sampler(&tex->sampler);
tex->alpha = true;
tex->fpe_format = FPE_TEX_RGBA;
tex->format = GL_RGBA;
tex->type = GL_UNSIGNED_BYTE;
tex->inter_format = GL_RGBA;
tex->inter_type = GL_UNSIGNED_BYTE;
} else {
tex = kh_value(list, k);
}
return tex;
}
void APIENTRY_GL4ES gl4es_glBindTexture(GLenum target, GLuint texture) {
noerrorShim();
DBG(printf("glBindTexture(%s, %u), active=%i, client=%i, list.active=%p (compiling=%d, pending=%d)\n", PrintEnum(target), texture, glstate->texture.active, glstate->texture.client, glstate->list.active, glstate->list.compiling, glstate->list.pending);)
if ((target!=GL_PROXY_TEXTURE_2D) && glstate->list.compiling && glstate->list.active && !glstate->list.pending) {
// check if already a texture binded, if yes, create a new list
NewStage(glstate->list.active, STAGE_BINDTEX);
rlBindTexture(glstate->list.active, target, texture);
} else {
int tex_changed = 1;
gltexture_t *tex = NULL;
const GLuint itarget = what_target(target);
tex = gl4es_getTexture(target, texture);
if (glstate->texture.bound[glstate->texture.active][itarget] == tex)
return;
FLUSH_BEGINEND;
tex_changed = glstate->texture.active+1;
glstate->texture.bound[glstate->texture.active][itarget] = tex;
LOAD_GLES(glBindTexture);
switch(target) {
// cube map are bounded immediatly, other are defered and will be applied with realize_bound or realize_textures
case GL_TEXTURE_CUBE_MAP:
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
gles_glBindTexture(target, tex?tex->glname:0);
break;
case GL_TEXTURE_1D:
case GL_TEXTURE_2D:
case GL_TEXTURE_3D:
case GL_TEXTURE_RECTANGLE_ARB:
if (glstate->bound_changed < glstate->texture.active+1)
glstate->bound_changed = glstate->texture.active+1;
if (glstate->fpe_state && glstate->fpe_bound_changed < glstate->texture.active+1)
glstate->fpe_bound_changed = glstate->texture.active+1;
break;
}
}
}
int is_mipmap_needed(glsampler_t* sampler)
{
switch(sampler->min_filter) {
case GL_NEAREST_MIPMAP_NEAREST:
case GL_NEAREST_MIPMAP_LINEAR:
case GL_LINEAR_MIPMAP_NEAREST:
case GL_LINEAR_MIPMAP_LINEAR:
return 1;
default:
return 0;
}
}
GLenum get_texture_min_filter(gltexture_t* texture, glsampler_t* sampler)
{
GLenum ret = sampler->min_filter;
if ((globals4es.automipmap==3)
|| ((globals4es.automipmap==1) && (texture->mipmap_auto==0))
|| (texture->compressed && (texture->mipmap_auto==0))) {
switch (ret) {
case GL_NEAREST_MIPMAP_NEAREST:
case GL_NEAREST_MIPMAP_LINEAR:
ret = GL_NEAREST;
break;
case GL_LINEAR_MIPMAP_NEAREST:
case GL_LINEAR_MIPMAP_LINEAR:
ret = GL_LINEAR;
break;
}
}
if(texture->valid && (texture->type==GL_FLOAT || texture->type==GL_HALF_FLOAT_OES)) {
// FLOAT textures have limited mipmap support in GLES2
ret = minmag_float(ret);
}
if(texture->valid && (texture->npot && globals4es.forcenpot)) {
// need to remove MIPMAP for npot if not supported in hardware
ret = minmag_forcenpot(ret);
}
return ret;
}
GLenum get_texture_wrap(GLenum wrap, gltexture_t* texture)
{
switch (wrap) {
case GL_CLAMP:
case GL_CLAMP_TO_BORDER:
wrap = GL_CLAMP_TO_EDGE;
break;
case GL_REPEAT:
case GL_MIRRORED_REPEAT_OES:
if(globals4es.defaultwrap==2 && hardext.npot<3 && !texture->valid)
wrap = GL_CLAMP_TO_EDGE;
else if(hardext.esversion>1 && hardext.npot<3 && texture->valid
&& texture->npot) {
// should "upgrade" the texture to POT size...
//printf("Warning, REPEAT / MIRRORED_REPEAT on NPOT texture\n");
wrap = GL_CLAMP_TO_EDGE; // repeat is not support on NPOT with limited_npot
}
break;
}
return wrap;
}
GLenum get_texture_wrap_s(gltexture_t* texture, glsampler_t *sampler)
{
return get_texture_wrap(sampler->wrap_s, texture);
}
GLenum get_texture_wrap_t(gltexture_t* texture, glsampler_t *sampler)
{
return get_texture_wrap(sampler->wrap_t, texture);
}
// TODO: also glTexParameterf(v)?
void APIENTRY_GL4ES gl4es_glTexParameterfv(GLenum target, GLenum pname, const GLfloat *params) {
DBG(printf("glTexParameterfv(%s, %s, [%f(%s)...])\n", PrintEnum(target), PrintEnum(pname), params[0], PrintEnum(params[0]));)
if(!glstate->list.pending) {
PUSH_IF_COMPILING(glTexParameterfv);
}
noerrorShim();
const GLint itarget = what_target(target);
const GLuint rtarget = map_tex_target(target);
gltexture_t *texture = glstate->texture.bound[glstate->texture.active][itarget];
if(!samplerParameterfv(&texture->sampler, pname, params)) {
LOAD_GLES(glTexParameterfv);
GLint param = params[0];
switch (pname) {
case GL_TEXTURE_MAX_LEVEL:
if (texture)
texture->max_level = param;
return; // not on GLES
case GL_TEXTURE_BASE_LEVEL:
texture->base_level = param;
return; // not on GLES
case GL_TEXTURE_LOD_BIAS:
return; // not on GLES
case GL_GENERATE_MIPMAP:
if(globals4es.automipmap==3)
return; // no mipmap, so no need to generate any
if(texture->mipmap_auto == ((param)?1:0))
return; // same value...
texture->mipmap_auto = (param)?1:0;
if(hardext.esversion>1) {
/*if(texture->valid) {
// force regeneration, if possible
FLUSH_BEGINEND;
realize_bound(glstate->texture.active, target);
LOAD_GLES2_OR_OES(glGenerateMipmap);
gl4es_glGenerateMipmap(rtarget);
}*/
return;
}
break; // fallback to calling actual glTexParameteri
case GL_TEXTURE_MAX_ANISOTROPY:
if(!hardext.aniso) {
errorShim(GL_INVALID_ENUM);
return;
}
if(param<0){
errorShim(GL_INVALID_VALUE);
return;
}
if(param>hardext.aniso) param=hardext.aniso;
texture->aniso = param;
break;
}
FLUSH_BEGINEND;
realize_bound(glstate->texture.active, target);
gles_glTexParameterfv(rtarget, pname, params);
errorGL();
}
}
void APIENTRY_GL4ES gl4es_glTexParameterf(GLenum target, GLenum pname, GLfloat param) {
gl4es_glTexParameterfv(target, pname, ¶m);
}
void APIENTRY_GL4ES gl4es_glTexParameteri(GLenum target, GLenum pname, GLint param) {
GLfloat fparam = param;
gl4es_glTexParameterfv(target, pname, &fparam);
}
void APIENTRY_GL4ES gl4es_glTexParameteriv(GLenum target, GLenum pname, const GLint * params) {
GLfloat fparams[4];
fparams[0] = *params;
if(pname==GL_TEXTURE_BORDER_COLOR)
for(int i=1; i<4; ++i)
fparams[i] = params[i];
gl4es_glTexParameterfv(target, pname, fparams);
}
void APIENTRY_GL4ES gl4es_glDeleteTextures(GLsizei n, const GLuint *textures) {
DBG(printf("glDeleteTextures(%d, %p {%d...})\n", n, textures, n?textures[0]:-1);)
if(!glstate) return;
FLUSH_BEGINEND;
noerrorShim();
LOAD_GLES(glDeleteTextures);
khash_t(tex) *list = glstate->texture.list;
if (list) {
khint_t k;
gltexture_t *tex;
for (int i = 0; i < n; i++) {
GLuint t = textures[i];
if(!t) continue; // skip texture 0
k = kh_get(tex, list, t);
if (k != kh_end(list)) {
tex = kh_value(list, k);
int a;
for (a=0; a<MAX_TEX; a++) {
int found=0;
for (int j=0; j<ENABLED_TEXTURE_LAST; j++)
if (tex == glstate->texture.bound[a][j]) {
glstate->texture.bound[a][j] = glstate->texture.zero;
found = 1;
}
if(glstate->actual_tex2d[a]==tex->glname) {
glstate->actual_tex2d[a] = 0;
found = 1;
}
if(found)
glstate->bound_changed = a+1;
}
gles_glDeleteTextures(1, &tex->glname);
// check if renderbuffer where associeted
if(tex->binded_fbo) {
if(tex->renderdepth)
gl4es_glDeleteRenderbuffers(1, &tex->renderdepth);
if(tex->renderstencil)
gl4es_glDeleteRenderbuffers(1, &tex->renderstencil);
}
errorGL();
#ifdef TEXSTREAM
if (globals4es.texstream && tex->streamed)
FreeStreamed(tex->streamingID);
#endif
#if 1
kh_del(tex, list, k);
if (tex->data) free(tex->data);
free(tex);
#else
tex->glname = tex->texture;
tex->streamed = false;
tex->streamingID = -1;
if (tex->data) free(tex->data);
tex->data = NULL;
#endif
}
}
}
}
void APIENTRY_GL4ES gl4es_glGenTextures(GLsizei n, GLuint * textures) {
DBG(printf("glGenTextures(%d, %p)\n", n, textures);)
if (n<=0)
return;
FLUSH_BEGINEND;
LOAD_GLES(glGenTextures);
gles_glGenTextures(n, textures);
errorGL();
// now, add all the textures to the list
int ret;
khint_t k;
khash_t(tex) *list = glstate->texture.list;
for (int i=0; i<n; i++) {
k = kh_get(tex, list, textures[i]);
DBG(printf(" -> textures[%d] = %u\n", i, textures[i]);)
gltexture_t *tex = NULL;
if (k == kh_end(list)){
k = kh_put(tex, list, textures[i], &ret);
tex = kh_value(list, k) = malloc(sizeof(gltexture_t));
memset(tex, 0, sizeof(gltexture_t));
tex->texture = textures[i];
tex->glname = textures[i];
tex->adjustxy[0] = tex->adjustxy[1] = 1.f;
tex->mipmap_auto = (globals4es.automipmap==1);
tex->mipmap_need = (globals4es.automipmap==1)?1:0;
tex->streamingID = -1;
tex->base_level = -1;
tex->max_level = -1;
tex->alpha = true;
init_sampler(&tex->sampler);
tex->fpe_format = FPE_TEX_RGBA;
tex->format = GL_RGBA;
tex->type = GL_UNSIGNED_BYTE;
tex->inter_format = GL_RGBA;
tex->inter_type = GL_UNSIGNED_BYTE;
} else {
tex = kh_value(list, k);
// in case of no delete here...
if (tex->glname==0)
tex->glname = tex->texture;
}
}
}
GLboolean APIENTRY_GL4ES gl4es_glAreTexturesResident(GLsizei n, const GLuint *textures, GLboolean *residences) {
noerrorShim();
return true;
}
void APIENTRY_GL4ES gl4es_glGetTexLevelParameterfv(GLenum target, GLint level, GLenum pname, GLfloat *params) {
DBG(printf("glGetTexLevelParameteriv(%s, %d, %s, %p)\n", PrintEnum(target), level, PrintEnum(pname), params);)
// simplification: (mostly) not taking "target" into account here
FLUSH_BEGINEND;
*params = 0;
noerrorShim();
const GLuint itarget = what_target(target);
const GLuint rtarget = map_tex_target(target);
gltexture_t* bound = glstate->texture.bound[glstate->texture.active][itarget];
if(!getSamplerParameterfv(&bound->sampler, pname, params)) {
switch (pname) {
case GL_TEXTURE_WIDTH:
if (rtarget==GL_PROXY_TEXTURE_2D)
(*params) = nlevel(glstate->proxy_width,level);
else {
(*params) = nlevel((bound)?bound->width:hardext.maxsize,level);
if(level && !(bound->mipmap_auto || bound->mipmap_need))
(*params) = 0; // Mipmap level not loaded
}
break;
case GL_TEXTURE_HEIGHT:
if (rtarget==GL_PROXY_TEXTURE_2D)
(*params) = nlevel(glstate->proxy_height,level);
else {
(*params) = nlevel((bound)?bound->height:hardext.maxsize,level);
if(level && !(bound->mipmap_auto || bound->mipmap_need))
(*params) = 0; // Mipmap level not loaded
}
break;
case GL_TEXTURE_INTERNAL_FORMAT:
if (rtarget==GL_PROXY_TEXTURE_2D)
(*params) = glstate->proxy_intformat;
else {
if (bound->compressed)
(*params) = bound->internalformat;
else {
if(bound->wanted_internal==GL_COMPRESSED_RGBA_S3TC_DXT1_EXT)
*params = bound->wanted_internal;
else
if((bound->orig_internal==GL_COMPRESSED_RGB) || (bound->orig_internal==GL_COMPRESSED_RGBA)) {
if(bound->orig_internal==GL_COMPRESSED_RGB)
*(params) = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
else
*(params) = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
} else
(*params) = bound->internalformat;
}
}
break;
case GL_TEXTURE_DEPTH:
(*params) = 0;
break;
case GL_TEXTURE_RED_TYPE:
case GL_TEXTURE_GREEN_TYPE:
case GL_TEXTURE_BLUE_TYPE:
case GL_TEXTURE_ALPHA_TYPE:
case GL_TEXTURE_DEPTH_TYPE:
(*params) = GL_FLOAT;
break;
case GL_TEXTURE_RED_SIZE:
case GL_TEXTURE_GREEN_SIZE:
case GL_TEXTURE_BLUE_SIZE:
case GL_TEXTURE_ALPHA_SIZE:
(*params) = 8;
break;
case GL_TEXTURE_DEPTH_SIZE:
(*params) = 0;
break;
case GL_TEXTURE_COMPRESSED:
if (bound->compressed)
(*params) = GL_TRUE;
else {
if((bound->orig_internal==GL_COMPRESSED_RGB) || (bound->orig_internal==GL_COMPRESSED_RGBA))
(*params) = GL_TRUE;
else
(*params) = GL_FALSE;
}
break;
case GL_TEXTURE_COMPRESSED_IMAGE_SIZE:
if((bound->orig_internal==GL_COMPRESSED_RGB) || (bound->orig_internal==GL_COMPRESSED_RGBA)) {
int w = nlevel((bound->width>>level),2); //DXT works on 4x4 blocks...
int h = nlevel((bound->height>>level),2);
w<<=2; h<<=2;
if (bound->orig_internal==GL_COMPRESSED_RGB || bound->wanted_internal==GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) //DXT1, 64bits (i.e. size=8) for a 4x4 block
(*params) = (w*h)/2;
else //DXT5, 64+64 (i.e. size = 16) for a 4x4 block
(*params) = w*h;
} else
(*params) = bound->width*bound->height*4;
break;
case GL_TEXTURE_BORDER:
(*params) = 0;
break;
case GL_TEXTURE_INTENSITY_SIZE:
if(bound)
(*params) = 32; // is it correct ? GLES doesn't store Intensity... Shall I return 0 instead? Or fake it and return 8?
else
(*params) = 0;
break;
case GL_TEXTURE_LUMINANCE_SIZE:
(*params) = (bound->orig_internal==GL_LUMINANCE || bound->orig_internal==GL_LUMINANCE_ALPHA)?8:0;
break;
case GL_TEXTURE_MAX_ANISOTROPY:
if(!hardext.aniso)
errorShim(GL_INVALID_ENUM);
else
(*params) = bound->aniso;
break;
case GL_TEXTURE_MAX_LEVEL:
if(!bound->valid || bound->max_level==-1)
(*params) = 1000;
else
(*params) = bound->max_level;
break;
default:
errorShim(GL_INVALID_ENUM); //Wrong here...
printf("Stubbed glGetTexLevelParameteriv(%s, %i, %s, %p)\n", PrintEnum(target), level, PrintEnum(pname), params);
}
}
}
void APIENTRY_GL4ES gl4es_glActiveTexture( GLenum texture ) {
DBG(printf("glActiveTexture(%s)\n", PrintEnum(texture));)
int tmu = texture - GL_TEXTURE0;
if (glstate->list.pending) {
/* if(glstate->texture.active == tmu) {
noerrorShim();
return;
}
gl4es_flush();*/
} else if (glstate->list.active) {
NewStage(glstate->list.active, STAGE_ACTIVETEX);
rlActiveTexture(glstate->list.active, texture);
return;
}
if ((tmu<0) || (tmu>=hardext.maxtex)) {
errorShim(GL_INVALID_ENUM);
return;
}
if(glstate->texture.active == tmu) {
noerrorShim();
return;
}
glstate->texture.active = tmu;
noerrorShim();
}
void APIENTRY_GL4ES gl4es_glClientActiveTexture( GLenum texture ) {
DBG(printf("glClientActiveTexture(%s)\n", PrintEnum(texture));)
int tmu = texture - GL_TEXTURE0;
if ((tmu<0) || (tmu >= hardext.maxtex)) {
errorShim(GL_INVALID_ENUM);
return;
}
// try to speed-up things...
if (glstate->texture.client == tmu)
return;
FLUSH_BEGINEND;
glstate->texture.client = tmu;
LOAD_GLES_FPE(glClientActiveTexture);
gles_glClientActiveTexture(texture);
errorGL();
}
void APIENTRY_GL4ES gl4es_glPixelStorei(GLenum pname, GLint param) {
DBG(printf("glPixelStorei(%s, %d)\n", PrintEnum(pname), param);)
// TODO: add to glGetIntegerv?
LOAD_GLES(glPixelStorei);
noerrorShim();
switch (pname) {
case GL_UNPACK_ROW_LENGTH:
glstate->texture.unpack_row_length = param;
return;
case GL_UNPACK_SKIP_PIXELS:
glstate->texture.unpack_skip_pixels = param;
return;
case GL_UNPACK_SKIP_ROWS:
glstate->texture.unpack_skip_rows = param;
return;
case GL_UNPACK_LSB_FIRST:
glstate->texture.unpack_lsb_first = param;
return;
case GL_UNPACK_IMAGE_HEIGHT:
glstate->texture.unpack_image_height = param;
return;
case GL_UNPACK_SWAP_BYTES:
case GL_PACK_SWAP_BYTES:
// Fake... TODO?
//glstate->texture.unpack_lsb_first = param;
return;
case GL_PACK_ROW_LENGTH:
glstate->texture.pack_row_length = param;
return;
case GL_PACK_SKIP_PIXELS:
glstate->texture.pack_skip_pixels = param;
return;
case GL_PACK_SKIP_ROWS:
glstate->texture.pack_skip_rows = param;
return;
case GL_PACK_LSB_FIRST:
glstate->texture.pack_lsb_first = param;
return;
case GL_PACK_IMAGE_HEIGHT:
glstate->texture.pack_image_height = param;
return;
case GL_PACK_ALIGNMENT:
if(glstate->texture.pack_align==param)
return;
if (param!=1 && param!=2 && param!=4 && param!=8) {
errorShim(GL_INVALID_VALUE);
return;
}
glstate->texture.pack_align=param;
break;
case GL_UNPACK_ALIGNMENT:
if(glstate->texture.unpack_align==param)
return;
if (param!=1 && param!=2 && param!=4 && param!=8) {
errorShim(GL_INVALID_VALUE);
return;
}
glstate->texture.unpack_align=param;
break;
}
errorGL();
gles_glPixelStorei(pname, param);
}
// bind the correct texture on Tex2D or TEXCUBE mapper...
void realize_bound(int TMU, GLenum target) {
realize_active();
LOAD_GLES(glBindTexture);
gltexture_t *tex = glstate->texture.bound[TMU][what_target(target)];
GLuint t = tex->glname;
DBG(printf("realize_bound(%d, %s), glsate->actual_tex2d[%d]=%u / %u\n", TMU, PrintEnum(target), TMU, glstate->actual_tex2d[TMU], t);)
#ifdef TEXSTREAM
LOAD_GLES(glEnable);
LOAD_GLES(glDisable);
#endif
switch (target) {
case GL_TEXTURE_1D:
case GL_TEXTURE_2D:
case GL_TEXTURE_3D:
case GL_TEXTURE_RECTANGLE_ARB:
#ifdef TEXSTREAM
if(glstate->bound_stream[TMU]) {
realize_active();
gles_glDisable(GL_TEXTURE_STREAM_IMG);
DeactivateStreaming();
glstate->bound_stream[TMU] = 0;
}
int streamingID = tex->streamingID;
if (globals4es.texstream && (streamingID>-1)) {
if(hardext.esversion<2) gles_glDisable(GL_TEXTURE_2D);
ActivateStreaming(streamingID);
glstate->bound_stream[TMU] = 1;
glstate->actual_tex2d[TMU] = t;
if (hardext.esversion<2)
gles_glEnable(GL_TEXTURE_STREAM_IMG);
if (glstate->bound_changed < TMU+1)
glstate->bound_changed = TMU+1;
} else
#endif
if(glstate->actual_tex2d[TMU] != t) {
realize_active();
gles_glBindTexture(GL_TEXTURE_2D, t);
glstate->actual_tex2d[TMU] = t;
if (glstate->bound_changed < TMU+1)
glstate->bound_changed = TMU+1;
}
break;
}
// all done
if (glstate->fpe_state && glstate->fpe_bound_changed < TMU+1)
glstate->fpe_bound_changed = TMU+1;
}
void realize_active() {
LOAD_GLES(glActiveTexture);
if(glstate->gleshard->active == glstate->texture.active)
return;
glstate->gleshard->active = glstate->texture.active;
gles_glActiveTexture(GL_TEXTURE0 + glstate->gleshard->active);
}
void realize_1texture(GLenum target, int wantedTMU, gltexture_t* tex, glsampler_t* sampler)
{
DBG(printf("realize_1texture(%s, %d, %p[%u], %p)\n", PrintEnum(target), wantedTMU, tex, tex->glname, sampler);)
LOAD_GLES(glActiveTexture);
LOAD_GLES(glTexParameteri);
LOAD_GLES(glBindTexture);
// check sampler stuff
if(!sampler) sampler = &tex->sampler;
GLuint oldtex = 0;
int TMU = (wantedTMU==-1)?glstate->gleshard->active:wantedTMU;
if(wantedTMU==-1) {
gltexture_t *bound = glstate->texture.bound[TMU][ENABLED_TEX2D];
oldtex = bound->glname;
if (oldtex!=tex->glname) gles_glBindTexture(GL_TEXTURE_2D, tex->glname);
}
GLenum param;
param = get_texture_min_filter(tex, sampler);
if(tex->actual.min_filter!=param) {
DBG(printf("Adjusting %s[%d]:Texture[%u].min_filter = %s (binded=%u)\n", PrintEnum(target), TMU, tex->glname, PrintEnum(param), glstate->actual_tex2d[TMU]);)
if(glstate->gleshard->active!=TMU) {
glstate->gleshard->active = TMU;
gles_glActiveTexture(GL_TEXTURE0+TMU);
}
gles_glTexParameteri(target, GL_TEXTURE_MIN_FILTER, param);
tex->actual.min_filter=param;
}
param = sampler->mag_filter;
if(tex->actual.mag_filter!=param) {
DBG(printf("Adjusting %s[%d]:Texture[%u].mag_filter = %s (min=%s/%s)\n", PrintEnum(target), TMU, tex->glname, PrintEnum(param), PrintEnum(sampler->min_filter), PrintEnum(tex->actual.min_filter));)
if(glstate->gleshard->active!=TMU) {
glstate->gleshard->active = TMU;
gles_glActiveTexture(GL_TEXTURE0+TMU);
}
gles_glTexParameteri(target, GL_TEXTURE_MAG_FILTER, param);
tex->actual.mag_filter=param;
}
param = get_texture_wrap_s(tex, sampler);
if(tex->actual.wrap_s!=param) {
DBG(printf("Adjusting %s[%d]:Texture[%u].wrap_s = %s\n", PrintEnum(target), TMU, tex->glname, PrintEnum(param));)
if(glstate->gleshard->active!=TMU) {
glstate->gleshard->active = TMU;
gles_glActiveTexture(GL_TEXTURE0+TMU);
}
gles_glTexParameteri(target, GL_TEXTURE_WRAP_S, param);
tex->actual.wrap_s=param;
}
param = get_texture_wrap_t(tex, sampler);
if(tex->actual.wrap_t!=param) {
DBG(printf("Adjusting %s[%d]:Texture[%u].wrap_t = %s\n", PrintEnum(target), TMU, tex->glname, PrintEnum(param));)
if(glstate->gleshard->active!=TMU) {
glstate->gleshard->active = TMU;
gles_glActiveTexture(GL_TEXTURE0+TMU);
}
gles_glTexParameteri(target, GL_TEXTURE_WRAP_T, param);
tex->actual.wrap_t=param;
}
if(wantedTMU==-1) {
if (oldtex!=tex->glname) gles_glBindTexture(GL_TEXTURE_2D, oldtex);
}
}
void realize_textures(int drawing) {
LOAD_GLES(glEnable);
LOAD_GLES(glDisable);
LOAD_GLES(glBindTexture);
LOAD_GLES(glActiveTexture);
LOAD_GLES(glTexParameteri);
#ifdef TEXSTREAM
DBG(printf("realize_textures(%d), glstate->bound_changed=%d, glstate->enable.texture[0]=%X glsate->actual_tex2d[0]=%u / glstate->bound_stream[0]=%u\n", drawing, glstate->bound_changed, glstate->enable.texture[0], glstate->actual_tex2d[0], glstate->bound_stream[0]);)
#else
DBG(printf("realize_textures(%d), glstate->bound_changed=%d, glstate->enable.texture[0]=%X glsate->actual_tex2d[0]=%u\n", drawing, glstate->bound_changed, glstate->enable.texture[0], glstate->actual_tex2d[0]);)
#endif
for (int i=0; i<glstate->bound_changed; i++) {
// get highest priority texture unit
int tmp = glstate->enable.texture[glstate->texture.active];
int tgt = ENABLED_TEX2D; // default to TEX2D
if(IS_TEX3D(tmp))
tgt = ENABLED_TEX3D;
else if(IS_TEXTURE_RECTANGLE(tmp))
tgt = ENABLED_TEXTURE_RECTANGLE;
else if(IS_TEX2D(tmp))
tgt = ENABLED_TEX2D;
else if(IS_TEX1D(tmp))
tgt = ENABLED_TEX1D;
else if(IS_CUBE_MAP(tmp))
tgt = ENABLED_CUBE_MAP;
GLenum target = map_tex_target(to_target(tgt));
gltexture_t *tex = glstate->texture.bound[i][tgt];
GLuint t = tex->glname;
if(tgt!=ENABLED_CUBE_MAP) {// CUBE MAP are immediatly bound
#ifdef TEXSTREAM
if(glstate->bound_stream[i]) {
realize_active();
if(hardext.esversion<2) gles_glDisable(GL_TEXTURE_STREAM_IMG);
DeactivateStreaming();
glstate->bound_stream[i] = 0;
}
#endif
if (t!=glstate->actual_tex2d[i]
#ifdef TEXSTREAM
|| (glstate->bound_stream[i] != tex->streamed)
#endif
) {
if(glstate->gleshard->active!=i) {
glstate->gleshard->active = i;
gles_glActiveTexture(GL_TEXTURE0+i);
}
#ifdef TEXSTREAM
int streamed = tex->streamed;
int streamingID = tex->streamingID;
if(glstate->bound_stream[i]) {
if(hardext.esversion<2) gles_glDisable(GL_TEXTURE_STREAM_IMG);
DeactivateStreaming();
if(hardext.esversion<2) gles_glEnable(GL_TEXTURE_2D);
glstate->bound_stream[i] = 0;
}
if (globals4es.texstream && (streamingID>-1)) {
if (IS_ANYTEX(tmp) && hardext.esversion<2)
gles_glDisable(GL_TEXTURE_2D);
target = GL_TEXTURE_STREAM_IMG;
ActivateStreaming(streamingID);
glstate->bound_stream[i] = 1;
glstate->actual_tex2d[i] = t;
if (IS_ANYTEX(tmp))
gles_glEnable(GL_TEXTURE_STREAM_IMG);
continue;
}
#endif
// bound...
DBG(printf("Binding %s/%s[%d]:Texture[%u] (sampler[%d]=%p)\n", PrintEnum(to_target(tgt)), PrintEnum(target), i, t, i, glstate->samplers.sampler[i]);)
gles_glBindTexture(GL_TEXTURE_2D, t);
glstate->actual_tex2d[i] = t;
}
}
// check, if drawing, if mipmap needs some special care...
if(drawing) {
if((globals4es.automipmap==3) || ((globals4es.automipmap==1) && (tex->mipmap_auto==0)) || (tex->compressed && (tex->mipmap_auto==0)))
tex->mipmap_need = 0;
else
tex->mipmap_need = (is_mipmap_needed(&tex->sampler) && (hardext.esversion!=1) && !tex->npot)?1:0;
if(tex->mipmap_need && !tex->mipmap_done) {
if(!tex->mipmap_auto) {
// should check if glGenerateMipmap exist, and fall back to no mipmap if not
LOAD_GLES2_OR_OES(glGenerateMipmap);
gles_glGenerateMipmap(GL_TEXTURE_2D);
}
tex->mipmap_done = 1;
}
}
realize_1texture(target, i, tex, glstate->samplers.sampler[i]);
}
glstate->bound_changed = 0;
}
//Direct wrapper
AliasExport(void,glBindTexture,,(GLenum target, GLuint texture));
AliasExport(void,glGenTextures,,(GLsizei n, GLuint * textures));
AliasExport(void,glDeleteTextures,,(GLsizei n, const GLuint * textures));
AliasExport(void,glTexParameteri,,(GLenum target, GLenum pname, GLint param));
AliasExport(void,glTexParameterf,,(GLenum target, GLenum pname, GLfloat param));
AliasExport(void,glTexParameterfv,,(GLenum target, GLenum pname, const GLfloat * params));
AliasExport(void,glTexParameteriv,,(GLenum target, GLenum pname, const GLint * params));
AliasExport(void,glGetTexLevelParameterfv,,(GLenum target, GLint level, GLenum pname, GLint *params));
AliasExport(GLboolean,glAreTexturesResident,,(GLsizei n, const GLuint *textures, GLboolean *residences));
AliasExport(void,glActiveTexture,,( GLenum texture ));
AliasExport(void,glClientActiveTexture,,( GLenum texture ));
AliasExport(void,glPixelStorei,,(GLenum pname, GLint param));
//ARB mapper
AliasExport(void,glActiveTexture,ARB,(GLenum texture));
AliasExport(void,glClientActiveTexture,ARB,(GLenum texture));
| {
"content_hash": "c9de6b45f7fcc11cc33c0c983bc5a922",
"timestamp": "",
"source": "github",
"line_count": 937,
"max_line_length": 270,
"avg_line_length": 39.062966915688364,
"alnum_prop": 0.5533304191027812,
"repo_name": "ptitSeb/glshim",
"id": "597ae4394862f89467d8521fd0dc6b1f386f834e",
"size": "36602",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/gl/texture_params.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "9660135"
},
{
"name": "C++",
"bytes": "25358"
},
{
"name": "CMake",
"bytes": "2780"
},
{
"name": "Makefile",
"bytes": "1031"
},
{
"name": "Objective-C",
"bytes": "1370"
},
{
"name": "Python",
"bytes": "7382"
},
{
"name": "Shell",
"bytes": "1609"
}
],
"symlink_target": ""
} |
php ./bin/console doctrine:generate:entities SiteBundle --no-backup
php ./bin/console doctrine:generate:entities UserBundle --no-backup
( exec "./app/bin/migrate.sh" ) | {
"content_hash": "b19c4720653b143171173ac7a1bb69bd",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 67,
"avg_line_length": 42,
"alnum_prop": 0.7678571428571429,
"repo_name": "plalance/fototek",
"id": "995bb9bd3269dc3b6a490812ce97fcc4f05c33fc",
"size": "178",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/bin/build.sh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10130"
},
{
"name": "HTML",
"bytes": "47616"
},
{
"name": "JavaScript",
"bytes": "177"
},
{
"name": "PHP",
"bytes": "81620"
},
{
"name": "Shell",
"bytes": "495"
}
],
"symlink_target": ""
} |
#ifndef itkMeshConvertPixelTraits_h
#define itkMeshConvertPixelTraits_h
#include "itkArray.h"
#include "itkMatrix.h"
#include "itkOffset.h"
#include "itkCovariantVector.h"
#include "itkVariableLengthVector.h"
#include "itkVector.h"
#include "itkPoint.h"
namespace itk
{
/** \class MeshConvertPixelTraits
* \brief Traits class used to by ConvertPixels to convert blocks of pixels.
*
* TOutputPixelType is the destination type. The input type is inferred
* by the templated static function Convert.
*
* This implementaion, does a simple assignment operator, so if you are
* going from from a higher bit representation to a lower bit one (int to
* char), you may want to specialize and add some sort of transfer function.
* \ingroup ITKIOMeshBase
*/
template<typename PixelType>
class MeshConvertPixelTraits
{
public:
/** Determine the pixel data type. */
using ComponentType = typename PixelType::ComponentType;
/** Return the number of components per pixel. */
static unsigned int GetNumberOfComponents()
{ return PixelType::GetNumberOfComponents();}
static unsigned int GetNumberOfComponents(const PixelType& )
{ return PixelType::GetNumberOfComponents();}
/** Return the nth component of the pixel. */
static ComponentType GetNthComponent(int c, const PixelType& pixel)
{ return pixel.GetNthComponent(c); }
/** Set the nth component of the pixel. */
static void SetNthComponent(int c, PixelType& pixel, const ComponentType& v)
{ pixel.SetNthComponent(c, v); }
/** Return a single scalar value from this pixel. */
static ComponentType GetScalarValue(const PixelType& pixel)
{ return pixel.GetScalarValue(); }
};
#define ITK_DEFAULTCONVERTTRAITS_NATIVE_SPECIAL(type) \
template<> \
class MeshConvertPixelTraits<type> \
{ \
public: \
using ComponentType = type; \
static unsigned int GetNumberOfComponents() \
{ \
return 1; \
} \
static unsigned int GetNumberOfComponents(const type& itkNotUsed(pixel))\
{ \
return 1; \
} \
static ComponentType GetNthComponent(int itkNotUsed(c), const type& pixel)\
{ \
return pixel; \
} \
static void SetNthComponent(int , type& pixel, const ComponentType& v) \
{ \
pixel = v; \
} \
static type GetScalarValue(const type& pixel) \
{ \
return pixel; \
} \
};
ITK_DEFAULTCONVERTTRAITS_NATIVE_SPECIAL(float)
ITK_DEFAULTCONVERTTRAITS_NATIVE_SPECIAL(double)
ITK_DEFAULTCONVERTTRAITS_NATIVE_SPECIAL(int)
ITK_DEFAULTCONVERTTRAITS_NATIVE_SPECIAL(char)
ITK_DEFAULTCONVERTTRAITS_NATIVE_SPECIAL(short)
ITK_DEFAULTCONVERTTRAITS_NATIVE_SPECIAL(unsigned int)
ITK_DEFAULTCONVERTTRAITS_NATIVE_SPECIAL(signed char)
ITK_DEFAULTCONVERTTRAITS_NATIVE_SPECIAL(unsigned char)
ITK_DEFAULTCONVERTTRAITS_NATIVE_SPECIAL(unsigned short)
ITK_DEFAULTCONVERTTRAITS_NATIVE_SPECIAL(long)
ITK_DEFAULTCONVERTTRAITS_NATIVE_SPECIAL(unsigned long)
ITK_DEFAULTCONVERTTRAITS_NATIVE_SPECIAL(bool)
#undef ITK_DEFAULTCONVERTTRAITS_NATIVE_SPECIAL
//
// Default traits for the Offset<> pixel type
//
#define ITK_MESH_DEFAULTCONVERTTRAITS_OFFSET_TYPE(dimension) \
template<> \
class MeshConvertPixelTraits< Offset<dimension> > \
{ \
public: \
using TargetType = Offset<dimension>; \
using ComponentType = TargetType::OffsetValueType; \
static unsigned int GetNumberOfComponents() \
{ \
return dimension; \
} \
static unsigned int GetNumberOfComponents(const TargetType& itkNotUsed(pixel)) \
{ \
return dimension; \
} \
static ComponentType GetNthComponent(int c, const TargetType& pixel) \
{ \
return pixel[c]; \
} \
static void SetNthComponent(int i, TargetType & pixel, const ComponentType& v) \
{ \
pixel[i] = v; \
} \
static ComponentType GetScalarValue(const TargetType& pixel) \
{ \
return pixel[0]; \
} \
}; \
// Define traits for Offset<> from dimensions 1 to 5
ITK_MESH_DEFAULTCONVERTTRAITS_OFFSET_TYPE(1)
ITK_MESH_DEFAULTCONVERTTRAITS_OFFSET_TYPE(2)
ITK_MESH_DEFAULTCONVERTTRAITS_OFFSET_TYPE(3)
ITK_MESH_DEFAULTCONVERTTRAITS_OFFSET_TYPE(4)
ITK_MESH_DEFAULTCONVERTTRAITS_OFFSET_TYPE(5)
//
// Default traits for the pixel types deriving from FixedArray<>
//
#define ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE(type,componenttype, dimension) \
template<> \
class MeshConvertPixelTraits< type< componenttype, dimension> > \
{ \
public: \
using TargetType = type< componenttype, dimension >; \
using ComponentType = componenttype; \
static unsigned int GetNumberOfComponents() \
{ \
return dimension; \
} \
static unsigned int GetNumberOfComponents(const TargetType& itkNotUsed(pixel)) \
{ \
return dimension; \
} \
static ComponentType GetNthComponent(int c, const TargetType& pixel) \
{ \
return pixel[c]; \
} \
static void SetNthComponent(int i, TargetType & pixel, const ComponentType& v) \
{ \
pixel[i] = v; \
} \
static ComponentType GetScalarValue(const TargetType& pixel) \
{ \
return pixel[0]; \
} \
}; \
//
//
// Define traits for Classed deriving from FixedArray from dimensions 1 to 6
// These classes include: Vector, CovariantVector and Point.
//
//
#define ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE_ALL_MACRO(ArrayType, Type) \
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE(ArrayType,Type,1) \
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE(ArrayType,Type,2) \
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE(ArrayType,Type,3) \
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE(ArrayType,Type,4) \
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE(ArrayType,Type,5) \
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE(ArrayType,Type,6)
#define ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE_ALL_TYPES_MACRO(ArrayType) \
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE_ALL_MACRO(ArrayType, char); \
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE_ALL_MACRO(ArrayType, signed char); \
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE_ALL_MACRO(ArrayType, unsigned char); \
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE_ALL_MACRO(ArrayType, short); \
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE_ALL_MACRO(ArrayType, unsigned short); \
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE_ALL_MACRO(ArrayType, int); \
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE_ALL_MACRO(ArrayType, unsigned int); \
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE_ALL_MACRO(ArrayType, long); \
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE_ALL_MACRO(ArrayType, unsigned long); \
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE_ALL_MACRO(ArrayType, float); \
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE_ALL_MACRO(ArrayType, double);
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE_ALL_TYPES_MACRO(Vector);
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE_ALL_TYPES_MACRO(CovariantVector);
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE_ALL_TYPES_MACRO(Point);
ITK_MESH_DEFAULTCONVERTTRAITS_FIXEDARRAY_TYPE_ALL_TYPES_MACRO(FixedArray);
//
// End of Traits for the classes deriving from FixedArray.
//
//
//
// Default traits for the pixel types deriving from Matrix<>
//
#define ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE(type,componenttype,rows,cols) \
template<> \
class MeshConvertPixelTraits< type< componenttype, rows, cols > > \
{ \
public: \
using TargetType = type< componenttype, rows, cols >; \
using ComponentType = componenttype; \
static unsigned int GetNumberOfComponents() \
{ \
return rows * cols; \
} \
static unsigned int GetNumberOfComponents(const TargetType& itkNotUsed(pixel)) \
{ \
return rows * cols; \
} \
static ComponentType GetNthComponent(int c, const TargetType& pixel) \
{ \
const unsigned int row = c / cols; \
const unsigned int col = c % cols; \
return pixel[row][col]; \
} \
static void SetNthComponent(int i, TargetType & pixel, const ComponentType& v) \
{ \
const unsigned int row = i / cols; \
const unsigned int col = i % cols; \
pixel[row][col] = v; \
} \
static ComponentType GetScalarValue(const TargetType& pixel) \
{ \
return pixel[0][0]; \
} \
}; \
//
//
// Define traits for Classed deriving from Matrix from dimensions 1 to 6
//
//
#define ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE_ALL_MACRO(ArrayType, Type) \
ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE(ArrayType,Type,1,1) \
ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE(ArrayType,Type,2,2) \
ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE(ArrayType,Type,3,3) \
ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE(ArrayType,Type,4,4) \
ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE(ArrayType,Type,5,5) \
ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE(ArrayType,Type,6,6)
#define ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE_ALL_TYPES_MACRO(ArrayType) \
ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE_ALL_MACRO(ArrayType, char); \
ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE_ALL_MACRO(ArrayType, signed char); \
ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE_ALL_MACRO(ArrayType, unsigned char); \
ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE_ALL_MACRO(ArrayType, short); \
ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE_ALL_MACRO(ArrayType, unsigned short); \
ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE_ALL_MACRO(ArrayType, int); \
ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE_ALL_MACRO(ArrayType, unsigned int); \
ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE_ALL_MACRO(ArrayType, long); \
ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE_ALL_MACRO(ArrayType, unsigned long); \
ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE_ALL_MACRO(ArrayType, float); \
ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE_ALL_MACRO(ArrayType, double);
//
// Add here other classes that derive from Matrix or that have the same API
//
ITK_MESH_DEFAULTCONVERTTRAITS_MATRIX_TYPE_ALL_TYPES_MACRO(Matrix);
//
// End of Traits for the classes deriving from Matrix.
//
//
//
// Default traits for the pixel types deriving from std::complex<>
//
#define ITK_MESH_DEFAULTCONVERTTRAITS_COMPLEX_TYPE( componenttype ) \
template<> \
class MeshConvertPixelTraits< ::std::complex< componenttype > > \
{ \
public: \
using TargetType = ::std::complex< componenttype>; \
using ComponentType = componenttype; \
static unsigned int GetNumberOfComponents() \
{ \
return 2; \
} \
static unsigned int GetNumberOfComponents(const TargetType & itkNotUsed(pixel)) \
{ \
return 2; \
} \
static ComponentType GetNthComponent(int i, TargetType & pixel) \
{ \
if( i == 0 ) \
{ \
return pixel.imag(); \
} \
else \
{ \
return pixel.real(); \
} \
} \
static void SetNthComponent(int i, TargetType & pixel, const ComponentType& v) \
{ \
if( i == 0 ) \
{ \
pixel = TargetType( v, pixel.imag() ); \
} \
else \
{ \
pixel = TargetType( pixel.real(), v ); \
} \
} \
static ComponentType GetScalarValue(const TargetType& pixel) \
{ \
return std::norm(pixel); \
} \
}; \
ITK_MESH_DEFAULTCONVERTTRAITS_COMPLEX_TYPE(float);
ITK_MESH_DEFAULTCONVERTTRAITS_COMPLEX_TYPE(double);
#define ITK_MESH_DEFAULTCONVERTTRAITS_ARRAY_TYPE(type,componenttype) \
template<> \
class MeshConvertPixelTraits< type< componenttype> > \
{ \
public: \
using TargetType = type< componenttype >; \
using ComponentType = componenttype; \
static unsigned int GetNumberOfComponents() \
{ \
return 0; \
} \
static unsigned int GetNumberOfComponents(const TargetType& pixel) \
{ \
return pixel.Size(); \
} \
static ComponentType GetNthComponent(int c, const TargetType& pixel) \
{ \
return pixel[c]; \
} \
static void SetNthComponent(int i, TargetType & pixel, const ComponentType& v) \
{ \
pixel[i] = v; \
} \
static ComponentType GetScalarValue(const TargetType& pixel) \
{ \
return pixel[0]; \
} \
}; \
#define ITK_MESH_DEFAULTCONVERTTRAITS_ARRAY_TYPE_ALL_TYPES_MACRO(ArrayType) \
ITK_MESH_DEFAULTCONVERTTRAITS_ARRAY_TYPE(ArrayType, char); \
ITK_MESH_DEFAULTCONVERTTRAITS_ARRAY_TYPE(ArrayType, signed char); \
ITK_MESH_DEFAULTCONVERTTRAITS_ARRAY_TYPE(ArrayType, unsigned char); \
ITK_MESH_DEFAULTCONVERTTRAITS_ARRAY_TYPE(ArrayType, short); \
ITK_MESH_DEFAULTCONVERTTRAITS_ARRAY_TYPE(ArrayType, unsigned short); \
ITK_MESH_DEFAULTCONVERTTRAITS_ARRAY_TYPE(ArrayType, int); \
ITK_MESH_DEFAULTCONVERTTRAITS_ARRAY_TYPE(ArrayType, unsigned int); \
ITK_MESH_DEFAULTCONVERTTRAITS_ARRAY_TYPE(ArrayType, long); \
ITK_MESH_DEFAULTCONVERTTRAITS_ARRAY_TYPE(ArrayType, unsigned long); \
ITK_MESH_DEFAULTCONVERTTRAITS_ARRAY_TYPE(ArrayType, float); \
ITK_MESH_DEFAULTCONVERTTRAITS_ARRAY_TYPE(ArrayType, double);
ITK_MESH_DEFAULTCONVERTTRAITS_ARRAY_TYPE_ALL_TYPES_MACRO(Array);
ITK_MESH_DEFAULTCONVERTTRAITS_ARRAY_TYPE_ALL_TYPES_MACRO(VariableLengthVector);
//
// End of Traits for the classes deriving from std::complex.
//
//
} // end namespace itk
#endif
| {
"content_hash": "22c1fcd20b716dfff7238c5f8e88aac9",
"timestamp": "",
"source": "github",
"line_count": 385,
"max_line_length": 87,
"avg_line_length": 61.50909090909091,
"alnum_prop": 0.39335332122798866,
"repo_name": "spinicist/ITK",
"id": "1c824b64354d0aa5ad88e2cd564d0c21a59ed5fd",
"size": "24456",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "Modules/IO/MeshBase/include/itkMeshConvertPixelTraits.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "296"
},
{
"name": "C",
"bytes": "33723237"
},
{
"name": "C++",
"bytes": "47607115"
},
{
"name": "CMake",
"bytes": "2448515"
},
{
"name": "CSS",
"bytes": "24960"
},
{
"name": "DIGITAL Command Language",
"bytes": "709"
},
{
"name": "Fortran",
"bytes": "2260380"
},
{
"name": "HTML",
"bytes": "208515"
},
{
"name": "Io",
"bytes": "1833"
},
{
"name": "Java",
"bytes": "28585"
},
{
"name": "JavaScript",
"bytes": "1522"
},
{
"name": "Lex",
"bytes": "7073"
},
{
"name": "Makefile",
"bytes": "292947"
},
{
"name": "Objective-C",
"bytes": "59064"
},
{
"name": "Objective-C++",
"bytes": "5773"
},
{
"name": "OpenEdge ABL",
"bytes": "85244"
},
{
"name": "Perl",
"bytes": "17941"
},
{
"name": "Python",
"bytes": "885632"
},
{
"name": "Ruby",
"bytes": "296"
},
{
"name": "Shell",
"bytes": "185530"
},
{
"name": "Tcl",
"bytes": "74786"
},
{
"name": "WebAssembly",
"bytes": "4056"
},
{
"name": "XSLT",
"bytes": "206927"
},
{
"name": "Yacc",
"bytes": "21035"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe 'APIv3 Area details' do
before { get("/api/v3/areas/#{id}") }
context 'with a valid area ID' do
let(:id) { 'nl' }
it 'responds successfully' do
expect(response).to have_http_status(:ok)
end
it 'replies with JSON' do
expect(response.media_type).to eq('application/json')
end
it 'sends the area data' do
expect(JSON.parse(response.body)).to eq(
AreaSerializer.new(Area.get(:nl), detailed: true).as_json
)
end
end
context 'with an area ID that does not exist' do
let(:id) { 'nope' }
it 'responds with not found' do
expect(response).to have_http_status(:not_found)
end
end
end
| {
"content_hash": "23e92341950b37fde62e896377633d6e",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 65,
"avg_line_length": 22.548387096774192,
"alnum_prop": 0.6251788268955651,
"repo_name": "quintel/etengine",
"id": "b49af54bf56e7319bc83880be245b1419fa0bdf0",
"size": "699",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/requests/api/v3/area_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8720"
},
{
"name": "CoffeeScript",
"bytes": "10941"
},
{
"name": "Dockerfile",
"bytes": "570"
},
{
"name": "HTML",
"bytes": "24245"
},
{
"name": "Haml",
"bytes": "73816"
},
{
"name": "JavaScript",
"bytes": "480986"
},
{
"name": "Ruby",
"bytes": "1556794"
},
{
"name": "SCSS",
"bytes": "5800"
},
{
"name": "Sass",
"bytes": "17259"
},
{
"name": "Shell",
"bytes": "2088"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML>
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (11.0.13) on Thu Sep 22 11:06:07 MDT 2022 -->
<title>Uses of Class mil.nga.geopackage.tiles.reproject.PlatteCarreOptimize (GeoPackage Core 6.5.0 API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-09-22">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../../jquery/jquery-ui.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
<script type="text/javascript" src="../../../../../../jquery/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="../../../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../../../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]-->
<script type="text/javascript" src="../../../../../../jquery/jquery-3.5.1.js"></script>
<script type="text/javascript" src="../../../../../../jquery/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class mil.nga.geopackage.tiles.reproject.PlatteCarreOptimize (GeoPackage Core 6.5.0 API)";
}
}
catch(err) {
}
//-->
var pathtoroot = "../../../../../../";
var useModuleDirectories = true;
loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<header role="banner">
<nav role="navigation">
<div class="fixedNav">
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a id="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../index.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../PlatteCarreOptimize.html" title="class in mil.nga.geopackage.tiles.reproject">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" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses.html">All Classes</a></li>
</ul>
<ul class="navListSearch">
<li><label for="search">SEARCH:</label>
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">
</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>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a id="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
</div>
<div class="navPadding"> </div>
<script type="text/javascript"><!--
$('.navPadding').css('padding-top', $('.fixedNav').css("height"));
//-->
</script>
</nav>
</header>
<main role="main">
<div class="header">
<h2 title="Uses of Class mil.nga.geopackage.tiles.reproject.PlatteCarreOptimize" class="title">Uses of Class<br>mil.nga.geopackage.tiles.reproject.PlatteCarreOptimize</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary">
<caption><span>Packages that use <a href="../PlatteCarreOptimize.html" title="class in mil.nga.geopackage.tiles.reproject">PlatteCarreOptimize</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<th class="colFirst" scope="row"><a href="#mil.nga.geopackage.tiles.reproject">mil.nga.geopackage.tiles.reproject</a></th>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList">
<section role="region"><a id="mil.nga.geopackage.tiles.reproject">
<!-- -->
</a>
<h3>Uses of <a href="../PlatteCarreOptimize.html" title="class in mil.nga.geopackage.tiles.reproject">PlatteCarreOptimize</a> in <a href="../package-summary.html">mil.nga.geopackage.tiles.reproject</a></h3>
<table class="useSummary">
<caption><span>Methods in <a href="../package-summary.html">mil.nga.geopackage.tiles.reproject</a> that return <a href="../PlatteCarreOptimize.html" title="class in mil.nga.geopackage.tiles.reproject">PlatteCarreOptimize</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colSecond" scope="col">Method</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../PlatteCarreOptimize.html" title="class in mil.nga.geopackage.tiles.reproject">PlatteCarreOptimize</a></code></td>
<th class="colSecond" scope="row"><span class="typeNameLabel">PlatteCarreOptimize.</span><code><span class="memberNameLink"><a href="../PlatteCarreOptimize.html#create()">create</a></span>()</code></th>
<td class="colLast">
<div class="block">Create with minimal bounds</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../PlatteCarreOptimize.html" title="class in mil.nga.geopackage.tiles.reproject">PlatteCarreOptimize</a></code></td>
<th class="colSecond" scope="row"><span class="typeNameLabel">PlatteCarreOptimize.</span><code><span class="memberNameLink"><a href="../PlatteCarreOptimize.html#createWorld()">createWorld</a></span>()</code></th>
<td class="colLast">
<div class="block">Create with world bounds</div>
</td>
</tr>
</tbody>
</table>
</section>
</li>
</ul>
</li>
</ul>
</div>
</main>
<footer role="contentinfo">
<nav role="navigation">
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a id="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../index.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../PlatteCarreOptimize.html" title="class in mil.nga.geopackage.tiles.reproject">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" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses.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>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a id="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</nav>
<p class="legalCopy"><small>Copyright © 2022 <a href="https://www.nga.mil/">National Geospatial-Intelligence Agency</a>. All rights reserved.</small></p>
</footer>
</body>
</html>
| {
"content_hash": "d5fba1c064702cd7a3148d99fd6d10bb",
"timestamp": "",
"source": "github",
"line_count": 202,
"max_line_length": 275,
"avg_line_length": 38.777227722772274,
"alnum_prop": 0.6464955955572578,
"repo_name": "ngageoint/geopackage-core-java",
"id": "0915b74844a7727cc84e96d7855724a6a14ccb19",
"size": "7833",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/docs/api/mil/nga/geopackage/tiles/reproject/class-use/PlatteCarreOptimize.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1784920"
}
],
"symlink_target": ""
} |
from importlib import import_module
from django.apps import apps
from django.core.management.base import BaseCommand, CommandError
from django.core.management.color import no_style
from django.core.management.sql import emit_post_migrate_signal, sql_flush
from django.db import DEFAULT_DB_ALIAS, connections
class Command(BaseCommand):
help = (
'Removes ALL DATA from the database, including data added during '
'migrations. Does not achieve a "fresh install" state.'
)
stealth_options = ('reset_sequences', 'allow_cascade', 'inhibit_post_migrate')
def add_arguments(self, parser):
parser.add_argument(
'--noinput', '--no-input', action='store_false', dest='interactive',
help='Tells Django to NOT prompt the user for input of any kind.',
)
parser.add_argument(
'--database', action='store', dest='database', default=DEFAULT_DB_ALIAS,
help='Nominates a database to flush. Defaults to the "default" database.',
)
def handle(self, **options):
database = options['database']
connection = connections[database]
verbosity = options['verbosity']
interactive = options['interactive']
# The following are stealth options used by Django's internals.
reset_sequences = options.get('reset_sequences', True)
allow_cascade = options.get('allow_cascade', False)
inhibit_post_migrate = options.get('inhibit_post_migrate', False)
self.style = no_style()
# Import the 'management' module within each installed app, to register
# dispatcher events.
for app_config in apps.get_app_configs():
try:
import_module('.management', app_config.name)
except ImportError:
pass
sql_list = sql_flush(self.style, connection, only_django=True,
reset_sequences=reset_sequences,
allow_cascade=allow_cascade)
if interactive:
confirm = input("""You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the %r database,
and return each table to an empty state.
Are you sure you want to do this?
Type 'yes' to continue, or 'no' to cancel: """ % connection.settings_dict['NAME'])
else:
confirm = 'yes'
if confirm == 'yes':
try:
connection.ops.execute_sql_flush(database, sql_list)
except Exception as exc:
raise CommandError(
"Database %s couldn't be flushed. Possible reasons:\n"
" * The database isn't running or isn't configured correctly.\n"
" * At least one of the expected database tables doesn't exist.\n"
" * The SQL was invalid.\n"
"Hint: Look at the output of 'django-admin sqlflush'. "
"That's the SQL this command wasn't able to run.\n" % (
connection.settings_dict['NAME'],
)
) from exc
# Empty sql_list may signify an empty database and post_migrate would then crash
if sql_list and not inhibit_post_migrate:
# Emit the post migrate signal. This allows individual applications to
# respond as if the database had been migrated from scratch.
emit_post_migrate_signal(verbosity, interactive, database)
else:
self.stdout.write("Flush cancelled.\n")
| {
"content_hash": "90e534a92002b3ee5fb56d648f41b877",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 92,
"avg_line_length": 43.78048780487805,
"alnum_prop": 0.6072423398328691,
"repo_name": "edmorley/django",
"id": "f6ae83940a534c18bf9029f0ba7b1f023ab296c2",
"size": "3590",
"binary": false,
"copies": "22",
"ref": "refs/heads/master",
"path": "django/core/management/commands/flush.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "55935"
},
{
"name": "HTML",
"bytes": "202902"
},
{
"name": "JavaScript",
"bytes": "252653"
},
{
"name": "Makefile",
"bytes": "125"
},
{
"name": "Python",
"bytes": "11837174"
},
{
"name": "Shell",
"bytes": "809"
},
{
"name": "Smarty",
"bytes": "130"
}
],
"symlink_target": ""
} |
#!/bin/bash
# Copyright 2014 The Kubernetes Authors All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# exit on any error
set -e
function release_not_found() {
echo "It looks as if you don't have a compiled version of Kubernetes. If you" >&2
echo "are running from a clone of the git repo, please run ./build/release.sh." >&2
echo "Note that this requires having Docker installed. If you are running " >&2
echo "from a release tarball, something is wrong. Look at " >&2
echo "http://kubernetes.io/ for information on how to contact the development team for help." >&2
exit 1
}
# Look for our precompiled binary releases. When running from a source repo,
# these are generated under _output. When running from an release tarball these
# are under ./server.
server_binary_tar="/vagrant/server/kubernetes-server-linux-amd64.tar.gz"
if [[ ! -f "$server_binary_tar" ]]; then
server_binary_tar="/vagrant/_output/release-tars/kubernetes-server-linux-amd64.tar.gz"
fi
if [[ ! -f "$server_binary_tar" ]]; then
release_not_found
fi
salt_tar="/vagrant/server/kubernetes-salt.tar.gz"
if [[ ! -f "$salt_tar" ]]; then
salt_tar="/vagrant/_output/release-tars/kubernetes-salt.tar.gz"
fi
if [[ ! -f "$salt_tar" ]]; then
release_not_found
fi
# Setup hosts file to support ping by hostname to each minion in the cluster from apiserver
for (( i=0; i<${#MINION_NAMES[@]}; i++)); do
minion=${MINION_NAMES[$i]}
ip=${MINION_IPS[$i]}
if [ ! "$(cat /etc/hosts | grep $minion)" ]; then
echo "Adding $minion to hosts file"
echo "$ip $minion" >> /etc/hosts
fi
done
echo "127.0.0.1 localhost" >> /etc/hosts # enables cmds like 'kubectl get pods' on master.
# Update salt configuration
mkdir -p /etc/salt/minion.d
cat <<EOF >/etc/salt/minion.d/master.conf
master: '$(echo "$MASTER_NAME" | sed -e "s/'/''/g")'
master: '$(echo "$MASTER_NAME" | sed -e "s/'/''/g")'
auth_timeout: 10
auth_tries: 2
auth_safemode: True
ping_interval: 1
random_reauth_delay: 3
state_aggregrate:
- pkg
EOF
cat <<EOF >/etc/salt/minion.d/grains.conf
grains:
node_ip: '$(echo "$MASTER_IP" | sed -e "s/'/''/g")'
publicAddressOverride: '$(echo "$MASTER_IP" | sed -e "s/'/''/g")'
network_mode: openvswitch
networkInterfaceName: eth1
api_servers: '$(echo "$MASTER_IP" | sed -e "s/'/''/g")'
cloud: vagrant
roles:
- kubernetes-master
runtime_config: '$(echo "$RUNTIME_CONFIG" | sed -e "s/'/''/g")'
EOF
mkdir -p /srv/salt-overlay/pillar
cat <<EOF >/srv/salt-overlay/pillar/cluster-params.sls
portal_net: '$(echo "$PORTAL_NET" | sed -e "s/'/''/g")'
cert_ip: '$(echo "$MASTER_IP" | sed -e "s/'/''/g")'
enable_cluster_monitoring: '$(echo "$ENABLE_CLUSTER_MONITORING" | sed -e "s/'/''/g")'
enable_node_monitoring: '$(echo "$ENABLE_NODE_MONITORING" | sed -e "s/'/''/g")'
enable_cluster_logging: '$(echo "$ENABLE_CLUSTER_LOGGING" | sed -e "s/'/''/g")'
enable_node_logging: '$(echo "$ENABLE_NODE_LOGGING" | sed -e "s/'/''/g")'
logging_destination: '$(echo "$LOGGING_DESTINATION" | sed -e "s/'/''/g")'
elasticsearch_replicas: '$(echo "$ELASTICSEARCH_LOGGING_REPLICAS" | sed -e "s/'/''/g")'
enable_cluster_dns: '$(echo "$ENABLE_CLUSTER_DNS" | sed -e "s/'/''/g")'
dns_replicas: '$(echo "$DNS_REPLICAS" | sed -e "s/'/''/g")'
dns_server: '$(echo "$DNS_SERVER_IP" | sed -e "s/'/''/g")'
dns_domain: '$(echo "$DNS_DOMAIN" | sed -e "s/'/''/g")'
instance_prefix: '$(echo "$INSTANCE_PREFIX" | sed -e "s/'/''/g")'
admission_control: '$(echo "$ADMISSION_CONTROL" | sed -e "s/'/''/g")'
EOF
# Configure the salt-master
# Auto accept all keys from minions that try to join
mkdir -p /etc/salt/master.d
cat <<EOF >/etc/salt/master.d/auto-accept.conf
open_mode: True
auto_accept: True
EOF
cat <<EOF >/etc/salt/master.d/reactor.conf
# React to new minions starting by running highstate on them.
reactor:
- 'salt/minion/*/start':
- /srv/reactor/highstate-new.sls
EOF
cat <<EOF >/etc/salt/master.d/salt-output.conf
# Minimize the amount of output to terminal
state_verbose: False
state_output: mixed
log_level: debug
log_level_logfile: debug
EOF
cat <<EOF >/etc/salt/minion.d/log-level-debug.conf
log_level: debug
log_level_logfile: debug
EOF
# Generate and distribute a shared secret (bearer token) to
# apiserver and kubelet so that kubelet can authenticate to
# apiserver to send events.
known_tokens_file="/srv/salt-overlay/salt/kube-apiserver/known_tokens.csv"
if [[ ! -f "${known_tokens_file}" ]]; then
kubelet_token=$(cat /dev/urandom | base64 | tr -d "=+/" | dd bs=32 count=1 2> /dev/null)
kube_proxy_token=$(cat /dev/urandom | base64 | tr -d "=+/" | dd bs=32 count=1 2> /dev/null)
mkdir -p /srv/salt-overlay/salt/kube-apiserver
known_tokens_file="/srv/salt-overlay/salt/kube-apiserver/known_tokens.csv"
(umask u=rw,go= ;
echo "$kubelet_token,kubelet,kubelet" > $known_tokens_file;
echo "$kube_proxy_token,kube_proxy,kube_proxy" >> $known_tokens_file)
mkdir -p /srv/salt-overlay/salt/kubelet
kubelet_auth_file="/srv/salt-overlay/salt/kubelet/kubernetes_auth"
(umask u=rw,go= ; echo "{\"BearerToken\": \"$kubelet_token\", \"Insecure\": true }" > $kubelet_auth_file)
mkdir -p /srv/salt-overlay/salt/kube-proxy
kube_proxy_kubeconfig_file="/srv/salt-overlay/salt/kube-proxy/kubeconfig"
# Make a kubeconfig file with the token.
# TODO(etune): put apiserver certs into secret too, and reference from authfile,
# so that "Insecure" is not needed.
(umask 077;
cat > "${kube_proxy_kubeconfig_file}" <<EOF
apiVersion: v1
kind: Config
users:
- name: kube-proxy
user:
token: ${kube_proxy_token}
clusters:
- name: local
cluster:
insecure-skip-tls-verify: true
contexts:
- context:
cluster: local
user: kube-proxy
name: service-account-context
current-context: service-account-context
EOF
)
# Generate tokens for other "service accounts". Append to known_tokens.
#
# NB: If this list ever changes, this script actually has to
# change to detect the existence of this file, kill any deleted
# old tokens and add any new tokens (to handle the upgrade case).
service_accounts=("system:scheduler" "system:controller_manager" "system:logging" "system:monitoring" "system:dns")
for account in "${service_accounts[@]}"; do
token=$(dd if=/dev/urandom bs=128 count=1 2>/dev/null | base64 | tr -d "=+/" | dd bs=32 count=1 2>/dev/null)
echo "${token},${account},${account}" >> "${known_tokens_file}"
done
fi
# Configure nginx authorization
mkdir -p /srv/salt-overlay/salt/nginx
if [[ ! -f /srv/salt-overlay/salt/nginx/htpasswd ]]; then
python "${KUBE_ROOT}/third_party/htpasswd/htpasswd.py" \
-b -c "/srv/salt-overlay/salt/nginx/htpasswd" \
"$MASTER_USER" "$MASTER_PASSWD"
fi
echo "Running release install script"
rm -rf /kube-install
mkdir -p /kube-install
pushd /kube-install
tar xzf "$salt_tar"
cp "$server_binary_tar" .
./kubernetes/saltbase/install.sh "${server_binary_tar##*/}"
popd
# we will run provision to update code each time we test, so we do not want to do salt installs each time
if ! which salt-master &>/dev/null; then
# Configure the salt-api
cat <<EOF >/etc/salt/master.d/salt-api.conf
# Set vagrant user as REST API user
external_auth:
pam:
vagrant:
- .*
rest_cherrypy:
port: 8000
host: 127.0.0.1
disable_ssl: True
webhook_disable_auth: True
EOF
# Install Salt Master
#
# -M installs the master
# -N does not install the minion
curl -sS -L --connect-timeout 20 --retry 6 --retry-delay 10 https://bootstrap.saltstack.com | sh -s -- -M -N
# Install salt-api
#
# This is used to provide the network transport for salt-api
yum install -y python-cherrypy
# This is used to inform the cloud provider used in the vagrant cluster
yum install -y salt-api
# Set log level to a level higher than "info" to prevent the message about
# enabling the service (which is not an error) from being printed to stderr.
SYSTEMD_LOG_LEVEL=notice systemctl enable salt-api
systemctl start salt-api
fi
if ! which salt-minion >/dev/null 2>&1; then
# Install Salt minion
curl -sS -L --connect-timeout 20 --retry 6 --retry-delay 10 https://bootstrap.saltstack.com | sh -s
else
# Only run highstate when updating the config. In the first-run case, Salt is
# set up to run highstate as new minions join for the first time.
echo "Executing configuration"
salt '*' mine.update
salt --show-timeout --force-color '*' state.highstate
fi
| {
"content_hash": "a7d2b3cfb47accef9c4c3855f256e4e3",
"timestamp": "",
"source": "github",
"line_count": 253,
"max_line_length": 117,
"avg_line_length": 35.27272727272727,
"alnum_prop": 0.6848946660690274,
"repo_name": "kenmoore/kubernetes",
"id": "82e294fbf0b5ed9f235deb03eeb057becd4a36c6",
"size": "8924",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "cluster/vagrant/provision-master.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "60606"
},
{
"name": "Go",
"bytes": "9967409"
},
{
"name": "HTML",
"bytes": "51569"
},
{
"name": "Java",
"bytes": "3851"
},
{
"name": "JavaScript",
"bytes": "177353"
},
{
"name": "Makefile",
"bytes": "11664"
},
{
"name": "Nginx",
"bytes": "1013"
},
{
"name": "PHP",
"bytes": "736"
},
{
"name": "Python",
"bytes": "60519"
},
{
"name": "Ruby",
"bytes": "2778"
},
{
"name": "SaltStack",
"bytes": "23791"
},
{
"name": "Shell",
"bytes": "637826"
}
],
"symlink_target": ""
} |
{% load helplink %}
{% load editor_controls %}
<div class="form-group">
<label class="label-block">
<div class="{{form_label_class}} control-label">
{{label}}
{% if help_url %}{% helplink help_url %}{% endif %}
</div>
<div class="{{form_control_class}}">
<div class="checkbox">
{% boolean_input property disable=disable %}
</div>
</div>
</label>
</div>
| {
"content_hash": "ed145caff216a5dd3663dbcee4853fd1",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 63,
"avg_line_length": 30.466666666666665,
"alnum_prop": 0.49452954048140046,
"repo_name": "numbas/editor",
"id": "c9929862bd16212b5533092be6c4a6322a2eb29a",
"size": "457",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "editor/templates/editor-controls/booleanproperty.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "44056"
},
{
"name": "HTML",
"bytes": "548468"
},
{
"name": "JavaScript",
"bytes": "2344000"
},
{
"name": "Less",
"bytes": "205670"
},
{
"name": "Makefile",
"bytes": "10028"
},
{
"name": "Python",
"bytes": "551931"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="jquery.mobile-1.0a2.min.css" />
<script src="scripts/phonegap.js"></script>
<script src="scripts/jquery-1.4.4.min.js"></script>
<script src="scripts/Lawnchair.js"></script>
<script src="scripts/LawnchairAdaptorHelpers.js"></script>
<script src="scripts/DOMStorageAdaptor.js"></script>
<script src="scripts/parkit.js"></script>
<script src="scripts/jquery.mobile-1.0a2.min.js"></script>
</head>
<body>
<div data-role="page" data-theme="a" id="parkit">
<div data-role="header">
<a href="index.html" data-icon="arrow-l" rel="external">Back</a>
<h1>Park car</h1>
</div>
<div data-role="content" class="content" align="center">
<div id="result">
Please wait, storing your GPS pos...
</div>
<div id="success" style="display:none">
<p>Your car has been parked successfully!</p>
<p id="latitude"></p>
<p id="longitude"></p>
</div>
<div id="save" data-inline="true" style="display:none">
<a href="#" data-role="button">Save with name</a>
</div>
<div class="saving" style="display:none">
<input type="text" name="position" />
<div class="savingButton">
<div id="save"><a href="#">SAVE</a></div>
</div>
</div>
</div>
<div data-role="footer">
</div>
</div>
</body>
</html>
| {
"content_hash": "acf05c44e2912e6e9fefd541c211526a",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 69,
"avg_line_length": 28,
"alnum_prop": 0.5998542274052479,
"repo_name": "sub/yacf",
"id": "6f66734cce702631f15b6d5fdc452825d98367f5",
"size": "1372",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "parkit.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "253280"
}
],
"symlink_target": ""
} |
package ru.org.linux.topic;
import ru.org.linux.user.Userpic;
import javax.annotation.Nullable;
public class TopicMenu {
private final boolean topicEditable;
private final boolean tagsEditable;
private final boolean resolvable;
private final boolean commentsAllowed;
private final boolean deletable;
@Nullable
private final Userpic userpic;
public TopicMenu(
boolean topicEditable,
boolean tagsEditable,
boolean resolvable,
boolean commentsAllowed,
boolean deletable,
@Nullable Userpic userpic) {
this.topicEditable = topicEditable;
this.tagsEditable = tagsEditable;
this.resolvable = resolvable;
this.commentsAllowed = commentsAllowed;
this.deletable = deletable;
this.userpic = userpic;
}
public boolean isEditable() {
return tagsEditable || topicEditable;
}
public boolean isTopicEditable() {
return topicEditable;
}
public boolean isTagsEditable() {
return tagsEditable;
}
public boolean isResolvable() {
return resolvable;
}
public boolean isCommentsAllowed() {
return commentsAllowed;
}
public boolean isDeletable() {
return deletable;
}
@Nullable
public Userpic getUserpic() {
return userpic;
}
}
| {
"content_hash": "d44842e1aa5c9c9eb72df4cddefb190e",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 43,
"avg_line_length": 20.3015873015873,
"alnum_prop": 0.6989835809225958,
"repo_name": "hizel/lorsource",
"id": "8b67edbff4e13c63590d3725b5e824dc12da480b",
"size": "1903",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/main/java/ru/org/linux/topic/TopicMenu.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "91521"
},
{
"name": "HTML",
"bytes": "40739"
},
{
"name": "Java",
"bytes": "1486067"
},
{
"name": "JavaScript",
"bytes": "46905"
},
{
"name": "Scala",
"bytes": "330249"
},
{
"name": "Shell",
"bytes": "1947"
}
],
"symlink_target": ""
} |
class ParametrisedEvent
include AASM
aasm do
state :sleeping, :initial => true
state :showering
state :working
state :dating
state :prettying_up
event :wakeup do
transitions :from => :sleeping, :to => [:showering, :working]
end
event :dress do
transitions :from => :sleeping, :to => :working, :after => :wear_clothes
transitions :from => :showering, :to => [:working, :dating], :after => Proc.new { |*args| wear_clothes(*args) }
transitions :from => :showering, :to => :prettying_up, :after => [:condition_hair, :fix_hair]
end
end
def wear_clothes(shirt_color, trouser_type=nil)
end
def condition_hair
end
def fix_hair
end
end
| {
"content_hash": "ca8486c0c594862446f622df50563a65",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 117,
"avg_line_length": 24.482758620689655,
"alnum_prop": 0.6295774647887324,
"repo_name": "allspiritseve/aasm",
"id": "23e013e9c5acdb1243fd8b70f7375556f6d3436e",
"size": "710",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "spec/models/parametrised_event.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "255587"
}
],
"symlink_target": ""
} |
/**
* Federated User
*/
@interface SecurityTokenServiceFederatedUser:NSObject
{
NSString *federatedUserId;
NSString *arn;
}
/**
* The string that identifies the federated user associated with the
* credentials, similar to the unique ID of an IAM user.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>2 - 96<br/>
* <b>Pattern: </b>[\w+=,.@\:-]*<br/>
*/
@property (nonatomic, retain) NSString *federatedUserId;
/**
* The ARN that specifies the federated user that is associated with the
* credentials. For more information about ARNs and how to use them in
* policies, see <a
* ttp://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html"
* target="_blank">Identifiers for IAM Entities</a> in <i>Using IAM</i>.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>20 - 2048<br/>
*/
@property (nonatomic, retain) NSString *arn;
/**
* Default constructor for a new FederatedUser object. Callers should use the
* property methods to initialize this object after creating it.
*/
-(id)init;
/**
* Constructs a new FederatedUser object.
* Callers should use properties to initialize any additional object members.
*
* @param theFederatedUserId The string that identifies the federated
* user associated with the credentials, similar to the unique ID of an
* IAM user.
* @param theArn The ARN that specifies the federated user that is
* associated with the credentials. For more information about ARNs and
* how to use them in policies, see <a
* ttp://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html"
* target="_blank">Identifiers for IAM Entities</a> in <i>Using IAM</i>.
*/
-(id)initWithFederatedUserId:(NSString *)theFederatedUserId andArn:(NSString *)theArn;
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*/
-(NSString *)description;
@end
| {
"content_hash": "ec8c41f09aeef35d207be0e807181242",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 86,
"avg_line_length": 26.65277777777778,
"alnum_prop": 0.7087024491922876,
"repo_name": "Maxwell2022/S3Upload",
"id": "e5c98343cbbb331b4b43c0e9a254b5e81a46435b",
"size": "2503",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "AWSSecurityTokenService.framework/Versions/A/Headers/SecurityTokenServiceFederatedUser.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "696"
},
{
"name": "Objective-C",
"bytes": "3010391"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, maximum-scale=1, initial-scale=1, user-scalable=no">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<title>Dingo</title>
<link rel="icon" href="http://localhost:9008/img/favicon.ico" type="image/x-icon">
<script src="http://localhost:9008/vendor/webcomponentsjs/webcomponents.min.js"></script>
<link rel="import" href="http://localhost:9008/dingo-coder.html">
<style>
body {
direction: ltr;
background-color: white;
color: white;
font-family: 'Arial';
font-size: 13px;
padding: 0px !important;
margin: 0px !important;
line-height: 1.5;
font-style: normal;
font-weight: normal;
height: 100%;
}
.wrap {
min-height: 100%;
height: 600px;
width:950px;
margin: 0 auto -60px;
max-width: 1100px;
}
</style>
</head>
<body>
<div style="height:20px;width:100%"></div>
<div class="wrap">
<dingo-coder layout="2" code="false" preview="false">
<textarea code="html" style="display: none">
<link href="http://cdn.bootcss.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<div class="example">
<button type="button" class="btn btn-default">Default</button>
<button type="button" class="btn btn-primary">Primary</button>
<button type="button" class="btn btn-success">Success</button>
<button type="button" class="btn btn-info">Info</button>
<button type="button" class="btn btn-warning">Warning</button>
<button type="button" class="btn btn-danger">Danger</button>
<button type="button" class="btn btn-link">Link</button>
</div>
</textarea>
<textarea code="css" style="display:none">
.example {
margin:auto;
margin-top:10px;
width:95%;
background-color: #fff;
border-color: #ddd;
border-width: 1px;
border-radius: 4px;
-webkit-box-shadow: none;
box-shadow: none;
position: relative;
padding: 45px 15px 45px 15px;
border-style: solid;
}
button{
margin-top:10px;}
</textarea>
<textarea code="js" style="display:none">
console.log(1111);
</textarea>
<textarea code="velocity" style="display:none">
The RHS can also be a simple arithmetic expression, such as:
Addition: #set( $value = $foo + 1 )
Subtraction: #set( $value = $bar - 1 )
Multiplication: #set( $value = $foo * $bar )
Division: #set( $value = $foo / $bar )
Remainder: #set( $value = $foo % $bar )
</textarea>
<textarea target="css">
#title {
color: red;
}
</textarea>
</dingo-coder>
</div>
<script type="text/javascript">
window.addEventListener("message", function(e){console.log(e)})
</script>
</body>
</html> | {
"content_hash": "9aab4bf4a97daf7e9e24073c1a557aff",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 107,
"avg_line_length": 37.95876288659794,
"alnum_prop": 0.5111352525801195,
"repo_name": "wh1100717/dingo-coder",
"id": "5eeded098c3f91d9af3dc48be731dc446c180063",
"size": "3682",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "view/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "72185"
},
{
"name": "CoffeeScript",
"bytes": "55289"
},
{
"name": "HTML",
"bytes": "35647"
},
{
"name": "JavaScript",
"bytes": "1861"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "ca9c3b29762c6d81bc985e625a7c438f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "19ee1581b5343377223f31fbdbc79036f6cd0c9b",
"size": "184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Vitales/Vitaceae/Cissus/Cissus lamarckiana/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import sys
try:
pyreadline_codepage=sys.stdout.encoding
except AttributeError: #This error occurs when pdb imports readline and doctest has replaced
#stdout with stdout collector
pyreadline_codepage="ascii" #assume ascii codepage
def ensure_unicode(text):
"""helper to ensure that text passed to WriteConsoleW is unicode"""
if isinstance(text, str):
return text.decode(pyreadline_codepage, "replace")
return text
def ensure_str(text):
"""Convert unicode to str using pyreadline_codepage"""
if isinstance(text, unicode):
return text.encode(pyreadline_codepage, "replace")
return text
| {
"content_hash": "958a00912cca2a40159f723b2cf16283",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 100,
"avg_line_length": 34.95,
"alnum_prop": 0.6666666666666666,
"repo_name": "chvrga/outdoor-explorer",
"id": "f33fa099c5dec12401b6f5ceb82eadbca9244350",
"size": "1101",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "java/play-1.4.4/python/Lib/site-packages/pyreadline/unicode_helper.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "4720"
},
{
"name": "C",
"bytes": "76128"
},
{
"name": "C++",
"bytes": "31284"
},
{
"name": "CSS",
"bytes": "107401"
},
{
"name": "HTML",
"bytes": "1754737"
},
{
"name": "Java",
"bytes": "2441299"
},
{
"name": "JavaScript",
"bytes": "1405163"
},
{
"name": "PLpgSQL",
"bytes": "1377"
},
{
"name": "Python",
"bytes": "8991412"
},
{
"name": "Ruby",
"bytes": "295601"
},
{
"name": "Shell",
"bytes": "7499"
},
{
"name": "XQuery",
"bytes": "544017"
},
{
"name": "XSLT",
"bytes": "1099"
}
],
"symlink_target": ""
} |
Cookbook
========
.. toctree::
:maxdepth: 1
complex-joins
table-prefix
| {
"content_hash": "62b15a9ced287c49453bc844e2fa394a",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 17,
"avg_line_length": 10.625,
"alnum_prop": 0.5529411764705883,
"repo_name": "shabbyrobe/amiss",
"id": "d84eb256e85161b8a0bebaa203efdd927c16845d",
"size": "85",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/cookbook/index.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "530195"
},
{
"name": "Shell",
"bytes": "2944"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>colour.models.dataset.srgb — Colour 0.3.0 documentation</title>
<link rel="stylesheet" href="../../../../_static/basic.css" type="text/css" />
<link rel="stylesheet" href="../../../../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="../../../../_static/bootswatch-3.1.0/colour/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="../../../../_static/bootstrap-sphinx.css" type="text/css" />
<link rel="stylesheet" href="../../../../_static/styles.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../../../../',
VERSION: '0.3.0',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="../../../../_static/jquery.js"></script>
<script type="text/javascript" src="../../../../_static/underscore.js"></script>
<script type="text/javascript" src="../../../../_static/doctools.js"></script>
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/javascript" src="../../../../_static/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="../../../../_static/js/jquery-fix.js"></script>
<script type="text/javascript" src="../../../../_static/bootstrap-3.1.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../../../../_static/bootstrap-sphinx.js"></script>
<link rel="top" title="Colour 0.3.0 documentation" href="../../../../index.html" />
<link rel="up" title="colour.models.dataset" href="../dataset.html" />
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">
</head>
<body>
<div id="navbar" class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<!-- .btn-navbar is used as the toggle for collapsed navbar content -->
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../../../../index.html"><img src="../../../../_static/Colour_Logo_Icon_001.png">
Colour 0.3</a>
<!--<span class="navbar-text navbar-version pull-left"><b>0.3</b></span>-->
</div>
<div class="collapse navbar-collapse nav-collapse">
<ul class="nav navbar-nav">
<li class="divider-vertical"></li>
<li><a href="https://www.colour-science.org">colour-science.org</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-life-ring"> Documentation</i><b class="caret"></b></a>
<ul class="dropdown-menu">
<li>
<a href="api.html" class="fa fa-life-ring"> API Reference</a>
</li>
<li>
<a href="http://nbviewer.ipython.org/github/colour-science/colour-ipython/blob/master/notebooks/colour.ipynb', True)" class="fa fa-book"> IPython Notebooks</a>
</li>
<li>
<a href="https://www.colour-science.org/features.php" class="fa fa-lightbulb-o"> Features</a>
</li>
<li>
<a href="https://www.colour-science.org/contributing.php"><span class="fa fa-gears"> Contributing</span></a>
</li>
</ul>
</li>
</ul>
<form class="navbar-form navbar-right" action="../../../../search.html" method="get">
<div class="form-group">
<input type="text" name="q" class="form-control" placeholder="Search" />
</div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Source code for colour.models.dataset.srgb</h1><div class="highlight"><pre>
<span class="c">#!/usr/bin/env python</span>
<span class="c"># -*- coding: utf-8 -*-</span>
<span class="sd">"""</span>
<span class="sd">sRGB Colourspace</span>
<span class="sd">================</span>
<span class="sd">Defines the *sRGB* colourspace:</span>
<span class="sd">- :attr:`sRGB_COLOURSPACE`.</span>
<span class="sd">See Also</span>
<span class="sd">--------</span>
<span class="sd">`RGB Colourspaces IPython Notebook</span>
<span class="sd"><http://nbviewer.ipython.org/github/colour-science/colour-ipython/blob/master/notebooks/models/rgb.ipynb>`_ # noqa</span>
<span class="sd">References</span>
<span class="sd">----------</span>
<span class="sd">.. [1] http://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.709-5-200204-I!!PDF-E.pdf # noqa</span>
<span class="sd"> (Last accessed 24 February 2014)</span>
<span class="sd">"""</span>
<span class="kn">from</span> <span class="nn">__future__</span> <span class="kn">import</span> <span class="n">division</span><span class="p">,</span> <span class="n">unicode_literals</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="kn">as</span> <span class="nn">np</span>
<span class="kn">from</span> <span class="nn">colour.colorimetry</span> <span class="kn">import</span> <span class="n">ILLUMINANTS</span>
<span class="kn">from</span> <span class="nn">colour.models</span> <span class="kn">import</span> <span class="n">RGB_Colourspace</span>
<span class="n">__author__</span> <span class="o">=</span> <span class="s">'Colour Developers'</span>
<span class="n">__copyright__</span> <span class="o">=</span> <span class="s">'Copyright (C) 2013 - 2014 - Colour Developers'</span>
<span class="n">__license__</span> <span class="o">=</span> <span class="s">'New BSD License - http://opensource.org/licenses/BSD-3-Clause'</span>
<span class="n">__maintainer__</span> <span class="o">=</span> <span class="s">'Colour Developers'</span>
<span class="n">__email__</span> <span class="o">=</span> <span class="s">'colour-science@googlegroups.com'</span>
<span class="n">__status__</span> <span class="o">=</span> <span class="s">'Production'</span>
<span class="n">__all__</span> <span class="o">=</span> <span class="p">[</span><span class="s">'sRGB_PRIMARIES'</span><span class="p">,</span>
<span class="s">'sRGB_WHITEPOINT'</span><span class="p">,</span>
<span class="s">'sRGB_TO_XYZ_MATRIX'</span><span class="p">,</span>
<span class="s">'XYZ_TO_sRGB_MATRIX'</span><span class="p">,</span>
<span class="s">'sRGB_TRANSFER_FUNCTION'</span><span class="p">,</span>
<span class="s">'sRGB_INVERSE_TRANSFER_FUNCTION'</span><span class="p">,</span>
<span class="s">'sRGB_COLOURSPACE'</span><span class="p">]</span>
<span class="n">sRGB_PRIMARIES</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">(</span>
<span class="p">[[</span><span class="mf">0.6400</span><span class="p">,</span> <span class="mf">0.3300</span><span class="p">],</span>
<span class="p">[</span><span class="mf">0.3000</span><span class="p">,</span> <span class="mf">0.6000</span><span class="p">],</span>
<span class="p">[</span><span class="mf">0.1500</span><span class="p">,</span> <span class="mf">0.0600</span><span class="p">]])</span>
<span class="sd">"""</span>
<span class="sd">*sRGB* colourspace primaries.</span>
<span class="sd">sRGB_PRIMARIES : ndarray, (3, 2)</span>
<span class="sd">"""</span>
<span class="n">sRGB_WHITEPOINT</span> <span class="o">=</span> <span class="n">ILLUMINANTS</span><span class="o">.</span><span class="n">get</span><span class="p">(</span>
<span class="s">'CIE 1931 2 Degree Standard Observer'</span><span class="p">)</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'D65'</span><span class="p">)</span>
<span class="sd">"""</span>
<span class="sd">*sRGB* colourspace whitepoint.</span>
<span class="sd">sRGB_WHITEPOINT : tuple</span>
<span class="sd">"""</span>
<span class="n">sRGB_TO_XYZ_MATRIX</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">(</span>
<span class="p">[[</span><span class="mf">0.41238656</span><span class="p">,</span> <span class="mf">0.35759149</span><span class="p">,</span> <span class="mf">0.18045049</span><span class="p">],</span>
<span class="p">[</span><span class="mf">0.21263682</span><span class="p">,</span> <span class="mf">0.71518298</span><span class="p">,</span> <span class="mf">0.0721802</span><span class="p">],</span>
<span class="p">[</span><span class="mf">0.01933062</span><span class="p">,</span> <span class="mf">0.11919716</span><span class="p">,</span> <span class="mf">0.95037259</span><span class="p">]])</span>
<span class="sd">"""</span>
<span class="sd">*sRGB* colourspace to *CIE XYZ* colourspace matrix.</span>
<span class="sd">sRGB_TO_XYZ_MATRIX : array_like, (3, 3)</span>
<span class="sd">"""</span>
<span class="n">XYZ_TO_sRGB_MATRIX</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">linalg</span><span class="o">.</span><span class="n">inv</span><span class="p">(</span><span class="n">sRGB_TO_XYZ_MATRIX</span><span class="p">)</span>
<span class="sd">"""</span>
<span class="sd">*CIE XYZ* colourspace to *sRGB* colourspace matrix.</span>
<span class="sd">XYZ_TO_sRGB_MATRIX : array_like, (3, 3)</span>
<span class="sd">"""</span>
<span class="n">sRGB_TRANSFER_FUNCTION</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="p">(</span>
<span class="n">x</span> <span class="o">*</span> <span class="mf">12.92</span> <span class="k">if</span> <span class="n">x</span> <span class="o"><=</span> <span class="mf">0.0031308</span> <span class="k">else</span> <span class="mf">1.055</span> <span class="o">*</span> <span class="p">(</span><span class="n">x</span> <span class="o">**</span> <span class="p">(</span><span class="mi">1</span> <span class="o">/</span> <span class="mf">2.4</span><span class="p">))</span> <span class="o">-</span> <span class="mf">0.055</span><span class="p">)</span>
<span class="sd">"""</span>
<span class="sd">Transfer function from linear to *sRGB* colourspace.</span>
<span class="sd">sRGB_TRANSFER_FUNCTION : object</span>
<span class="sd">"""</span>
<span class="n">sRGB_INVERSE_TRANSFER_FUNCTION</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="p">(</span>
<span class="n">x</span> <span class="o">/</span> <span class="mf">12.92</span> <span class="k">if</span> <span class="n">x</span> <span class="o"><=</span> <span class="mf">0.0031308</span> <span class="k">else</span> <span class="p">((</span><span class="n">x</span> <span class="o">+</span> <span class="mf">0.055</span><span class="p">)</span> <span class="o">/</span> <span class="mf">1.055</span><span class="p">)</span> <span class="o">**</span> <span class="mf">2.4</span><span class="p">)</span>
<span class="sd">"""</span>
<span class="sd">Inverse transfer function from *sRGB* colourspace to linear.</span>
<span class="sd">sRGB_INVERSE_TRANSFER_FUNCTION : object</span>
<span class="sd">"""</span>
<span class="n">sRGB_COLOURSPACE</span> <span class="o">=</span> <span class="n">RGB_Colourspace</span><span class="p">(</span>
<span class="s">'sRGB'</span><span class="p">,</span>
<span class="n">sRGB_PRIMARIES</span><span class="p">,</span>
<span class="n">sRGB_WHITEPOINT</span><span class="p">,</span>
<span class="n">sRGB_TO_XYZ_MATRIX</span><span class="p">,</span>
<span class="n">XYZ_TO_sRGB_MATRIX</span><span class="p">,</span>
<span class="n">sRGB_TRANSFER_FUNCTION</span><span class="p">,</span>
<span class="n">sRGB_INVERSE_TRANSFER_FUNCTION</span><span class="p">)</span>
<span class="sd">"""</span>
<span class="sd">*sRGB* colourspace.</span>
<span class="sd">sRGB_COLOURSPACE : RGB_Colourspace</span>
<span class="sd">"""</span>
</pre></div>
</div>
</div>
</div>
<footer class="footer">
<div class="container">
<p class="pull-right">
<a href="#">Back to top</a>
</p>
<p>
© Copyright 2013 - 2014, Colour Developers.<br/>
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2.2.<br/>
</p>
</div>
</footer>
</body>
</html> | {
"content_hash": "b839771a0e759b82054eb7bd6f5e9895",
"timestamp": "",
"source": "github",
"line_count": 236,
"max_line_length": 562,
"avg_line_length": 58.105932203389834,
"alnum_prop": 0.5956391745059433,
"repo_name": "colour-science/colour-science.org",
"id": "5c78348d5ce60600ff61af41e5ba7405649e6aae",
"size": "13713",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "files/api/0.3.0/html/_modules/colour/models/dataset/srgb.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "326070"
},
{
"name": "HTML",
"bytes": "290246316"
},
{
"name": "JavaScript",
"bytes": "718896"
},
{
"name": "Jupyter Notebook",
"bytes": "103462848"
},
{
"name": "Less",
"bytes": "400806"
},
{
"name": "Python",
"bytes": "68039"
},
{
"name": "SCSS",
"bytes": "182749"
},
{
"name": "XSLT",
"bytes": "3619"
}
],
"symlink_target": ""
} |
import { Contacts } from '../../api/contacts/contacts.js';
import { Meteor } from 'meteor/meteor';
Meteor.publish('Contacts', function publishContactsData() {
return Contacts.find();
}); | {
"content_hash": "8515fba8c9b02bbfa23a19571b180228",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 59,
"avg_line_length": 31.5,
"alnum_prop": 0.7037037037037037,
"repo_name": "gviloria/digits",
"id": "35ada806ececfe0f31bee86713094a2b696ab165",
"size": "189",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/imports/startup/server/publications.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "4195"
},
{
"name": "HTML",
"bytes": "7089"
},
{
"name": "JavaScript",
"bytes": "763792"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "8eb109a64a4d424dc669e569658bf42a",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "2631fa21852fd740933f8cc1ef7880fd8b89b84c",
"size": "195",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Restionaceae/Thamnochortus/Thamnochortus nutans/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace StingerSoft\DoctrineEntitySearchBundle\Entity;
use StingerSoft\DoctrineEntitySearchBundle\Model\Document as BaseDocument;
class Document extends BaseDocument {
protected function newFieldInstance(): \StingerSoft\DoctrineEntitySearchBundle\Model\Field {
return new Field();
}
} | {
"content_hash": "cbeefb4b8526def1223d26414073dd35",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 93,
"avg_line_length": 21.8,
"alnum_prop": 0.8165137614678899,
"repo_name": "Stinger-Soft/DoctrineEntitySearchBundle",
"id": "cb05e2ebd35cd2b49853ab95fdbc0a859279f280",
"size": "631",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Entity/Document.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "33163"
}
],
"symlink_target": ""
} |
@protocol CategorySearchDelegate <NSObject>
-(void)search:(NSPredicate *)forCategory;
@end
| {
"content_hash": "f27ed857d363aa5189e5c170fb2e6cb1",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 43,
"avg_line_length": 30.333333333333332,
"alnum_prop": 0.8021978021978022,
"repo_name": "liamdkane/wineClubChallenge",
"id": "e74082ee5bca0492f3d6623db1bb495fbeacb5c8",
"size": "271",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WineClubChallenge/WineClubChallenge/CategorySearchDelegate.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "559394"
},
{
"name": "Ruby",
"bytes": "403"
},
{
"name": "Shell",
"bytes": "17196"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "f9fec549ab384584d9678ae7d5d80ac9",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "5a17c32355010e016f80a16970300af7a325dd87",
"size": "174",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Celastrales/Celastraceae/Wimmeria/Wimmeria lanceolata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?><resources>
<string name="activity_resolver_use_always">"Sempre"</string>
<string name="activity_resolver_use_once">"Só uma vez"</string>
<string name="candidates_style">"candidatos"</string>
<string name="capital_off">"DESL"</string>
<string name="capital_on">"LIG"</string>
<string name="chooseActivity">"Escolher uma ação"</string>
<string name="date_picker_decrement_day_button">"Diminuir dia"</string>
<string name="date_picker_decrement_month_button">"Diminuir mês"</string>
<string name="date_picker_decrement_year_button">"Diminuir ano"</string>
<string name="date_picker_dialog_title">"Definir data"</string>
<string name="date_picker_increment_day_button">"Aumentar dia"</string>
<string name="date_picker_increment_month_button">"Aumentar mês"</string>
<string name="date_picker_increment_year_button">"Aumentar ano"</string>
<string name="date_time_done">"Concluído"</string>
<string name="date_time_set">"Definir"</string>
<string name="loading">"Carregando…"</string>
<string name="noApplications">"Nenhum aplicativo pode realizar esta ação."</string>
<string name="number_picker_decrement_button">"Diminuir"</string>
<string name="number_picker_increment_button">"Aumentar"</string>
<string name="number_picker_increment_scroll_action">"Deslize para cima para aumentar e para baixo para diminuir."</string>
<string name="number_picker_increment_scroll_mode">"%s toque e mantenha pressionado."</string>
<string name="ringtone_default">"Toque padrão"</string>
<string name="ringtone_picker_title">"Toques"</string>
<string name="ringtone_silent">"Silencioso"</string>
<string name="time_picker_decrement_hour_button">"Diminuir hora"</string>
<string name="time_picker_decrement_minute_button">"Diminuir minuto"</string>
<string name="time_picker_decrement_set_am_button">"Configurar valor AM"</string>
<string name="time_picker_dialog_title">"Definir hora"</string>
<string name="time_picker_increment_hour_button">"Aumentar hora"</string>
<string name="time_picker_increment_minute_button">"Aumentar minuto"</string>
<string name="time_picker_increment_set_pm_button">"Configurar valor PM"</string>
<string name="whichApplication">"Complete a ação usando"</string>
</resources>
| {
"content_hash": "095af770818e69626b88caa076fcf070",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 127,
"avg_line_length": 69.3529411764706,
"alnum_prop": 0.7171331636980492,
"repo_name": "mercadolibre/HoloEverywhere",
"id": "4386dc96afd3a8b397fdc67aadffcd7135190338",
"size": "2371",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "library/res/values-pt/strings.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groovy",
"bytes": "2007"
},
{
"name": "Java",
"bytes": "1558776"
},
{
"name": "Shell",
"bytes": "617"
}
],
"symlink_target": ""
} |
layout: post
date: '2016-06-03'
title: "Jasmine Bridal M170067 Sleeveless Knee-Length Sheath/Column"
category: Jasmine
tags: [Jasmine ,Jasmine,Sheath/Column,Bateau,Knee-Length,Sleeveless]
---
### Jasmine Bridal M170067
Just **$239.99**
### Sleeveless Knee-Length Sheath/Column
<table><tr><td>BRANDS</td><td>Jasmine</td></tr><tr><td>Silhouette</td><td>Sheath/Column</td></tr><tr><td>Neckline</td><td>Bateau</td></tr><tr><td>Hemline/Train</td><td>Knee-Length</td></tr><tr><td>Sleeve</td><td>Sleeveless</td></tr></table>
<a href="https://www.readybrides.com/en/jasmine-/19547-jasmine-bridal-m170067.html"><img src="//static.msromantic.com/44384/jasmine-bridal-m170067.jpg" alt="Jasmine Bridal M170067" style="width:100%;" /></a>
<!-- break --><a href="https://www.readybrides.com/en/jasmine-/19547-jasmine-bridal-m170067.html"><img src="//static.msromantic.com/44383/jasmine-bridal-m170067.jpg" alt="Jasmine Bridal M170067" style="width:100%;" /></a>
Buy it: [https://www.readybrides.com/en/jasmine-/19547-jasmine-bridal-m170067.html](https://www.readybrides.com/en/jasmine-/19547-jasmine-bridal-m170067.html)
| {
"content_hash": "7324f42009d32f9c370f763736aa5665",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 240,
"avg_line_length": 79.42857142857143,
"alnum_prop": 0.7266187050359713,
"repo_name": "variousweddingdress/variousweddingdress.github.io",
"id": "43dc4096bbc51ff1e239dee36512c21eab81e544",
"size": "1116",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2016-06-03-Jasmine-Bridal-M170067-Sleeveless-KneeLength-SheathColumn.md",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "83876"
},
{
"name": "HTML",
"bytes": "14755"
},
{
"name": "Ruby",
"bytes": "897"
}
],
"symlink_target": ""
} |
'''
Copyright 2016, EMC, Inc.
Author(s):
George Paulos
'''
import fit_path # NOQA: unused import
import os
import sys
import subprocess
import fit_common
# Select test group here using @attr
from nose.plugins.attrib import attr
@attr(all=True, regression=True, smoke=True)
class redfish10_api_schemas(fit_common.unittest.TestCase):
def test_redfish_v1_schemas(self):
api_data = fit_common.rackhdapi('/redfish/v1/Schemas')
self.assertEqual(api_data['status'], 200, "Was expecting code 200. Got " + str(api_data['status']))
# iterate through links
for item in api_data['json']['Members']:
self.assertEqual(fit_common.rackhdapi(item['@odata.id'])['status'], 200, "Bad or missing link: " + item['@odata.id'])
def test_redfish_v1_schemastore_en(self):
api_data = fit_common.rackhdapi('/redfish/v1/Schemas')
self.assertEqual(api_data['status'], 200, "Was expecting code 200. Got " + str(api_data['status']))
for item in api_data['json']['Members']:
schema_data = fit_common.rackhdapi('/redfish/v1/SchemaStore/en/' + item['@odata.id'].replace('/redfish/v1/Schemas/', ''))
self.assertEqual(schema_data['status'], 200, "Was expecting code 200. Got " + str(schema_data['status']))
if __name__ == '__main__':
fit_common.unittest.main()
| {
"content_hash": "7e356ed80a96ad8b74672ea424d8bed3",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 133,
"avg_line_length": 38.2,
"alnum_prop": 0.6581899775617053,
"repo_name": "srinia6/RackHD",
"id": "e7a5d35027b92f8db95233e5cc363cb44660581f",
"size": "1337",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "test/tests/redfish10/test_redfish10_api_schemas.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "696"
},
{
"name": "Python",
"bytes": "1530855"
},
{
"name": "Ruby",
"bytes": "10910"
},
{
"name": "Shell",
"bytes": "71655"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "a9aa1214f0e92f566ee659a4c37915a7",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "f80f6afe71e2d6e5d1a36a3c7f5c03bbeb039bcf",
"size": "182",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Acanthaceae/Staurogyne/Staurogyne brachystachya/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package support
import (
"fmt"
"io"
"strings"
"sync"
"time"
"github.com/golang/glog"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/tools/cache"
kapi "k8s.io/kubernetes/pkg/api"
kcoreclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion"
"github.com/openshift/origin/pkg/client"
deployapi "github.com/openshift/origin/pkg/deploy/apis/apps"
strategyutil "github.com/openshift/origin/pkg/deploy/strategy/util"
deployutil "github.com/openshift/origin/pkg/deploy/util"
imageapi "github.com/openshift/origin/pkg/image/apis/image"
"github.com/openshift/origin/pkg/util"
namer "github.com/openshift/origin/pkg/util/namer"
)
// hookContainerName is the name used for the container that runs inside hook pods.
const hookContainerName = "lifecycle"
// HookExecutor knows how to execute a deployment lifecycle hook.
type HookExecutor interface {
Execute(hook *deployapi.LifecycleHook, rc *kapi.ReplicationController, suffix, label string) error
}
// hookExecutor implements the HookExecutor interface.
var _ HookExecutor = &hookExecutor{}
// hookExecutor executes a deployment lifecycle hook.
type hookExecutor struct {
// pods provides client to pods
pods kcoreclient.PodsGetter
// tags allows setting image stream tags
tags client.ImageStreamTagsNamespacer
// out is where hook pod logs should be written to.
out io.Writer
// decoder is used for encoding/decoding.
decoder runtime.Decoder
// recorder is used to emit events from hooks
events kcoreclient.EventsGetter
// getPodLogs knows how to get logs from a pod and is used for testing
getPodLogs func(*kapi.Pod) (io.ReadCloser, error)
}
// NewHookExecutor makes a HookExecutor from a client.
func NewHookExecutor(pods kcoreclient.PodsGetter, tags client.ImageStreamTagsNamespacer, events kcoreclient.EventsGetter, out io.Writer, decoder runtime.Decoder) HookExecutor {
executor := &hookExecutor{
tags: tags,
pods: pods,
events: events,
out: out,
decoder: decoder,
}
executor.getPodLogs = func(pod *kapi.Pod) (io.ReadCloser, error) {
opts := &kapi.PodLogOptions{
Container: hookContainerName,
Follow: true,
Timestamps: false,
}
return executor.pods.Pods(pod.Namespace).GetLogs(pod.Name, opts).Stream()
}
return executor
}
// Execute executes hook in the context of deployment. The suffix is used to
// distinguish the kind of hook (e.g. pre, post).
func (e *hookExecutor) Execute(hook *deployapi.LifecycleHook, rc *kapi.ReplicationController, suffix, label string) error {
var err error
switch {
case len(hook.TagImages) > 0:
tagEventMessages := []string{}
for _, t := range hook.TagImages {
image, ok := findContainerImage(rc, t.ContainerName)
if ok {
tagEventMessages = append(tagEventMessages, fmt.Sprintf("image %q as %q", image, t.To.Name))
}
}
strategyutil.RecordConfigEvent(e.events, rc, e.decoder, kapi.EventTypeNormal, "Started",
fmt.Sprintf("Running %s-hook (TagImages) %s for rc %s/%s", label, strings.Join(tagEventMessages, ","), rc.Namespace, rc.Name))
err = e.tagImages(hook, rc, suffix, label)
case hook.ExecNewPod != nil:
strategyutil.RecordConfigEvent(e.events, rc, e.decoder, kapi.EventTypeNormal, "Started",
fmt.Sprintf("Running %s-hook (%q) for rc %s/%s", label, strings.Join(hook.ExecNewPod.Command, " "), rc.Namespace, rc.Name))
err = e.executeExecNewPod(hook, rc, suffix, label)
}
if err == nil {
strategyutil.RecordConfigEvent(e.events, rc, e.decoder, kapi.EventTypeNormal, "Completed",
fmt.Sprintf("The %s-hook for rc %s/%s completed successfully", label, rc.Namespace, rc.Name))
return nil
}
// Retry failures are treated the same as Abort.
switch hook.FailurePolicy {
case deployapi.LifecycleHookFailurePolicyAbort, deployapi.LifecycleHookFailurePolicyRetry:
strategyutil.RecordConfigEvent(e.events, rc, e.decoder, kapi.EventTypeWarning, "Failed",
fmt.Sprintf("The %s-hook failed: %v, aborting rollout of %s/%s", label, err, rc.Namespace, rc.Name))
return fmt.Errorf("the %s hook failed: %v, aborting rollout of %s/%s", label, err, rc.Namespace, rc.Name)
case deployapi.LifecycleHookFailurePolicyIgnore:
strategyutil.RecordConfigEvent(e.events, rc, e.decoder, kapi.EventTypeWarning, "Failed",
fmt.Sprintf("The %s-hook failed: %v (ignore), rollout of %s/%s will continue", label, err, rc.Namespace, rc.Name))
return nil
default:
return err
}
}
// findContainerImage returns the image with the given container name from a replication controller.
func findContainerImage(rc *kapi.ReplicationController, containerName string) (string, bool) {
if rc.Spec.Template == nil {
return "", false
}
for _, container := range rc.Spec.Template.Spec.Containers {
if container.Name == containerName {
return container.Image, true
}
}
return "", false
}
// tagImages tags images as part of the lifecycle of a rc. It uses an ImageStreamTag client
// which will provision an ImageStream if it doesn't already exist.
func (e *hookExecutor) tagImages(hook *deployapi.LifecycleHook, rc *kapi.ReplicationController, suffix, label string) error {
var errs []error
for _, action := range hook.TagImages {
value, ok := findContainerImage(rc, action.ContainerName)
if !ok {
errs = append(errs, fmt.Errorf("unable to find image for container %q, container could not be found", action.ContainerName))
continue
}
namespace := action.To.Namespace
if len(namespace) == 0 {
namespace = rc.Namespace
}
if _, err := e.tags.ImageStreamTags(namespace).Update(&imageapi.ImageStreamTag{
ObjectMeta: metav1.ObjectMeta{
Name: action.To.Name,
Namespace: namespace,
},
Tag: &imageapi.TagReference{
From: &kapi.ObjectReference{
Kind: "DockerImage",
Name: value,
},
},
}); err != nil {
errs = append(errs, err)
continue
}
fmt.Fprintf(e.out, "--> %s: Tagged %q into %s/%s\n", label, value, action.To.Namespace, action.To.Name)
}
return utilerrors.NewAggregate(errs)
}
// executeExecNewPod executes a ExecNewPod hook by creating a new pod based on
// the hook parameters and replication controller. The pod is then synchronously
// watched until the pod completes, and if the pod failed, an error is returned.
//
// The hook pod inherits the following from the container the hook refers to:
//
// * Environment (hook keys take precedence)
// * Working directory
// * Resources
func (e *hookExecutor) executeExecNewPod(hook *deployapi.LifecycleHook, rc *kapi.ReplicationController, suffix, label string) error {
config, err := deployutil.DecodeDeploymentConfig(rc, e.decoder)
if err != nil {
return err
}
deployerPod, err := e.pods.Pods(rc.Namespace).Get(deployutil.DeployerPodNameForDeployment(rc.Name), metav1.GetOptions{})
if err != nil {
return err
}
// Build a pod spec from the hook config and replication controller.
podSpec, err := makeHookPod(hook, rc, deployerPod, &config.Spec.Strategy, suffix)
if err != nil {
return err
}
// Track whether the pod has already run to completion and avoid showing logs
// or the Success message twice.
completed, created := false, false
// Try to create the pod.
pod, err := e.pods.Pods(rc.Namespace).Create(podSpec)
if err != nil {
if !kerrors.IsAlreadyExists(err) {
return fmt.Errorf("couldn't create lifecycle pod for %s: %v", rc.Name, err)
}
completed = true
pod = podSpec
pod.Namespace = rc.Namespace
} else {
created = true
fmt.Fprintf(e.out, "--> %s: Running hook pod ...\n", label)
}
stopChannel := make(chan struct{})
defer close(stopChannel)
nextPod := newPodWatch(e.pods.Pods(pod.Namespace), pod.Namespace, pod.Name, pod.ResourceVersion, stopChannel)
// Wait for the hook pod to reach a terminal phase. Start reading logs as
// soon as the pod enters a usable phase.
var updatedPod *kapi.Pod
wg := &sync.WaitGroup{}
wg.Add(1)
restarts := int32(0)
alreadyRead := false
waitLoop:
for {
updatedPod = nextPod()
switch updatedPod.Status.Phase {
case kapi.PodRunning:
completed = false
// We should read only the first time or in any container restart when we want to retry.
canRetry, restartCount := canRetryReading(updatedPod, restarts)
if alreadyRead && !canRetry {
break
}
// The hook container has restarted; we need to notify that we are retrying in the logs.
// TODO: Maybe log the container id
if restarts != restartCount {
wg.Add(1)
restarts = restartCount
fmt.Fprintf(e.out, "--> %s: Retrying hook pod (retry #%d)\n", label, restartCount)
}
alreadyRead = true
go e.readPodLogs(pod, wg)
case kapi.PodSucceeded, kapi.PodFailed:
if completed {
if updatedPod.Status.Phase == kapi.PodSucceeded {
fmt.Fprintf(e.out, "--> %s: Hook pod already succeeded\n", label)
}
wg.Done()
break waitLoop
}
if !created {
fmt.Fprintf(e.out, "--> %s: Hook pod is already running ...\n", label)
}
if !alreadyRead {
go e.readPodLogs(pod, wg)
}
break waitLoop
default:
completed = false
}
}
// The pod is finished, wait for all logs to be consumed before returning.
wg.Wait()
if updatedPod.Status.Phase == kapi.PodFailed {
fmt.Fprintf(e.out, "--> %s: Failed\n", label)
return fmt.Errorf(updatedPod.Status.Message)
}
// Only show this message if we created the pod ourselves, or we saw
// the pod in a running or pending state.
if !completed {
fmt.Fprintf(e.out, "--> %s: Success\n", label)
}
return nil
}
// readPodLogs streams logs from pod to out. It signals wg when
// done.
func (e *hookExecutor) readPodLogs(pod *kapi.Pod, wg *sync.WaitGroup) {
defer wg.Done()
logStream, err := e.getPodLogs(pod)
if err != nil || logStream == nil {
fmt.Fprintf(e.out, "warning: Unable to retrieve hook logs from %s: %v\n", pod.Name, err)
return
}
// Read logs.
defer logStream.Close()
if _, err := io.Copy(e.out, logStream); err != nil {
fmt.Fprintf(e.out, "\nwarning: Unable to read all logs from %s, continuing: %v\n", pod.Name, err)
}
}
// makeHookPod makes a pod spec from a hook and replication controller.
func makeHookPod(hook *deployapi.LifecycleHook, rc *kapi.ReplicationController, deployerPod *kapi.Pod, strategy *deployapi.DeploymentStrategy, suffix string) (*kapi.Pod, error) {
exec := hook.ExecNewPod
var baseContainer *kapi.Container
for _, container := range rc.Spec.Template.Spec.Containers {
if container.Name == exec.ContainerName {
baseContainer = &container
break
}
}
if baseContainer == nil {
return nil, fmt.Errorf("no container named '%s' found in rc template", exec.ContainerName)
}
// Build a merged environment; hook environment takes precedence over base
// container environment
envMap := map[string]kapi.EnvVar{}
mergedEnv := []kapi.EnvVar{}
for _, env := range baseContainer.Env {
envMap[env.Name] = env
}
for _, env := range exec.Env {
envMap[env.Name] = env
}
for k, v := range envMap {
mergedEnv = append(mergedEnv, kapi.EnvVar{Name: k, Value: v.Value, ValueFrom: v.ValueFrom})
}
mergedEnv = append(mergedEnv, kapi.EnvVar{Name: "OPENSHIFT_DEPLOYMENT_NAME", Value: rc.Name})
mergedEnv = append(mergedEnv, kapi.EnvVar{Name: "OPENSHIFT_DEPLOYMENT_NAMESPACE", Value: rc.Namespace})
// Inherit resources from the base container
resources := kapi.ResourceRequirements{}
if err := kapi.Scheme.Convert(&baseContainer.Resources, &resources, nil); err != nil {
return nil, fmt.Errorf("couldn't clone ResourceRequirements: %v", err)
}
// Assigning to a variable since its address is required
defaultActiveDeadline := deployapi.MaxDeploymentDurationSeconds
if strategy.ActiveDeadlineSeconds != nil {
defaultActiveDeadline = *(strategy.ActiveDeadlineSeconds)
}
maxDeploymentDurationSeconds := defaultActiveDeadline - int64(time.Since(deployerPod.Status.StartTime.Time).Seconds())
// Let the kubelet manage retries if requested
restartPolicy := kapi.RestartPolicyNever
if hook.FailurePolicy == deployapi.LifecycleHookFailurePolicyRetry {
restartPolicy = kapi.RestartPolicyOnFailure
}
// Transfer any requested volumes to the hook pod.
volumes := []kapi.Volume{}
volumeNames := sets.NewString()
for _, volume := range rc.Spec.Template.Spec.Volumes {
for _, name := range exec.Volumes {
if volume.Name == name {
volumes = append(volumes, volume)
volumeNames.Insert(volume.Name)
}
}
}
// Transfer any volume mounts associated with transferred volumes.
volumeMounts := []kapi.VolumeMount{}
for _, mount := range baseContainer.VolumeMounts {
if volumeNames.Has(mount.Name) {
volumeMounts = append(volumeMounts, kapi.VolumeMount{
Name: mount.Name,
ReadOnly: mount.ReadOnly,
MountPath: mount.MountPath,
})
}
}
// Transfer image pull secrets from the pod spec.
imagePullSecrets := []kapi.LocalObjectReference{}
for _, pullSecret := range rc.Spec.Template.Spec.ImagePullSecrets {
imagePullSecrets = append(imagePullSecrets, kapi.LocalObjectReference{Name: pullSecret.Name})
}
gracePeriod := int64(10)
var podSecurityContextCopy *kapi.PodSecurityContext
if ctx, err := kapi.Scheme.DeepCopy(rc.Spec.Template.Spec.SecurityContext); err != nil {
return nil, fmt.Errorf("unable to copy pod securityContext: %v", err)
} else {
podSecurityContextCopy = ctx.(*kapi.PodSecurityContext)
}
var securityContextCopy *kapi.SecurityContext
if ctx, err := kapi.Scheme.DeepCopy(baseContainer.SecurityContext); err != nil {
return nil, fmt.Errorf("unable to copy securityContext: %v", err)
} else {
securityContextCopy = ctx.(*kapi.SecurityContext)
}
pod := &kapi.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: namer.GetPodName(rc.Name, suffix),
Annotations: map[string]string{
deployapi.DeploymentAnnotation: rc.Name,
},
Labels: map[string]string{
deployapi.DeploymentPodTypeLabel: suffix,
deployapi.DeployerPodForDeploymentLabel: rc.Name,
},
},
Spec: kapi.PodSpec{
Containers: []kapi.Container{
{
Name: hookContainerName,
Image: baseContainer.Image,
ImagePullPolicy: baseContainer.ImagePullPolicy,
Command: exec.Command,
WorkingDir: baseContainer.WorkingDir,
Env: mergedEnv,
Resources: resources,
VolumeMounts: volumeMounts,
SecurityContext: securityContextCopy,
},
},
SecurityContext: podSecurityContextCopy,
Volumes: volumes,
ActiveDeadlineSeconds: &maxDeploymentDurationSeconds,
// Setting the node selector on the hook pod so that it is created
// on the same set of nodes as the rc pods.
NodeSelector: rc.Spec.Template.Spec.NodeSelector,
RestartPolicy: restartPolicy,
ImagePullSecrets: imagePullSecrets,
TerminationGracePeriodSeconds: &gracePeriod,
},
}
util.MergeInto(pod.Labels, strategy.Labels, 0)
util.MergeInto(pod.Annotations, strategy.Annotations, 0)
return pod, nil
}
// canRetryReading returns whether the deployment strategy can retry reading logs
// from the given (hook) pod and the number of restarts that pod has.
func canRetryReading(pod *kapi.Pod, restarts int32) (bool, int32) {
if len(pod.Status.ContainerStatuses) == 0 {
return false, int32(0)
}
restartCount := pod.Status.ContainerStatuses[0].RestartCount
return pod.Spec.RestartPolicy == kapi.RestartPolicyOnFailure && restartCount > restarts, restartCount
}
// newPodWatch creates a pod watching function which is backed by a
// FIFO/reflector pair. This avoids managing watches directly.
// A stop channel to close the watch's reflector is also returned.
// It is the caller's responsibility to defer closing the stop channel to prevent leaking resources.
func newPodWatch(client kcoreclient.PodInterface, namespace, name, resourceVersion string, stopChannel chan struct{}) func() *kapi.Pod {
fieldSelector := fields.OneTermEqualSelector("metadata.name", name)
podLW := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
options.FieldSelector = fieldSelector.String()
return client.List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.FieldSelector = fieldSelector.String()
return client.Watch(options)
},
}
queue := cache.NewResyncableFIFO(cache.MetaNamespaceKeyFunc)
cache.NewReflector(podLW, &kapi.Pod{}, queue, 1*time.Minute).RunUntil(stopChannel)
return func() *kapi.Pod {
obj := cache.Pop(queue)
return obj.(*kapi.Pod)
}
}
// NewAcceptAvailablePods makes a new acceptAvailablePods from a real client.
func NewAcceptAvailablePods(
out io.Writer,
kclient kcoreclient.PodsGetter,
timeout time.Duration,
interval time.Duration,
minReadySeconds int32,
) *acceptAvailablePods {
return &acceptAvailablePods{
out: out,
timeout: timeout,
interval: interval,
minReadySeconds: minReadySeconds,
acceptedPods: sets.NewString(),
getRcPodStore: func(rc *kapi.ReplicationController) (cache.Store, chan struct{}) {
selector := labels.Set(rc.Spec.Selector).AsSelector()
store := cache.NewStore(cache.MetaNamespaceKeyFunc)
lw := &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
options.LabelSelector = selector.String()
return kclient.Pods(rc.Namespace).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.LabelSelector = selector.String()
return kclient.Pods(rc.Namespace).Watch(options)
},
}
stop := make(chan struct{})
cache.NewReflector(lw, &kapi.Pod{}, store, 10*time.Second).RunUntil(stop)
return store, stop
},
}
}
// acceptAvailablePods will accept a replication controller if all the pods
// for the replication controller become available.
//
// acceptAvailablePods keeps track of the pods it has accepted for a
// replication controller so that the acceptor can be reused across multiple
// batches of updates to a single controller. For example, if during the first
// acceptance call the replication controller has 3 pods, the acceptor will
// validate those 3 pods. If the same acceptor instance is used again for the
// same replication controller which now has 6 pods, only the latest 3 pods
// will be considered for acceptance. The status of the original 3 pods becomes
// irrelevant.
//
// Note that this struct is stateful and intended for use with a single
// replication controller and should be discarded and recreated between
// rollouts.
type acceptAvailablePods struct {
out io.Writer
// getRcPodStore should return a Store containing all the pods for the
// replication controller, and a channel to stop whatever process is
// feeding the store.
getRcPodStore func(*kapi.ReplicationController) (cache.Store, chan struct{})
// timeout is how long to wait for pod readiness.
timeout time.Duration
// interval is how often to check for pod readiness
interval time.Duration
// minReadySeconds is the minimum number of seconds for which a newly created
// pod should be ready without any of its container crashing, for it to be
// considered available.
minReadySeconds int32
// acceptedPods keeps track of pods which have been previously accepted for
// a replication controller.
acceptedPods sets.String
}
// Accept all pods for a replication controller once they are available.
func (c *acceptAvailablePods) Accept(rc *kapi.ReplicationController) error {
// Make a pod store to poll and ensure it gets cleaned up.
podStore, stopStore := c.getRcPodStore(rc)
defer close(stopStore)
// Start checking for pod updates.
if c.acceptedPods.Len() > 0 {
fmt.Fprintf(c.out, "--> Waiting up to %s for pods in rc %s to become ready (%d pods previously accepted)\n", c.timeout, rc.Name, c.acceptedPods.Len())
} else {
fmt.Fprintf(c.out, "--> Waiting up to %s for pods in rc %s to become ready\n", c.timeout, rc.Name)
}
err := wait.Poll(c.interval, c.timeout, func() (done bool, err error) {
// Check for pod readiness.
unready := sets.NewString()
for _, obj := range podStore.List() {
pod := obj.(*kapi.Pod)
// Skip previously accepted pods; we only want to verify newly observed
// and unaccepted pods.
if c.acceptedPods.Has(pod.Name) {
continue
}
if kapi.IsPodAvailable(pod, c.minReadySeconds, metav1.NewTime(time.Now())) {
// If the pod is ready, track it as accepted.
c.acceptedPods.Insert(pod.Name)
} else {
// Otherwise, track it as unready.
unready.Insert(pod.Name)
}
}
// Check to see if we're done.
if unready.Len() == 0 {
return true, nil
}
// Otherwise, try again later.
glog.V(4).Infof("Still waiting for %d pods to become ready for rc %s", unready.Len(), rc.Name)
return false, nil
})
// Handle acceptance failure.
if err != nil {
if err == wait.ErrWaitTimeout {
return fmt.Errorf("pods for rc %q took longer than %.f seconds to become ready", rc.Name, c.timeout.Seconds())
}
return fmt.Errorf("pod readiness check failed for rc %q: %v", rc.Name, err)
}
return nil
}
| {
"content_hash": "5b67cc2e5c79d81431407e8a0d13cd9b",
"timestamp": "",
"source": "github",
"line_count": 587,
"max_line_length": 178,
"avg_line_length": 36.37819420783646,
"alnum_prop": 0.7205675751615622,
"repo_name": "smarterclayton/origin",
"id": "89a9c772928132d8f2dfc734aa7e0025585a8e61",
"size": "21354",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pkg/deploy/strategy/support/lifecycle.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "1842"
},
{
"name": "DIGITAL Command Language",
"bytes": "117"
},
{
"name": "Go",
"bytes": "18846196"
},
{
"name": "Groovy",
"bytes": "5288"
},
{
"name": "HTML",
"bytes": "74732"
},
{
"name": "Makefile",
"bytes": "21696"
},
{
"name": "Protocol Buffer",
"bytes": "635483"
},
{
"name": "Python",
"bytes": "33408"
},
{
"name": "Roff",
"bytes": "2049"
},
{
"name": "Ruby",
"bytes": "484"
},
{
"name": "Shell",
"bytes": "2152560"
},
{
"name": "Smarty",
"bytes": "626"
}
],
"symlink_target": ""
} |
package no.kantega.openaksess.rest.jersey;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
/**
* @author Kristian Myrhaug
* @since 2015-08-11
*/
@Provider
@Produces("application/json")
@Consumes("application/json")
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
private ObjectMapper objectMapper;
@Override
public ObjectMapper getContext(Class<?> type) {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.enable(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()));
}
return objectMapper;
}
}
| {
"content_hash": "79b46034bfa1334565442982548f459d",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 114,
"avg_line_length": 36,
"alnum_prop": 0.7635135135135135,
"repo_name": "kantega/Flyt-cms",
"id": "1a1bdc8197e4392cb70c1d13458d839c6b14e903",
"size": "1332",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/content-api/src/main/java/no/kantega/openaksess/rest/jersey/ObjectMapperContextResolver.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "102415"
},
{
"name": "Groovy",
"bytes": "9509"
},
{
"name": "HTML",
"bytes": "1484"
},
{
"name": "Java",
"bytes": "4322582"
},
{
"name": "JavaScript",
"bytes": "562456"
},
{
"name": "XSLT",
"bytes": "3705"
}
],
"symlink_target": ""
} |
module Fastlane
module Actions
class CleanBuildArtifactsAction < Action
def self.run(options)
[
Actions.lane_context[Actions::SharedValues::IPA_OUTPUT_PATH],
Actions.lane_context[Actions::SharedValues::SIGH_PROFILE_PATH],
Actions.lane_context[Actions::SharedValues::DSYM_OUTPUT_PATH]
].reject { |file| file.nil? || !File.exist?(file) }.each do |file|
if options[:exclude_pattern]
next if file.match(options[:exclude_pattern])
end
Helper.log.debug "Cleaning up '#{file}'".yellow
File.delete(file)
end
Helper.log.info 'Cleaned up build artifacts 🐙'.green
end
def self.available_options
[
FastlaneCore::ConfigItem.new(key: :exclude_pattern,
env_name: "FL_CLEAN_BUILD_ARTIFACTS_EXCLUDE_PATTERN",
description: "Exclude all files from clearing that match the given pattern: e.g. '.*\.mobileprovision'",
default_value: nil,
optional: true)
]
end
def self.description
"Deletes files created as result of running ipa or sigh"
end
def self.author
"lmirosevic"
end
def self.is_supported?(platform)
[:ios, :mac].include? platform
end
end
end
end
| {
"content_hash": "2fb4464aff5eae3aa5b987bb95327e6e",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 143,
"avg_line_length": 32.54545454545455,
"alnum_prop": 0.5565642458100558,
"repo_name": "cpsloal/fastlane",
"id": "fd7a02884c65b2dacb4991b1f73db1ec4d61f443",
"size": "1435",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "lib/fastlane/actions/clean_build_artifacts.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "11235"
},
{
"name": "Ruby",
"bytes": "532513"
}
],
"symlink_target": ""
} |
module FraseHelper
end
| {
"content_hash": "909f332b02f199e55fb3093b9a655721",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 18,
"avg_line_length": 11.5,
"alnum_prop": 0.8695652173913043,
"repo_name": "marciojrtorres/ds2-2014",
"id": "7150237f6515e78763906a453940b2f30e09416c",
"size": "23",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rails/frases/app/helpers/frase_helper.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4271"
},
{
"name": "CoffeeScript",
"bytes": "1581"
},
{
"name": "JavaScript",
"bytes": "2022"
},
{
"name": "Ruby",
"bytes": "94292"
}
],
"symlink_target": ""
} |
Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Do not eager load code on boot.
config.eager_load = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_files = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
end
| {
"content_hash": "35b386781215fac72e9aea1b732557c5",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 104,
"avg_line_length": 35.93939393939394,
"alnum_prop": 0.7449409780775716,
"repo_name": "mirrec/token_field",
"id": "88a0205997d6e637f40437f0747b42eff1cc5517",
"size": "2372",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/dummy/config/environments/production.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "579"
},
{
"name": "HTML",
"bytes": "4780"
},
{
"name": "JavaScript",
"bytes": "671"
},
{
"name": "Ruby",
"bytes": "44846"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Octokit
{
public class EventsClient : ApiClient, IEventsClient
{
public EventsClient(IApiConnection apiConnection)
: base(apiConnection)
{
}
/// <summary>
/// Gets all the public events
/// </summary>
/// <remarks>
/// http://developer.github.com/v3/activity/events/#list-public-events
/// </remarks>
/// <returns>All the public <see cref="Activity"/>s for the particular user.</returns>
public Task<IReadOnlyList<Activity>> GetAll()
{
return ApiConnection.GetAll<Activity>(ApiUrls.Events());
}
/// <summary>
/// Gets all the events for a given repository
/// </summary>
/// <remarks>
/// http://developer.github.com/v3/activity/events/#list-issue-events-for-a-repository
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <returns>All the <see cref="Activity"/>s for the particular repository.</returns>
public Task<IReadOnlyList<Activity>> GetAllForRepository(string owner, string name)
{
Ensure.ArgumentNotNullOrEmptyString(owner, "owner");
Ensure.ArgumentNotNullOrEmptyString(name, "name");
return ApiConnection.GetAll<Activity>(ApiUrls.IssuesEvents(owner, name));
}
/// <summary>
/// Gets all the events for a given repository network
/// </summary>
/// <remarks>
/// http://developer.github.com/v3/activity/events/#list-public-events-for-a-network-of-repositories
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <returns>All the <see cref="Activity"/>s for the particular repository network.</returns>
public Task<IReadOnlyList<Activity>> GetAllForRepositoryNetwork(string owner, string name)
{
Ensure.ArgumentNotNullOrEmptyString(owner, "owner");
Ensure.ArgumentNotNullOrEmptyString(name, "name");
return ApiConnection.GetAll<Activity>(ApiUrls.NetworkEvents(owner, name));
}
/// <summary>
/// Gets all the events for a given organization
/// </summary>
/// <remarks>
/// http://developer.github.com/v3/activity/events/#list-public-events-for-an-organization
/// </remarks>
/// <param name="organization">The name of the organization</param>
/// <returns>All the <see cref="Activity"/>s for the particular organization.</returns>
public Task<IReadOnlyList<Activity>> GetAllForOrganization(string organization)
{
Ensure.ArgumentNotNullOrEmptyString(organization, "organization");
return ApiConnection.GetAll<Activity>(ApiUrls.OrganizationEvents(organization));
}
/// <summary>
/// Gets all the events that have been received by a given user.
/// </summary>
/// <remarks>
/// http://developer.github.com/v3/activity/events/#list-events-that-a-user-has-received
/// </remarks>
/// <param name="user">The login of the user</param>
/// <returns>All the <see cref="Activity"/>s that a particular user has received.</returns>
public Task<IReadOnlyList<Activity>> GetUserReceived(string user)
{
Ensure.ArgumentNotNullOrEmptyString(user, "user");
return ApiConnection.GetAll<Activity>(ApiUrls.ReceivedEvents(user));
}
/// <summary>
/// Gets all the events that have been received by a given user.
/// </summary>
/// <remarks>
/// http://developer.github.com/v3/activity/events/#list-public-events-that-a-user-has-received
/// </remarks>
/// <param name="user">The login of the user</param>
/// <returns>All the <see cref="Activity"/>s that a particular user has received.</returns>
public Task<IReadOnlyList<Activity>> GetUserReceivedPublic(string user)
{
Ensure.ArgumentNotNullOrEmptyString(user, "user");
return ApiConnection.GetAll<Activity>(ApiUrls.ReceivedEvents(user, true));
}
/// <summary>
/// Gets all the events that have been performed by a given user.
/// </summary>
/// <remarks>
/// http://developer.github.com/v3/activity/events/#list-events-performed-by-a-user
/// </remarks>
/// <param name="user">The login of the user</param>
/// <returns>All the <see cref="Activity"/>s that a particular user has performed.</returns>
public Task<IReadOnlyList<Activity>> GetUserPerformed(string user)
{
Ensure.ArgumentNotNullOrEmptyString(user, "user");
return ApiConnection.GetAll<Activity>(ApiUrls.PerformedEvents(user));
}
/// <summary>
/// Gets all the public events that have been performed by a given user.
/// </summary>
/// <remarks>
/// http://developer.github.com/v3/activity/events/#list-public-events-performed-by-a-user
/// </remarks>
/// <param name="user">The login of the user</param>
/// <returns>All the public <see cref="Activity"/>s that a particular user has performed.</returns>
public Task<IReadOnlyList<Activity>> GetUserPerformedPublic(string user)
{
Ensure.ArgumentNotNullOrEmptyString(user, "user");
return ApiConnection.GetAll<Activity>(ApiUrls.PerformedEvents(user, true));
}
/// <summary>
/// Gets all the events that are associated with an organization.
/// </summary>
/// <remarks>
/// http://developer.github.com/v3/activity/events/#list-events-for-an-organization
/// </remarks>
/// <param name="user">The login of the user</param>
/// <param name="organization">The name of the organization</param>
/// <returns>All the public <see cref="Activity"/>s that are associated with an organization.</returns>
public Task<IReadOnlyList<Activity>> GetForAnOrganization(string user, string organization)
{
Ensure.ArgumentNotNullOrEmptyString(user, "user");
Ensure.ArgumentNotNullOrEmptyString(organization, "organization");
return ApiConnection.GetAll<Activity>(ApiUrls.OrganizationEvents(user, organization));
}
}
}
| {
"content_hash": "851fa9b36bc17f785c8c619a5d048b50",
"timestamp": "",
"source": "github",
"line_count": 151,
"max_line_length": 111,
"avg_line_length": 43.76158940397351,
"alnum_prop": 0.6203087167070218,
"repo_name": "yonglehou/octokit.net",
"id": "f21ed2144ff8bf394c3f2160103f73e8afe669e8",
"size": "6610",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Octokit/Clients/EventsClient.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "894601"
},
{
"name": "F#",
"bytes": "4940"
},
{
"name": "PowerShell",
"bytes": "2340"
},
{
"name": "Shell",
"bytes": "733"
}
],
"symlink_target": ""
} |
package iso20022
// Specifies the type of the document line identification.
type DocumentLineType1 struct {
// Provides the type details of the referred document line identification.
CodeOrProprietary *DocumentLineType1Choice `xml:"CdOrPrtry"`
// Identification of the issuer of the reference document line identificationtype.
Issuer *Max35Text `xml:"Issr,omitempty"`
}
func (d *DocumentLineType1) AddCodeOrProprietary() *DocumentLineType1Choice {
d.CodeOrProprietary = new(DocumentLineType1Choice)
return d.CodeOrProprietary
}
func (d *DocumentLineType1) SetIssuer(value string) {
d.Issuer = (*Max35Text)(&value)
}
| {
"content_hash": "eb7232173f64d92f3359f06ccf1dd588",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 83,
"avg_line_length": 31.4,
"alnum_prop": 0.7929936305732485,
"repo_name": "fgrid/iso20022",
"id": "a5118625ffefa0d33cd0519ce54b9e805d920024",
"size": "628",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DocumentLineType1.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "21383920"
}
],
"symlink_target": ""
} |
{% extends "layout_lr.html" %}
{% block page_title %}
Local land charges
{% endblock %}
{% block content %}
<main id="content" role="main">
<div class="grid-row">
<div class="column-two-thirds">
<h1 class="heading-large">Register a local land charge </h1>
<h2 class="heading-medium">What legal provision allows the {{ charge_type }} to be registered? </h2>
<form>
<fieldset class="inline">
<legend class="visuallyhidden">What legal provision allows the charge to be registered? </legend>
<div class="form-group">
<label class="form-label" for="law-act-agree">
Law, Act or Agreement
</label>
<input class="form-control" id="law-act-agree" type="text">
</div>
<div class="form-group">
<label class="form-label" for="section">
Section
</label>
<input class="form-control" id="section" type="text">
</div>
</fieldset>
<a class="button" href="/llc-02/register-6" role="button">Continue</a>
</form>
</div>
</div>
</main>
{% endblock %}
| {
"content_hash": "95d0713e69fbcb6b29267a64b1750c7d",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 113,
"avg_line_length": 29.837209302325583,
"alnum_prop": 0.5003897116134061,
"repo_name": "LandRegistry/llc-prototype",
"id": "44851176522f68f1b0ae6acc3d6c099b72cdc5e9",
"size": "1283",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "app/views/llc-02/register/register_5-law.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "66599"
},
{
"name": "HTML",
"bytes": "13226874"
},
{
"name": "JavaScript",
"bytes": "226812"
},
{
"name": "Shell",
"bytes": "649"
}
],
"symlink_target": ""
} |
module("magic.ComboBox");
test("render, default param", function(){
stop();
ua.loadcss(upath + 'setup/combobox/combobox.css', function() {
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
'items' : [{
'value' : 'f', 'content' : '女'
}, {
'value' : 'm', 'content' : '男'
}]
});
combobox1.render(div1);
equals(combobox1._options.items.length, 2, "The items is right");
combobox1.menu.show();
equals(combobox1.getElement('menu').getElementsByTagName('LI').length, 2, "The items displayed is right");
combobox1.menu.hide();
equals(combobox1._options.originIndex, -1, "The originIndex is right");
equals(combobox1.getElement('input').value, '', "The originIndex in readonly=false is right");
equals(combobox1._options.viewSize, 5, "The viewSize is right");
equals(combobox1._options.readonly, false, "The readonly is right");
equals($(combobox1.getElement('input')).attr('readonly'), undefined, "The readonly displayed is right");
equals(combobox1._options.disabled, false, "The disabled is right");
equals(combobox1.getElement('input').disabled, false, "The disabled displayed is right");
equals(combobox1._options.width, '100%', "The width is right");
var offset = (baidu.browser.ie == 6 ? 0 : -2);
equals(combobox1.getElement('container').offsetWidth + offset, combobox1.getElement('container').parentNode.offsetWidth, "The width displayed is right");
combobox1.$dispose();
document.body.removeChild(div1);
start();
});
});
test("render, all param", function(){
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
'items' : [{
'value' : 'beijing',
'content' : '北京'
},{
'value' : 'shanghai',
'content' : '上海'
},{
'value' : 'guangzhou',
'content' : '广州'
},{
'value' : 'tianjin',
'content' : '天津'
},{
'value' : 'chongqing',
'content' : '重庆'
}],
'originIndex' : 1,
'viewSize' : 3,
'readonly' : true,
'disabled' : false,
'width' : 200
});
combobox1.render(div1);
equals(combobox1._options.originIndex, 1, "_options.originIndex is right");
equals(combobox1._options.viewSize, 3, "_options.viewSize is right");
equals(combobox1._options.readonly, true, "_options.readonly is right");
equals(combobox1._options.disabled, false, "_options.disabled is right");
equals(combobox1._options.width, '200', "_options.width is right");
equals((function(){
var res = '';
for (var i=0;i<combobox1._options.items.length;i++) {
res += combobox1._options.items[i].content;
}
return res;
})(), "北京上海广州天津重庆", "_options.items is right");
equals(combobox1.getElement('input').value, '上海', "The item of originIndex displayed in input.");
equals($("li", combobox1.getElement("menu")).text(), "北京上海广州天津重庆", "The content of menu is right");
equals($($("li", combobox1.getElement("menu"))[0]).attr('data-value'), "beijing", "The values of menu is right");
equals(combobox1.getElement('container').clientWidth, 200, "The width is right");
equals($(combobox1.getElement('input')).attr('readonly'), "readonly", "The readonly displayed is right");
equals(combobox1.getElement('input').disabled, false, "The disabled displayed is right");
combobox1.$dispose();
document.body.removeChild(div1);
});
//3
test("render, readonly", function(){
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
'items' : [{
'value' : 'beijing',
'content' : '北京'
},{
'value' : 'shanghai',
'content' : '上海'
},{
'value' : 'guangzhou',
'content' : '广州'
},{
'value' : 'tianjin',
'content' : '天津'
},{
'value' : 'chongqing',
'content' : '重庆'
}],
'readonly' : true
});
combobox1.render(div1);
equals(combobox1.getElement('input').value, '北京', "The item of originIndex displayed in input.");
combobox1.$dispose();
document.body.removeChild(div1);
});
//4
test("render, render", function() {
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 'f', 'content' : '女'
}, {
'value' : 'm', 'content' : '男'
}]
});
combobox1.render(div1);
var container = combobox1.getElement('container');
equals(true, $.contains(div1, container), 'position of combobox is right.');
equals(baidu.dom(div1).offset().left, baidu.dom(container).offset().left, 'left');
equals(baidu.dom(div1).offset().top, baidu.dom(container).offset().top, 'top');
combobox1.menu.show();
var menu = combobox1.getElement('menu');
equals(baidu.dom(container).offset().left, baidu.dom(menu).offset().left, 'left');
var offset = -1;
equals(baidu.dom(container).offset().top + container.offsetHeight + offset, baidu.dom(menu).offset().top, 'top');
combobox1.$dispose();
document.body.removeChild(div1);
});
//5
test("render, events", function() {
expect(32);
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var highlight = pick = change = 0;
var l1 = !ua.adapterMode ? ua.getEventsLength(baidu._util_.eventBase.queue) : 0;
var combobox1 = new magic.ComboBox({
items : [{
'value' : 'f', 'content' : '女'
}, {
'value' : 'm', 'content' : '男'
}]
});
combobox1.on("show", function(e, data){
equals('show', 'show', "The show Event is right");
equals(this.menu.visible, true, "menu is visible.");
});
combobox1.on("hide", function(e, data){
equals('hide', 'hide', "The hide Event is right");
});
combobox1.on("load", function(e, data){
equals('load', 'load', "The load Event is right");
});
combobox1.on("focus", function(e, data){
equals('focus', 'focus', "The focus Event is right");
});
combobox1.on("blur", function(e, data){
equals('blur', 'blur', "The blur Event is right");
});
combobox1.on("highlight", function(e, data){
highlight ++;
switch(highlight) {
case 1 :
equals(e.index, 0, "The highlight Event is right");
break;
case 2 :
equals(e.index, 1, "The highlight Event is right");
}
});
combobox1.on("pick", function(e, data){
pick ++;
switch(pick) {
case 1 :
equals(e.result.value, 'f', "The result.value of pick Event is right");
equals(e.result.index, 0, "The result.index of pick Event is right");
equals(e.result.content, '女', "The result.content of pick Event is right");
break;
case 2 :
equals(e.result.value, 'm', "The result.value of pick Event is right");
equals(e.result.index, 1, "The result.index of pick Event is right");
equals(e.result.content, '男', "The result.content of pick Event is right");
break;
}
});
combobox1.on("menufocus", function(e, data){
equals(e.result.value, 'f', "The result.value of menufocus Event is right");
equals(e.result.index, 0, "The result.value menufocus Event is right");
equals(e.result.content, '女', "The result.value menufocus Event is right");
});
combobox1.on("clickitem", function(e, data){
equals(e.result.value, 'm', "The result.value of clickitem Event is right");
equals(e.result.index, 1, "The result.value clickitem Event is right");
equals(e.result.content, '男', "The result.value clickitem Event is right");
});
combobox1.on("confirm", function(e, data){
equals(e.result.value, 'm', "The result.value of confirm Event is right");
equals(e.result.index, 1, "The result.value confirm Event is right");
equals(e.result.content, '男', "The result.value confirm Event is right");
});
combobox1.on("change", function(e, data){
change ++;
switch (change) {
case 1 :
equals(e.from, 'confirm', "The confirm change Event is right");
equals(e.result.index, 1, "The result.index of confirm change Event is right");
equals(e.result.value, 'm', "The result.value of confirm change Event is right");
equals(e.result.content, '男', "The result.content of confirm change Event is right");
break;
case 2 :
equals(e.from, 'blur', "The confirm change Event is right");
}
});
combobox1.on("reload", function(e, data){
equals(combobox1._options.items[0].content, '北京', "The reload Event is right");
});
combobox1.on("dispose", function(e, data){
equals('dispose', 'dispose', "The dispose Event is right");
var l2 = !ua.adapterMode ? ua.getEventsLength(baidu._util_.eventBase.queue) : 0;
equals(l2, l1, "The events are un");
});
combobox1.render(div1);
ua.click(combobox1.getElement("arrow"));
ua.click(combobox1.getElement('input'));
ua.keydown(combobox1.getElement('input'), {
'keyCode' : 40
});
ua.click($('li', combobox1.getElement('menu'))[1]);
combobox1.getElement('input').value = '不男不女';
combobox1.blur();
combobox1.reload([{
'value' : 'beijing',
'content' : '北京'
},{
'value' : 'shanghai',
'content' : '上海'
},{
'value' : 'guangzhou',
'content' : '广州'
},{
'value' : 'tianjin',
'content' : '天津'
},{
'value' : 'chongqing',
'content' : '重庆'
}]);
combobox1.$dispose();
document.body.removeChild(div1);
});
//5
test('render event beforeshow beforehide', function() {
stop();
expect(9);
ua.importsrc('baidu.lang.Class.$removeEventListener', function() {
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 0, 'content' : '女'
}, {
'value' : 1, 'content' : '男'
}]
});
function f1(e) {
equals('beforeshow', 'beforeshow', "The beforeshow Event is right");
e.returnValue = false;
}
function f2(e) {
equals('beforehide', 'beforehide', "The beforehide Event is right");
e.returnValue = false;
}
combobox1.on("beforeshow", f1);
combobox1.on("beforehide", f2);
combobox1.on('show', function() {
equals('show', 'show', 'show event fired');
});
combobox1.on('hide', function() {
equals('hide', 'hide', 'hide event fired');
});
combobox1.render(div1);
ua.click(combobox1.getElement('arrow'));
equals(combobox1.menu.visible, false, "The beforeshow Event prevent show event is right");
combobox1.un("beforeshow", f1);
ua.click(combobox1.getElement('arrow'));
equals(combobox1.menu.visible, true, "showing is right");
ua.click($('li', combobox1.getElement('menu'))[0]);
equals(combobox1.menu.visible, true, "The beforehide Event prevent hide event is right");
combobox1.un("beforehide", f2);
ua.click($('li', combobox1.getElement('menu'))[0]);
equals(combobox1.menu.visible, false, "hiding is right");
combobox1.$dispose();
document.body.removeChild(div1);
start();
}, 'baidu.lang.Class.$removeEventListener', 'magic.ComboBox');
});
//6
test('render event beforepick', function() {
expect(4);
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 0, 'content' : '女'
}, {
'value' : 1, 'content' : '男'
}]
});
function f1(e) {
equals('beforepick', 'beforepick', "The beforepick Event is right");
e.returnValue = false;
}
combobox1.on("beforepick", f1);
combobox1.on("pick", function(e) {
equals(e.result.value, 0, 'result.value of pick event.');
});
combobox1.render(div1);
ua.click(combobox1.getElement('arrow'));
ua.click($('li', combobox1.getElement('menu'))[0]);
equals(combobox1.getElement('input').value, '', "The beforepick Event prevent pick event is right");
combobox1.un("beforepick", f1);
ua.click(combobox1.getElement('arrow'));
ua.click($('li', combobox1.getElement('menu'))[0]);
equals(combobox1.getElement('input').value, '女', "pick event is right");
combobox1.$dispose();
document.body.removeChild(div1);
});
test("render, getValue", function(){
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 0, 'content' : '女'
}, {
'value' : 1, 'content' : '男'
}]
});
combobox1.render(div1);
var input = combobox1.getElement('input');
ua.click(input);
$(input).attr('value', 'abc');
equals(combobox1.getValue(), 'abc', "getValue(), input a value which not in the menu, is right.");
$(input).attr('value', '男');
equals(combobox1.getValue(), '1', "getValue(), input a value which in the menu, is right.");
ua.click(combobox1.getElement('arrow'));
ua.click($('li', combobox1.getElement('menu'))[0]);
equals(combobox1.getValue(), '0', "getValue(), click a item in the menu, is right.");
combobox1.$dispose();
document.body.removeChild(div1);
});
test("render, getSelectIndex", function(){
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 'f', 'content' : '女'
}, {
'value' : 'm', 'content' : '男'
}]
});
combobox1.render(div1);
var input = combobox1.getElement('input');
ua.click(input);
$(input).attr('value', 'abc');
equals(combobox1.getSelectIndex(), -1, "getSelectIndex(), input a value which not in the menu, is right.");
ua.click(combobox1.getElement('arrow'));
ua.click($('li', combobox1.getElement('menu'))[0]);
equals(combobox1.getSelectIndex(), '0', "getSelectIndex(), click a item in the menu, is right.");
combobox1.$dispose();
document.body.removeChild(div1);
});
test("render, setByValue", function(){
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 'f', 'content' : '女'
}, {
'value' : 'm', 'content' : '男'
}]
});
combobox1.render(div1);
combobox1.setByValue('m');
var input = combobox1.getElement('input');
equals(combobox1.getElement('input').value, '男', "setByValue(), the value in the inputbox is right.");
equals(combobox1.getValue(), 'm', "setByValue(), getValue() == 'm' is right.");
equals(combobox1.selectValue, 'm', "selectValue is right.");
combobox1.$dispose();
document.body.removeChild(div1);
});
test("render, focus", function() {
expect(2);
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 'f', 'content' : '女'
}, {
'value' : 'm', 'content' : '男'
}]
});
var focus = 0;
combobox1.render(div1);
combobox1.on('focus', function() {
focus ++;
switch (focus) {
case 1 :
equals('focus once', 'focus once', "focus is right.");
equals(combobox1.isFocus, true, "instance.isFocus is right.");
break;
case 2 :
equals('only focus once', 'focus twice', "focus is wrong.");
break;
}
});
combobox1.focus();
combobox1.focus();
ua.click(combobox1.getElement('arrow'));
combobox1.$dispose();
document.body.removeChild(div1);
});
test("render, blur", function(){
expect(2);
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 'f', 'content' : '女'
}, {
'value' : 'm', 'content' : '男'
}]
});
var blur = 0;
combobox1.render(div1);
combobox1.on('blur', function() {
blur ++;
switch (blur) {
case 1 :
equals('blur once', 'blur once', "blur is right.");
equals(combobox1.isFocus, false, "instance.isFocus is right.");
break;
case 2 :
equals('blur twice', 'only blur once', "blur is wrong.");
break;
}
});
combobox1.focus();
combobox1.blur();
combobox1.blur();
combobox1.$dispose();
document.body.removeChild(div1);
});
test("render, reset originIndex=1", function(){
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 'f', 'content' : '女'
}, {
'value' : 'm', 'content' : '男'
}],
originIndex : 1
});
combobox1.render(div1);
combobox1.getElement('input').value = 'abx';
combobox1.reset();
equals(combobox1.getElement('input').value, '男', "input value is right.");
equals(combobox1.getValue(), 'm', "getValue() is right.");
combobox1.$dispose();
document.body.removeChild(div1);
});
test("render, reset originIndex=-1 readonly=false", function(){
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 'f', 'content' : '女'
}, {
'value' : 'm', 'content' : '男'
}],
originIndex : -1
});
combobox1.render(div1);
combobox1.getElement('input').value = 'abx';
combobox1.reset();
equals(combobox1.getElement('input').value, '', "input value is right.");
equals(combobox1.getValue(), '', "getValue() is right.");
combobox1.$dispose();
document.body.removeChild(div1);
});
test("render, reset originIndex=-1 readonly=true", function(){
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 'f', 'content' : '女'
}, {
'value' : 'm', 'content' : '男'
}],
originIndex : -1,
readonly : true
});
combobox1.render(div1);
combobox1.getElement('input').value = 'abx';
combobox1.reset();
equals(combobox1.getElement('input').value, '女', "input value is right.");
equals(combobox1.getValue(), 'f', "getValue() is right.");
combobox1.$dispose();
document.body.removeChild(div1);
});
test("render, reload", function(){
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 'f', 'content' : '女'
}, {
'value' : 'm', 'content' : '男'
}],
originIndex : 1
});
var reloadData = [{
'value' : 'beijing',
'content' : '北京'
},{
'value' : 'shanghai',
'content' : '上海'
},{
'value' : 'guangzhou',
'content' : '广州'
},{
'value' : 'tianjin',
'content' : '天津'
},{
'value' : 'chongqing',
'content' : '重庆'
}];
combobox1.render(div1);
combobox1.reload(reloadData);
equals(combobox1._options.items[0].value, "beijing", "The _options.items is right");
equals($("li", combobox1.getElement("menu")).text(), "北京上海广州天津重庆", "menu is right");
equals(combobox1.getElement('input').value, '上海', "input value is right.");
combobox1.$dispose();
document.body.removeChild(div1);
});
test("render, disable", function(){
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 'f', 'content' : '女'
}, {
'value' : 'm', 'content' : '男'
}]
});
combobox1.render(div1);
combobox1.disable();
equals($(combobox1.getElement('container')).hasClass('magic-combobox-disable'), true, "The disable style is right");
equals(combobox1.getElement('input').disabled, true, "input disabled right");
equals(combobox1.disabled, true, "instance.disabled is right.");
combobox1.$dispose();
document.body.removeChild(div1);
});
test("render, enable", function(){
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 'f', 'content' : '女'
}, {
'value' : 'm', 'content' : '男'
}],
disabled : true
});
combobox1.render(div1);
combobox1.enable();
equals($(combobox1.getElement('container')).hasClass('magic-combobox-disable'), false, "The enable style is right");
equals(combobox1.getElement('input').disabled, false, "input enable right");
equals(combobox1.disabled, false, "instance.disabled is right.");
combobox1.$dispose();
document.body.removeChild(div1);
});
test("render, setWidth", function(){
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 'f', 'content' : '女'
}, {
'value' : 'm', 'content' : '男'
}]
});
combobox1.render(div1);
combobox1.setWidth(200);
equals(combobox1.getElement('container').clientWidth, 200, 'width of input container is right');
ua.click(combobox1.getElement('arrow'));
equals(combobox1.getElement('menu').clientWidth, 200, 'width of menu is right');
combobox1.$dispose();
document.body.removeChild(div1);
});
test("render, dispose", function() {
stop();
ua.importsrc('baidu.array.indexOf', function() {
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 'f', 'content' : '女'
}, {
'value' : 'm', 'content' : '男'
}]
});
combobox1.render(div1);
var comboid = combobox1.guid,
popguid = combobox1.menu.guid,
popdomid = combobox1.menu.$getId(),
container = combobox1.getElement('container'),
menu = combobox1.getElement('menu');
equals(true, !!baiduInstance(popguid), 'popup is created.');
equals(0, baidu.array.indexOf(magic.control.ComboBox.instanceArray, comboid), 'guid is added in global array.')
ua.click(combobox1.getElement('arrow'));
combobox1.$dispose();
equals($.contains(document.body, container), false, 'container is removed');
equals($.contains(document.body, menu), false, 'menu is removed');
//equals(baidu.dom('#' + popdomid).style.display, 'none', 'popup is hidden');
equals(undefined, baiduInstance(popguid), 'popup is disposed.');
equals(-1, baidu.array.indexOf(magic.control.ComboBox.instanceArray, comboid), 'guid is removed from global array.')
document.body.removeChild(div1);
start();
}, 'baidu.array.indexOf', 'magic.ComboBox');
});
test("render, keyboard action", function(){
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 'f', 'content' : '女'
}, {
'value' : 'm', 'content' : '男'
}]
});
var focus = 0;
combobox1.on('menufocus', function(e) {
focus ++;
switch (focus) {
case 1 :
equals(e.result.value, 'f', 'down keydown once right');
equals(this.menu.visible, true, 'menu is showing');
break;
case 2 :
equals(e.result.value, 'm', 'down keydown twice right');
break;
case 3 :
equals(e.result.value, 'f', 'down keydown 4 times right');
break;
case 4 :
equals(e.result.value, 'm', 'up keydown twice right');
break;
}
});
combobox1.on('confirm', function(e) {
equals(e.result.value, 'm', 'enter keydown right');
equals(this.menu.visible, false, 'menu is hiding');
});
combobox1.render(div1);
var input = combobox1.getElement('input');
input.value = 'abc';
ua.click(input);
ua.keydown(input, {
'keyCode' : 40
});
ua.keydown(input, {
'keyCode' : 40
});
ua.keydown(input, {
'keyCode' : 40
});
equals(input.value, 'abc', "The input value is right");
ua.keydown(input, {
'keyCode' : 40
});
ua.keydown(input, {
'keyCode' : 38
});
equals(input.value, 'abc', "The input value is right");
ua.keydown(input, {
'keyCode' : 38
});
ua.keydown(input, {
'keyCode' : 13
});
combobox1.$dispose();
document.body.removeChild(div1);
});
test("render, mouse action in readonly = false combobox", function(){
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 'f', 'content' : '女'
}, {
'value' : 'm', 'content' : '男'
}]
});
var mouseover = 0;
combobox1.on('highlight', function(e) {
mouseover ++;
switch (mouseover) {
case 1 :
equals(e.index, 0, 'The mouseover action is right');
equals($('li', combobox1.getElement('menu')).eq(0).hasClass('magic-combobox-menu-item-hover'), true, 'The highlight style is right');
break;
case 2 :
equals(e.index, 1, 'The mouseover action is right');
equals($('li', combobox1.getElement('menu')).eq(0).hasClass('magic-combobox-menu-item-hover'), false, 'clearHighlight is right');
equals($('li', combobox1.getElement('menu')).eq(1).hasClass('magic-combobox-menu-item-hover'), true, 'The highlight style is right');
break;
}
});
combobox1.on('confirm', function(e) {
equals(e.result.value, 'm', 'the click action is right');
});
combobox1.on('blur', function() {
equals(1, 1, 'blur!!');
});
combobox1.render(div1);
ua.click(combobox1.getElement('input'));
equals(combobox1.menu.visible, false, "the menu dosn't show is right");
ua.click(combobox1.getElement('arrow'));
equals(combobox1.menu.visible, true, "The menu is showing is right");
equals($('li', combobox1.getElement('menu')).length, 2, 'all the items are showing');
ua.mouseover($('li', combobox1.getElement('menu'))[0]);
ua.mouseover($('li', combobox1.getElement('menu'))[1]);
ua.click($('li', combobox1.getElement('menu'))[1]);
ua.click(combobox1.getElement('arrow'));
equals(combobox1.menu.visible, true, "The menu is showing is right");
stop();
setTimeout(function() {
ua.click(document);
equals(combobox1.menu.visible, false, "the menu dosn't show is right");
combobox1.$dispose();
document.body.removeChild(div1);
start();
}, 50);
});
test('render mouse action in readonly = true combobox', function() {
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 'f', 'content' : '女'
}, {
'value' : 'm', 'content' : '男'
}],
readonly : true
});
combobox1.render(div1);
ua.click(combobox1.getElement('input'));
equals(combobox1.menu.visible, true, "the menu is showing");
equals($('li', combobox1.getElement('menu')).length, 2, 'all the items are showing');
combobox1.$dispose();
document.body.removeChild(div1);
});
test("render, viewSize", function(){
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
items : [{
'value' : 'beijing',
'content' : '北京'
},{
'value' : 'shanghai',
'content' : '上海'
},{
'value' : 'guangzhou',
'content' : '广州'
},{
'value' : 'tianjin',
'content' : '天津'
},{
'value' : 'chongqing',
'content' : '重庆'
}],
viewSize : 3
});
combobox1.render(div1);
combobox1.menu.show();
var single = $('li', combobox1.getElement('menu'))[0];
var singleHeight = Math.max(single.offsetHeight, single.offsetHeight);
equals(combobox1.getElement('menu').offsetHeight, singleHeight * 3 + 1, 'when the number of items is more than viewSize, only viewSize of the items will be show, and there will be scroll.');
combobox1.menu.hide();
combobox1.reload([{
'value' : 'f', 'content' : '女'
}, {
'value' : 'm', 'content' : '男'
}]);
combobox1.menu.show();
equals(combobox1.getElement('menu').offsetHeight, singleHeight * 2 + 2, 'If number of items is less than viewSize, the viewSize is useless.')
combobox1.$dispose();
document.body.removeChild(div1);
});
test('use keyboard select items, press enter should be right while select the last item and continue to press down once', function() {
var div1 = document.createElement("div");
document.body.appendChild(div1);
div1.id = "div1";
var combobox1 = new magic.ComboBox({
'items' : [{
'value' : 0,
'content' : '选项1'
},{
'value' : 1,
'content' : '选项2'
},{
'value' : 2,
'content' : '选项3'
}]
});
combobox1.render('#div1');
combobox1.getElement('input').value = 'my value';
ua.keydown(combobox1.getElement('input'), {
keyCode : 40
});
ua.keydown(combobox1.getElement('input'), {
keyCode : 40
});
ua.keydown(combobox1.getElement('input'), {
keyCode : 40
});
ua.keydown(combobox1.getElement('input'), {
keyCode : 40
});
ua.keydown(combobox1.getElement('input'), {
keyCode : 13
});
equals(combobox1.getElement('input').value, 'my value', 'should be \'my value\'');
combobox1.$dispose();
document.body.removeChild(div1);
}); | {
"content_hash": "c99a9a6a75702562d2773850208f40ea",
"timestamp": "",
"source": "github",
"line_count": 909,
"max_line_length": 194,
"avg_line_length": 34.76897689768977,
"alnum_prop": 0.5669988925802879,
"repo_name": "BaiduFE/Magic",
"id": "76b7b78997220b81b818e5b5b9ca4fcbd36ae036",
"size": "31911",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/magic/ComboBox.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "148686"
},
{
"name": "JavaScript",
"bytes": "2493772"
},
{
"name": "PHP",
"bytes": "53627"
},
{
"name": "XSLT",
"bytes": "13511"
}
],
"symlink_target": ""
} |
import os
import pytest
import sh
from molecule.verifier import testinfra
@pytest.fixture()
def testinfra_instance(molecule_instance):
return testinfra.Testinfra(molecule_instance)
@pytest.fixture
def patched_code_verifier(mocker):
return mocker.patch('molecule.verifier.testinfra.Testinfra._flake8')
@pytest.fixture
def patched_test_verifier(mocker):
return mocker.patch('molecule.verifier.testinfra.Testinfra._testinfra')
@pytest.fixture
def patched_get_tests(mocker):
return mocker.patch('molecule.verifier.testinfra.Testinfra._get_tests')
@pytest.fixture
def patched_ansible(mocker):
return mocker.patch('molecule.ansible_playbook.AnsiblePlaybook')
def test_execute(mocker, patched_code_verifier, patched_test_verifier,
patched_get_tests, patched_ansible, testinfra_instance):
patched_get_tests.return_value = ['/test/1', '/test/2']
patched_ansible.return_value = mocker.Mock(env={})
testinfra_instance._molecule.args = {'debug': True, 'sudo': True}
testinfra_instance.execute()
patched_code_verifier.assert_called_once_with(['/test/1', '/test/2'])
patched_test_verifier.assert_called_once_with(
['/test/1', '/test/2'],
ansible_inventory='test/inventory_file',
ansible_env={},
connection='ansible',
debug=True,
sudo=True)
def test_execute_no_tests(patched_code_verifier, patched_test_verifier,
patched_get_tests, testinfra_instance):
patched_get_tests.return_value = []
testinfra_instance.execute()
assert not patched_code_verifier.called
assert not patched_test_verifier.called
def test_testinfra(patched_run_command, patched_get_tests, testinfra_instance):
args = ['/tmp/ansible-inventory']
kwargs = {'debug': False, '_out': None, '_err': None}
testinfra_instance._testinfra(*args, **kwargs)
x = sh.testinfra.bake('/tmp/ansible-inventory')
patched_run_command.assert_called_once_with(x, debug=None)
def test_flake8(patched_run_command, testinfra_instance):
args = ['test1.py', 'test2.py']
testinfra_instance._flake8(args)
x = sh.flake8.bake('test1.py', 'test2.py')
patched_run_command.assert_called_once_with(x, debug=None)
def test_get_tests(temp_dir, testinfra_instance):
testinfra_instance._testinfra_dir = temp_dir
dir1 = os.path.join(temp_dir, 'foo')
dir2 = os.path.join(temp_dir, 'foo', 'bar')
os.mkdir(dir1)
os.mkdir(dir2)
test_file = os.path.join(dir2, 'test_default.py')
open(test_file, 'a').close()
assert 1 == len(testinfra_instance._get_tests())
assert test_file == testinfra_instance._get_tests()[0]
| {
"content_hash": "8ce4f32a7d8860c4cb03b63187b05daa",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 79,
"avg_line_length": 30.01123595505618,
"alnum_prop": 0.6918757019842755,
"repo_name": "rgreinho/molecule",
"id": "16a8b596be2567f267fb41cd2ca03201a6d5033b",
"size": "3791",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/unit/verifier/test_testinfra.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "315730"
},
{
"name": "Ruby",
"bytes": "1110"
},
{
"name": "Shell",
"bytes": "4029"
}
],
"symlink_target": ""
} |
package com.decker.javaProgramming.lab.lab2;
import com.decker.javaProgramming.utils.InputType;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class LastDigit {
public static void main(String[] args) throws Exception {
LastDigit lastDigit=new LastDigit();
lastDigit.loop();
System.out.println("Exit!");
}
public void loop()
{
while (!this.receive().equals(InputType.Determined))
{
Integer sevenTimes= this.numberReceived*7;
Integer lastdigit = sevenTimes%10;
System.out.printf("The number you inputted is %d, then multiply 7 to %d. The last digit is %d %n",this.numberReceived,sevenTimes,lastdigit);
}
}
private Integer numberReceived;
public InputType receive() {
try {
System.out.print("Input a number or empty to return:");
String line = new BufferedReader(new InputStreamReader(System.in)).readLine();
if (StringUtils.isBlank(line)) {
return InputType.Determined;
}
numberReceived= Integer.valueOf(line);
return InputType.Normal;
} catch (Exception ex) {
return InputType.Error;
}
}
}
| {
"content_hash": "5e9b5c8b47582a59e23ce8389e2f87e5",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 152,
"avg_line_length": 27.333333333333332,
"alnum_prop": 0.6280487804878049,
"repo_name": "DeckerCHAN/COMP6700_Java_Programming",
"id": "edc4b89566421a6ac6da16126a2a46658124bd1d",
"size": "2457",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/decker/javaProgramming/lab/lab2/LastDigit.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "189563"
}
],
"symlink_target": ""
} |
This is an attempt at a piece of software that can turn recordings of whistling into a midi file.
Right now, it is mostly miss with a few hits included. Every now and then it will reconstruct the correct notes in the generated midi file, but it needs a lot more tuning until it's actually usuable.
##Why?
I wanted to work with the fast fourier transformation, and being able to whistle a beat or melody instead of having to create one in a note setting application seemed like a good application.
| {
"content_hash": "9328c282d7cf52b2717c06cf27ed97ac",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 199,
"avg_line_length": 71.42857142857143,
"alnum_prop": 0.79,
"repo_name": "trb/whistle2midi",
"id": "272339f143e6a9e448170c256af2dcedc1ac03ba",
"size": "518",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Python",
"bytes": "47474"
}
],
"symlink_target": ""
} |
using namespace fst;
namespace fst {
namespace script {
REGISTER_FST(VectorFst, KaldiLatticeArc);
REGISTER_FST(ConstFst, KaldiLatticeArc);
REGISTER_FST(EditFst, KaldiLatticeArc);
REGISTER_FST_CLASSES(KaldiLatticeArc);
REGISTER_FST_OPERATIONS(KaldiLatticeArc);
REGISTER_FST_FAR_OPERATIONS(KaldiLatticeArc);
}
}
| {
"content_hash": "26ef997c5ea46952e7deed7b2cf8f6d5",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 47,
"avg_line_length": 25.076923076923077,
"alnum_prop": 0.7791411042944786,
"repo_name": "opendcd/opendcd",
"id": "a4045c2aabde034414c0c2f459078292d770f2bb",
"size": "1269",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/bin/kaldi-lattice-arc-reg.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1122"
},
{
"name": "C++",
"bytes": "406346"
},
{
"name": "Makefile",
"bytes": "7024"
},
{
"name": "Python",
"bytes": "2157"
},
{
"name": "Shell",
"bytes": "15428"
}
],
"symlink_target": ""
} |
DROP MATERIALIZED VIEW IF EXISTS weightdurations CASCADE;
CREATE MATERIALIZED VIEW weightdurations as
-- This query extracts weights for adult ICU patients with start/stop times
-- if an admission weight is given, then this is assigned from intime to outtime
with wt_stg as
(
SELECT
c.icustay_id
, c.charttime
, case when c.itemid in (762,226512) then 'admit'
else 'daily' end as weight_type
-- TODO: eliminate obvious outliers if there is a reasonable weight
, c.valuenum as weight
FROM chartevents c
WHERE c.valuenum IS NOT NULL
AND c.itemid in
(
762,226512 -- Admit Wt
,763,224639 -- Daily Weight
)
AND c.valuenum != 0
-- exclude rows marked as error
AND c.error IS DISTINCT FROM 1
)
-- assign ascending row number
, wt_stg1 as
(
select
icustay_id
, charttime
, weight_type
, weight
, ROW_NUMBER() OVER (partition by icustay_id, weight_type order by charttime) as rn
from wt_stg
)
-- change charttime to starttime - for admit weight, we use ICU admission time
, wt_stg2 as
(
select
wt_stg1.icustay_id
, ie.intime, ie.outtime
, case when wt_stg1.weight_type = 'admit' and wt_stg1.rn = 1
then ie.intime - interval '2' hour
else wt_stg1.charttime end as starttime
, wt_stg1.weight
from icustays ie
inner join wt_stg1
on ie.icustay_id = wt_stg1.icustay_id
where not (weight_type = 'admit' and rn = 1)
)
, wt_stg3 as
(
select
icustay_id
, starttime
, coalesce(
LEAD(starttime) OVER (PARTITION BY icustay_id ORDER BY starttime),
outtime + interval '2' hour
) as endtime
, weight
from wt_stg2
)
-- this table is the start/stop times from admit/daily weight in charted data
, wt1 as
(
select
ie.icustay_id
, wt.starttime
, case when wt.icustay_id is null then null
else
coalesce(wt.endtime,
LEAD(wt.starttime) OVER (partition by ie.icustay_id order by wt.starttime),
-- we add a 2 hour "fuzziness" window
ie.outtime + interval '2' hour)
end as endtime
, wt.weight
from icustays ie
left join wt_stg3 wt
on ie.icustay_id = wt.icustay_id
)
-- if the intime for the patient is < the first charted daily weight
-- then we will have a "gap" at the start of their stay
-- to prevent this, we look for these gaps and backfill the first weight
-- this adds (153255-149657)=3598 rows, meaning this fix helps for up to 3598 icustay_id
, wt_fix as
(
select ie.icustay_id
-- we add a 2 hour "fuzziness" window
, ie.intime - interval '2' hour as starttime
, wt.starttime as endtime
, wt.weight
from icustays ie
inner join
-- the below subquery returns one row for each unique icustay_id
-- the row contains: the first starttime and the corresponding weight
(
select wt1.icustay_id, wt1.starttime, wt1.weight
from wt1
inner join
(
select icustay_id, min(Starttime) as starttime
from wt1
group by icustay_id
) wt2
on wt1.icustay_id = wt2.icustay_id
and wt1.starttime = wt2.starttime
) wt
on ie.icustay_id = wt.icustay_id
and ie.intime < wt.starttime
)
, wt2 as
(
select
wt1.icustay_id
, wt1.starttime
, wt1.endtime
, wt1.weight
from wt1
UNION
SELECT
wt_fix.icustay_id
, wt_fix.starttime
, wt_fix.endtime
, wt_fix.weight
from wt_fix
)
-- get more weights from echo - completes data for ~2500 patients
-- we only use echo data if there is *no* charted data
-- we impute the median echo weight for their entire ICU stay
-- only ~762 patients remain with no weight data
, echo_lag as
(
select
ie.icustay_id
, ie.intime, ie.outtime
, 0.453592*ec.weight as weight_echo
, ROW_NUMBER() OVER (PARTITION BY ie.icustay_id ORDER BY ec.charttime) as rn
, ec.charttime as starttime
, LEAD(ec.charttime) OVER (PARTITION BY ie.icustay_id ORDER BY ec.charttime) as endtime
from icustays ie
inner join echodata ec
on ie.hadm_id = ec.hadm_id
where ec.weight is not null
)
, echo_final as
(
select
el.icustay_id
, el.starttime
-- we add a 2 hour "fuzziness" window
, coalesce(el.endtime,el.outtime + interval '2' hour) as endtime
, weight_echo
from echo_lag el
UNION
-- if the starttime was later than ICU admission, back-propogate the weight
select
el.icustay_id
, el.intime - interval '2' hour as starttime
, el.starttime as endtime
, el.weight_echo
from echo_lag el
where el.rn = 1
and el.starttime > el.intime - interval '2' hour
)
select
wt2.icustay_id, wt2.starttime, wt2.endtime, wt2.weight
from wt2
UNION
-- only add echos if we have no charted weight data
select
ef.icustay_id, ef.starttime, ef.endtime, ef.weight_echo as weight
from echo_final ef
where ef.icustay_id not in (select distinct icustay_id from wt2)
order by icustay_id, starttime, endtime;
| {
"content_hash": "8c5e8cc8fdfd953414ee56c5d16fd964",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 91,
"avg_line_length": 28.548571428571428,
"alnum_prop": 0.6621297037630104,
"repo_name": "MIT-LCP/mimic-code-sharing",
"id": "51817da24d457f29ab0d476e5d3a52e8cd7f9ec2",
"size": "5154",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "concepts/durations/weight-durations.sql",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "132257"
},
{
"name": "Makefile",
"bytes": "2107"
},
{
"name": "PLSQL",
"bytes": "31482"
},
{
"name": "PLpgSQL",
"bytes": "26215"
},
{
"name": "Python",
"bytes": "16837"
},
{
"name": "Shell",
"bytes": "1851"
}
],
"symlink_target": ""
} |
package envoy_config_ratelimit_v3
import (
"bytes"
"errors"
"fmt"
"net"
"net/mail"
"net/url"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/golang/protobuf/ptypes"
v3 "github.com/datawire/ambassador/pkg/api/envoy/config/core/v3"
)
// ensure the imports are used
var (
_ = bytes.MinRead
_ = errors.New("")
_ = fmt.Print
_ = utf8.UTFMax
_ = (*regexp.Regexp)(nil)
_ = (*strings.Reader)(nil)
_ = net.IPv4len
_ = time.Duration(0)
_ = (*url.URL)(nil)
_ = (*mail.Address)(nil)
_ = ptypes.DynamicAny{}
_ = v3.ApiVersion(0)
)
// define the regex for a UUID once up-front
var _rls_uuidPattern = regexp.MustCompile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
// Validate checks the field values on RateLimitServiceConfig with the rules
// defined in the proto definition for this message. If any rules are
// violated, an error is returned.
func (m *RateLimitServiceConfig) Validate() error {
if m == nil {
return nil
}
if m.GetGrpcService() == nil {
return RateLimitServiceConfigValidationError{
field: "GrpcService",
reason: "value is required",
}
}
if v, ok := interface{}(m.GetGrpcService()).(interface{ Validate() error }); ok {
if err := v.Validate(); err != nil {
return RateLimitServiceConfigValidationError{
field: "GrpcService",
reason: "embedded message failed validation",
cause: err,
}
}
}
if _, ok := v3.ApiVersion_name[int32(m.GetTransportApiVersion())]; !ok {
return RateLimitServiceConfigValidationError{
field: "TransportApiVersion",
reason: "value must be one of the defined enum values",
}
}
// no validation rules for UseAlpha
return nil
}
// RateLimitServiceConfigValidationError is the validation error returned by
// RateLimitServiceConfig.Validate if the designated constraints aren't met.
type RateLimitServiceConfigValidationError struct {
field string
reason string
cause error
key bool
}
// Field function returns field value.
func (e RateLimitServiceConfigValidationError) Field() string { return e.field }
// Reason function returns reason value.
func (e RateLimitServiceConfigValidationError) Reason() string { return e.reason }
// Cause function returns cause value.
func (e RateLimitServiceConfigValidationError) Cause() error { return e.cause }
// Key function returns key value.
func (e RateLimitServiceConfigValidationError) Key() bool { return e.key }
// ErrorName returns error name.
func (e RateLimitServiceConfigValidationError) ErrorName() string {
return "RateLimitServiceConfigValidationError"
}
// Error satisfies the builtin error interface
func (e RateLimitServiceConfigValidationError) Error() string {
cause := ""
if e.cause != nil {
cause = fmt.Sprintf(" | caused by: %v", e.cause)
}
key := ""
if e.key {
key = "key for "
}
return fmt.Sprintf(
"invalid %sRateLimitServiceConfig.%s: %s%s",
key,
e.field,
e.reason,
cause)
}
var _ error = RateLimitServiceConfigValidationError{}
var _ interface {
Field() string
Reason() string
Key() bool
Cause() error
ErrorName() string
} = RateLimitServiceConfigValidationError{}
| {
"content_hash": "9aff38ee6c7553b34dd92c4c60f482dd",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 122,
"avg_line_length": 23.938931297709924,
"alnum_prop": 0.7044005102040817,
"repo_name": "datawire/ambassador",
"id": "3179765d0fc9fc956fcd1a1de6763eae4705cbce",
"size": "3239",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pkg/api/envoy/config/ratelimit/v3/rls.pb.validate.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "20990"
},
{
"name": "Go",
"bytes": "564752"
},
{
"name": "HTML",
"bytes": "25150"
},
{
"name": "JavaScript",
"bytes": "32368"
},
{
"name": "Makefile",
"bytes": "113905"
},
{
"name": "Python",
"bytes": "1158187"
},
{
"name": "Shell",
"bytes": "188832"
}
],
"symlink_target": ""
} |
package org.mybatis.generator.config;
/**
* This class holds constants useful in the XML and Java merging operations.
*
* @author Jeff Butler
*
*/
public class MergeConstants {
/**
* Utility class - no instances
*
*/
private MergeConstants() {
}
public static final String[] OLD_XML_ELEMENT_PREFIXES = { "ibatorgenerated_", "abatorgenerated_" }; //$NON-NLS-1$ //$NON-NLS-2$
public static final String NEW_ELEMENT_TAG = "@mbggenerated"; //$NON-NLS-1$
public static final String[] OLD_ELEMENT_TAGS = { "@ibatorgenerated", "@abatorgenerated", "@mbggenerated" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
| {
"content_hash": "0bbac0cf41a76b9a7956445614c5b2c7",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 151,
"avg_line_length": 27.208333333333332,
"alnum_prop": 0.6447166921898928,
"repo_name": "caixu23/mybatis-generator",
"id": "e8cb9119bb4d6f58fa134665ad1c5796ebe0d612",
"size": "1290",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/org/mybatis/generator/config/MergeConstants.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "215"
},
{
"name": "Java",
"bytes": "1371770"
}
],
"symlink_target": ""
} |
require 'gooddata'
describe GoodData::Model::ProjectBlueprint do
before(:each) do
@blueprint = GoodData::Model::ProjectBlueprint.from_json('./spec/data/blueprints/test_project_model_spec.json')
@invalid_blueprint = GoodData::Model::ProjectBlueprint.from_json('./spec/data/blueprints/invalid_blueprint.json')
@spec_blueprint = GoodData::Model::FromWire.from_wire(MultiJson.load(File.read('./spec/data/wire_models/model_view.json')))
@repos = @blueprint.find_dataset('dataset.repos')
@commits = @blueprint.find_dataset('dataset.commits')
end
describe '#title' do
it "should return the title" do
expect(@blueprint.title).to eq "RubyGem Dev Week test"
end
end
describe '#valid?' do
it 'valid blueprint should be marked as valid' do
expect(@blueprint.valid?).to eq true
end
it 'model should be invalid if it contains more than one anchor' do
bp = GoodData::Model::ProjectBlueprint.build("my_bp") do |p|
p.add_dataset("dataset.repos") do |d|
d.add_anchor("repo_id")
d.add_anchor("repo_id2")
d.add_fact("numbers")
d.add_attribute("name")
end
end
expect(bp.valid?).to be_falsey
errors = bp.validate
expect(errors.map {|x| x[:type]}.to_set).to eq [:attribute_without_label, :more_than_on_anchor].to_set
expect(errors.count).to eq 2
end
it 'model should be invalid if it contains no anchor' do
bp = GoodData::Model::ProjectBlueprint.build("my_bp") do |p|
p.add_dataset("dataset.repos") do |d|
d.add_fact("numbers")
d.add_attribute("name")
d.add_label('some_label', reference: 'name')
end
end
expect(bp.valid?).to be_falsey
errors = bp.validate
expect(errors.first[:type]).to eq :no_anchor
expect(errors.count).to eq 1
end
it 'model should be invalid if it has invalid gd data type' do
bp = GoodData::Model::ProjectBlueprint.build("my_bp") do |p|
p.add_dataset("dataset.repos") do |d|
d.add_anchor("attr.repository", label_id: 'label.repo.name', label_gd_data_type: "INTEGERX")
d.add_attribute("attr.attribute1", title: 'Some attribute')
d.add_label('label.attribute1.name', gd_data_type: "SOMEOTHER", reference: "attr.attribute1")
end
end
expect(bp.valid?).to be_falsey
errors = bp.validate
expect(errors.count).to eq 2
end
it 'model should be valid if it has int specified as integer and default should be decimal' do
bp = GoodData::Model::ProjectBlueprint.build("my_bp") do |p|
p.add_dataset("dataset.repos") do |d|
d.add_anchor("attr.repository")
d.add_label('label.repository.name', reference: 'attr.repository')
d.add_attribute("attr.attribute1", title: 'Some attribute')
d.add_label('label.attribute1.name', reference: 'attr.attribute1')
d.add_fact('some_numbers', gd_data_type: 'INT')
d.add_fact('more_numbers')
end
end
bp.valid?.should == true
errors = bp.validate
expect(errors.count).to eq 0
facts = bp.to_wire[:diffRequest][:targetModel][:projectModel][:datasets].first[:dataset][:facts]
expect(facts[0][:fact][:dataType]).to eq 'INT'
expect(facts[1][:fact][:dataType]).to eq 'DECIMAL(12,2)'
end
it 'invalid blueprint should be marked as invalid' do
expect(@invalid_blueprint.valid?).to eq false
end
end
describe '#validate' do
it 'valid blueprint should give you empty array of errors' do
expect(@blueprint.validate).to be_empty
end
it 'invalid blueprint should give you list of violating references' do
errors = @invalid_blueprint.validate
expect(errors.size).to eq 1
expect(errors).to eq([{
:type=>:wrong_label_reference,
:label=>"some_label_id",
:wrong_reference=>"attr.repos.repo_id ERROR"
}])
end
it 'invalid label is caught correctly' do
bp = GoodData::Model::ProjectBlueprint.build("my_bp") do |p|
p.add_dataset("dataset.repos") do |d|
d.add_anchor("attr.repository", label_id: 'label.repo.name')
d.add_attribute("attr.attribute1", title: 'Some attribute')
d.add_label('label.attribute1.name', reference: 'attr.attribute23123')
d.add_label('label.attribute1.ssn', reference: 'attr.attribute23123')
d.add_fact('some_numbers', gd_data_type: 'INT')
d.add_fact('more_numbers')
end
end
expect(bp.valid?).to be_falsey
errors = bp.validate
expect(errors.count).to eq 3
expect(errors).to eq [
{
:type=>:wrong_label_reference,
:label=>"label.attribute1.name",
:wrong_reference=>"attr.attribute23123"
},
{
:type=>:wrong_label_reference,
:label=>"label.attribute1.ssn",
:wrong_reference=>"attr.attribute23123"
},
{
:type=>:attribute_without_label,
:attribute=>"attr.attribute1"
}
]
end
end
describe '#remove_dataset!' do
it "should be able to remove dataset by name" do
expect(@blueprint.datasets.count).to eq 3
bp = @blueprint.remove_dataset!('dataset.repos')
expect(bp).to be_kind_of(GoodData::Model::ProjectBlueprint)
expect(@blueprint.datasets.count).to eq 2
end
it "should be able to remove dataset by reference" do
expect(@blueprint.datasets.count).to eq 3
dataset = @blueprint.find_dataset('dataset.repos')
bp = @blueprint.remove_dataset!(dataset)
expect(bp).to be_kind_of(GoodData::Model::ProjectBlueprint)
expect(@blueprint.datasets.count).to eq 2
end
it "should be able to remove dataset by name" do
expect(@blueprint.datasets.count).to eq 3
bp = GoodData::Model::ProjectBlueprint.remove_dataset!(@blueprint, 'dataset.repos')
expect(bp).to be_kind_of(Hash)
expect(@blueprint.datasets.count).to eq 2
end
it "should be able to remove dataset by reference" do
expect(@blueprint.datasets.count).to eq 3
dataset = @blueprint.find_dataset('dataset.repos')
bp = GoodData::Model::ProjectBlueprint.remove_dataset!(@blueprint, dataset)
expect(bp).to be_kind_of(Hash)
expect(@blueprint.datasets.count).to eq 2
end
end
describe '#references' do
it 'references return empty array if there is no reference' do
refs = @blueprint.find_dataset('dataset.devs').references
expect(refs).to be_empty
end
end
describe '#find_dataset' do
it 'should be able to get dataset by identifier' do
ds = @blueprint.find_dataset('dataset.devs')
expect(ds.id).to eq 'dataset.devs'
expect(ds).to be_kind_of(GoodData::Model::DatasetBlueprint)
end
it 'should throw an error if the dataset with a given name could not be found' do
expect { @blueprint.find_dataset('nonexisting_dataset') }.to raise_error
end
it "should be pssible to find a dataset using dataset" do
ds = @blueprint.find_dataset('dataset.devs')
sds = @blueprint.find_dataset(ds)
expect(ds).to eq sds
end
end
describe '#to_blueprint' do
it "should be possible to create ProjectBlueprint from SchemaBuilder" do
builder = GoodData::Model::SchemaBuilder.create("stuff") do |d|
d.add_anchor("anchor_id")
d.add_attribute("id", title: "My Id")
d.add_label("label", reference: "id")
d.add_fact("amount", title: "Amount")
end
bp2 = builder.to_blueprint
expect(bp2.valid?).to eq true
end
it "should be possible to create ProjectBlueprint from SchemaBuilder" do
builder = GoodData::Model::SchemaBuilder.create("stuff") do |d|
d.add_anchor("anchor_id")
d.add_attribute("id", title: "My Id")
d.add_label("label", reference: "id")
d.add_fact("amount", title: "Amount")
end
bp1 = GoodData::Model::ProjectBlueprint.new(builder)
expect(bp1.valid?).to eq true
end
end
describe '#dataset?' do
it 'should be able to tell me if ceratain dataset by name is in the blueprint' do
expect(@blueprint.dataset?('dataset.devs')).to be_truthy
end
end
describe '#anchor?' do
it 'should tell you it has anchor when it does' do
expect(@repos.anchor?).to eq true
end
end
describe '#anchor' do
it 'should tell you anchor does have labels' do
expect(@commits.anchor.labels.count).to eq 0
end
it 'anchor should have labels' do
expect(@repos.anchor.labels.first.id).to eq 'some_label_id'
end
end
describe '#attributes' do
it 'attribute should have labels' do
expect(@repos.attributes.first.labels.first.id).to eq 'some_attr_label_id'
end
it "should return attributes form all datasets" do
expect(@blueprint.attributes.count).to eq 1
end
it 'should be able to grab attribute' do
expect(@repos.labels.size).to eq 2
expect(@repos.labels('some_attr_label_id').attribute).to eq @repos.attributes('some_attr_id')
expect(@repos.labels('some_label_id').attribute.id).to eq 'attr.repos.repo_id'
end
end
describe '#facts' do
it 'commits should have one fact' do
expect(@commits.facts.size).to eq 1
end
it 'commits should have one fact' do
expect(@repos.facts.size).to eq 0
end
it "should return facts form all datasets" do
expect(@blueprint.facts.count).to eq 1
end
end
describe '#labels' do
it 'Anchor on repos should have a label' do
expect(@repos.anchor.labels.size).to eq 1
end
it 'should not have a label for a dataset without anchor with label' do
expect(@commits.anchor.labels).to eq []
end
it "should return labels form all datasets" do
expect(@blueprint.labels.count).to eq 4
end
end
describe '#attributes_and_anchors' do
it "should return labels form all datasets" do
expect(@blueprint.attributes_and_anchors.count).to eq 4
end
end
describe '#merge' do
it "should be able to merge models without mutating the original" do
additional_blueprint = GoodData::Model::ProjectBlueprint.from_json("./spec/data/blueprints/additional_dataset_module.json")
expect(@blueprint.datasets.count).to eq 3
new_bp = @blueprint.merge(additional_blueprint)
expect(@blueprint.datasets.count).to eq 3
expect(new_bp.datasets.count).to eq 4
end
it "should perform merge in associative matter. Order should not matter." do
a = GoodData::Model::ProjectBlueprint.build("p") do |p|
p.add_date_dimension("updated_on")
p.add_dataset('stuff') do |d|
d.add_anchor('stuff_id')
d.add_label('name', reference: 'stuff_id')
d.add_date('updated_on')
end
end
b = GoodData::Model::ProjectBlueprint.build("p") do |p|
p.add_date_dimension("created_on")
p.add_dataset('stuff') do |d|
d.add_attribute('attr_id')
d.add_label('attr_name', reference: 'attr_id')
d.add_date('created_on')
end
end
# those two are the same. Notice that we have made the titles the same
# Merging titles is not associative
a_b = a.merge(b)
b_a = b.merge(a)
expect(a_b.valid?).to eq true
expect(b_a.valid?).to eq true
expect(b_a).to eq a_b
end
it "should perform merge in associative matter. Order should not matter." do
a = GoodData::Model::ProjectBlueprint.build("p") do |p|
p.add_date_dimension("updated_on")
p.add_dataset('stuff') do |d|
d.add_anchor('stuff_id')
d.add_label('name', reference: 'stuff_id')
d.add_date('updated_on')
end
end
b = GoodData::Model::ProjectBlueprint.build("p") do |p|
p.add_date_dimension("created_on")
p.add_dataset('stuff') do |d|
d.add_attribute('attr_id')
d.add_label('attr_name', reference: 'attr_id')
d.add_date('created_on')
end
end
# those two are the same. Notice that we have made the titles the same
# Merging titles is not associative
a_b = a.merge(b)
b_a = b.merge(a)
expect(a_b.valid?).to eq true
expect(b_a.valid?).to eq true
expect(b_a).to eq a_b
end
it "should fail if unable to merge date dimensions (they are different)." do
a = GoodData::Model::ProjectBlueprint.build("p") do |p|
p.add_date_dimension("created_on", title: 'title A')
p.add_dataset('stuff') do |d|
d.add_anchor('stuff_id')
d.add_label('name', reference: 'stuff_id')
d.add_date('created_on')
end
end
b = GoodData::Model::ProjectBlueprint.build("p") do |p|
p.add_date_dimension("created_on", title: 'title B')
p.add_dataset('stuff') do |d|
d.add_attribute('attr_id')
d.add_label('attr_name', reference: 'attr_id')
d.add_date('created_on')
end
end
expect {
c = a.merge(b)
}.to raise_exception 'Unable to merge date dimensions created_on with defintion {:type=>:date_dimension, :urn=>nil, :id=>"created_on", :title=>"title B"} with {:type=>:date_dimension, :urn=>nil, :id=>"created_on", :title=>"title A"}'
end
end
describe '#merge!' do
it "should be able to merge models" do
additional_blueprint = GoodData::Model::ProjectBlueprint.from_json("./spec/data/blueprints/additional_dataset_module.json")
expect(@blueprint.datasets.count).to eq 3
@blueprint.merge!(additional_blueprint)
expect(@blueprint.datasets.count).to eq 4
end
end
it "should be able to add datasets on the fly" do
builder = GoodData::Model::SchemaBuilder.new("stuff") do |d|
d.add_attribute("id", title: "My Id")
d.add_fact("amount", title: "Amount")
end
dataset = builder.to_blueprint
expect(@blueprint.datasets.count).to eq 3
@blueprint.add_dataset!(dataset)
expect(@blueprint.datasets.count).to eq 4
end
it "should be able to serialize itself to a hash" do
ser = @blueprint.to_hash
ser.is_a?(Hash)
expect(ser.keys).to eq [:title, :datasets, :date_dimensions]
end
it "should be able to tell you whether a dataset is referencing any others including date dimensions" do
d = @blueprint.datasets('dataset.commits')
referenced_datasets = @blueprint.referenced_by(d)
expect(referenced_datasets.count).to eq 3
end
it "should be able to find star centers - datasets that are not referenced by any other - these are typical fact tables" do
centers = @blueprint.find_star_centers
expect(centers.count).to eq 1
expect(centers.first.id).to eq 'dataset.commits'
end
it "should be able to return all attributes or anchors that can break metrics computed in the context of given dataset" do
commits = @blueprint.datasets('dataset.commits')
expect(commits.broken_by.count).to eq 3
expect(commits.broken_by.map(&:id)).to eq ["attr.devs.dev_id", "some_attr_id", "attr.repos.repo_id"]
end
it 'blueprint can be set without date reference and default format is set' do
bp = GoodData::Model::ProjectBlueprint.build("my_bp") do |p|
p.add_date_dimension("committed_on")
p.add_dataset("dataset.repos") do |d|
d.add_anchor("attr.repository")
d.add_label('label.repo.name')
d.add_attribute("attr.attribute1", title: 'Some attribute')
d.add_label('label.attribute1.name', reference: 'attr.attribute1')
d.add_label('label.attribute1.ssn', reference: 'attr.attribute1')
d.add_fact('some_numbers', gd_data_type: 'INT')
d.add_fact('more_numbers')
d.add_date('opportunity_comitted', dataset: 'committed_on')
end
end
expect(bp.datasets.flat_map { |d| d.find_columns_by_type(:date) }.map { |a| a.format }).to eq [GoodData::Model::DEFAULT_DATE_FORMAT]
end
it 'blueprint can be set with explicit date' do
bp = GoodData::Model::ProjectBlueprint.build("my_bp") do |p|
p.add_date_dimension("committed_on")
p.add_dataset("dataset.repos") do |d|
d.add_anchor("attr.repository", label_id: 'label.repo.name')
d.add_attribute("attr.attribute1")
d.add_label('label.attribute1.name', title: 'Some attribute', reference: 'attr.attribute1')
d.add_label('label.attribute1.ssn', reference: 'attr.attribute1')
d.add_fact('some_numbers', gd_data_type: 'INT')
d.add_fact('more_numbers')
d.add_date('opportunity_comitted', dataset: 'committed_on', format: 'yyyy/MM/dd')
end
end
expect(bp.valid?).to be_truthy
expect(bp.datasets.flat_map { |d| d.find_columns_by_type(:date) }.map { |a| a.format }).to eq ['yyyy/MM/dd']
end
describe '#remove' do
it 'can remove the anchor' do
bp = GoodData::Model::ProjectBlueprint.build("my_bp") do |p|
p.add_dataset("dataset.repos") do |d|
d.add_anchor("attr.repository", label_id: 'label.repo.name')
d.add_label('label.repository.name', title: 'Some attribute', reference: 'attr.repository')
end
end
expect(bp.datasets('dataset.repos').anchor.labels.count).to eq 1
bp.datasets('dataset.repos').anchor.remove!
expect(bp.datasets('dataset.repos').anchor.labels.count).to eq 0
end
end
describe '#move!' do
it 'can move attribute around' do
expect(@blueprint.datasets('dataset.repos').fields.count).to eq 4
expect(@blueprint.datasets('dataset.commits').fields.count).to eq 5
attr_before = @blueprint.datasets('dataset.repos').attributes('some_attr_id')
expect(attr_before).to_not be_nil
expect(@blueprint.datasets('dataset.commits').attributes('some_attr_id')).to be_nil
expect(attr_before.labels.first.dataset_blueprint.id).to eq 'dataset.repos'
@blueprint.move!('some_attr_id', 'dataset.repos', 'dataset.commits')
attr_after = @blueprint.datasets('dataset.commits').attributes('some_attr_id')
expect(@blueprint.datasets('dataset.repos').fields.count).to eq 2
expect(@blueprint.datasets('dataset.commits').fields.count).to eq 7
expect(@blueprint.datasets('dataset.repos').attributes('some_attr_id')).to be_nil
expect(attr_after).to_not be_nil
expect(attr_after.labels.first.dataset_blueprint.id).to eq 'dataset.commits'
end
it 'can move fact around' do
@blueprint.move!('fact.commits.lines_changed', 'dataset.commits', 'dataset.repos')
expect(@blueprint.datasets('dataset.commits').facts.count).to eq 0
expect(@blueprint.datasets('dataset.repos').facts.count).to eq 1
end
it 'crashes gracefully when nonexistent field is being moved' do
expect {
@blueprint.move!('nonexistent_field', 'dataset.commits', 'dataset.repos')
}.to raise_exception 'Column nonexistent_field cannot be found in dataset dataset.commits'
end
it 'crashes gracefully when datasets does not exist' do
expect {
@blueprint.move!('nonexistent_field', 'dataset.A', 'dataset.repos')
}.to raise_exception 'Dataset "dataset.A" could not be found'
end
it 'crashes gracefully when datasets does not exist' do
expect {
@blueprint.move!('nonexistent_field', 'dataset.commits', 'dataset.B')
}.to raise_exception 'Dataset "dataset.B" could not be found'
end
end
it 'should be able to refactor facts from attributes' do
blueprint = GoodData::Model::ProjectBlueprint.build("my_bp") do |p|
p.add_dataset('opportunities') do |d|
d.add_anchor('opportunities.id')
d.add_fact('opportunities.age')
d.add_fact('opportunities.amount')
d.add_attribute('opportunities.name')
d.add_label('label.opportunities.name', reference: 'opportunities.name')
d.add_attribute('opportunities.region')
d.add_label('label.opportunities.region', reference: 'opportunities.region')
d.add_reference('user_id', dataset: 'users')
d.add_reference('account_id', dataset: 'accounts')
end
p.add_dataset('users') do |d|
d.add_anchor('users.id')
d.add_attribute('users.name')
d.add_label('label.users.name', reference: 'users.name')
end
p.add_dataset('accounts') do |d|
d.add_anchor('accounts.id')
d.add_attribute('accounts.name')
d.add_label('label.accounts.region', reference: 'accounts.name')
end
end
refactored = GoodData::Model::ProjectBlueprint.build("my_bp") do |p|
p.add_dataset('opportunities') do |d|
d.add_anchor('opportunities.id')
d.add_fact('opportunities.age')
d.add_fact('opportunities.amount')
d.add_reference('user_id', dataset: 'users')
d.add_reference('accounts')
d.add_reference('accounts')
d.add_reference('opportunities_dim')
end
p.add_dataset('opportunities_dim') do |d|
d.add_anchor('vymysli_id')
d.add_label('label.vymysli_id', reference: 'vymysli_id')
d.add_attribute('opportunities.name')
d.add_label('label.opportunities.name', reference: 'opportunities.name')
d.add_attribute('opportunities.region')
d.add_label('label.opportunities.region', reference: 'opportunities.region')
end
p.add_dataset('users') do |d|
d.add_anchor('users.id')
d.add_attribute('users.name')
d.add_label('label.users.name', reference: 'users.name')
end
p.add_dataset('accounts') do |d|
d.add_anchor('accounts.id')
d.add_attribute('accounts.name')
d.add_label('label.accounts.region', reference: 'accounts.name')
end
end
expect(blueprint.refactor_split_df('opportunities')).to eq refactored
end
it 'should be able to refactor facts as a split into 2 datasets' do
blueprint = GoodData::Model::ProjectBlueprint.build("my_bp") do |p|
p.add_dataset('opportunities') do |d|
d.add_anchor('opportunities.id')
d.add_fact('opportunities.age')
d.add_fact('opportunities.amount')
d.add_attribute('opportunities.name')
d.add_label('label.opportunities.name', reference: 'opportunities.name')
d.add_attribute('opportunities.region')
d.add_label('label.opportunities.region', reference: 'opportunities.region')
d.add_reference('user_id', dataset: 'users')
d.add_reference('account_id', dataset: 'accounts')
end
p.add_dataset('users') do |d|
d.add_anchor('users.id')
d.add_attribute('users.name')
d.add_label('label.users.name', reference: 'users.name')
end
p.add_dataset('accounts') do |d|
d.add_anchor('accounts.id')
d.add_attribute('accounts.name')
d.add_label('label.accounts.region', reference: 'accounts.name')
end
end
refactored = GoodData::Model::ProjectBlueprint.build("my_bp") do |p|
p.add_dataset('opportunities') do |d|
d.add_anchor('opportunities.id')
d.add_fact('opportunities.amount')
d.add_attribute('opportunities.name')
d.add_label('label.opportunities.name', reference: 'opportunities.name')
d.add_attribute('opportunities.region')
d.add_label('label.opportunities.region', reference: 'opportunities.region')
d.add_reference('user_id', dataset: 'users')
d.add_reference('account_id', dataset: 'accounts')
end
p.add_dataset('users') do |d|
d.add_anchor('users.id')
d.add_attribute('users.name')
d.add_label('label.users.name', reference: 'users.name')
end
p.add_dataset('accounts') do |d|
d.add_anchor('accounts.id')
d.add_attribute('accounts.name')
d.add_label('label.accounts.region', reference: 'accounts.name')
end
p.add_dataset('opportunities_age_fact') do |d|
d.add_anchor('opportunities_age_fact.id')
d.add_fact('opportunities.age')
d.add_reference('user_id', dataset: 'users')
d.add_reference('account_id', dataset: 'accounts')
end
end
col_names = ['opportunities.age']
# that should be possible to express with #refactor_split_facts
expect(blueprint.refactor_split_facts('opportunities', col_names, 'opportunities_age_fact')).to eq refactored
end
end
| {
"content_hash": "575c6082b858e1b62328990047ae7d33",
"timestamp": "",
"source": "github",
"line_count": 642,
"max_line_length": 239,
"avg_line_length": 38.04828660436137,
"alnum_prop": 0.6387603880951406,
"repo_name": "korczis/app_store",
"id": "5766cf88d324a10acfea0b67f50b1c2a9abff3d8",
"size": "24445",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "apps/user_filters_brick/vendor/gooddata-0.6.20/spec/unit/models/blueprint/project_blueprint_spec.rb",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "5089"
},
{
"name": "HTML",
"bytes": "7931"
},
{
"name": "JavaScript",
"bytes": "1326276"
},
{
"name": "Ruby",
"bytes": "78091"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
namespace Xamarin_PCL78
{
public class App
{
public static Page GetMainPage()
{
return new NavigationPage(new MainPage());
}
}
}
| {
"content_hash": "71b8fea725358db8547974dfc47e23cb",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 54,
"avg_line_length": 16.88235294117647,
"alnum_prop": 0.6376306620209059,
"repo_name": "moonmile/FSharp.Data.PCL",
"id": "9d90c3e7507c5b855566027e724d251640fb65c5",
"size": "289",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/TestApps/Xamarin_PCL78/Xamarin_PCL78/App.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "82843"
},
{
"name": "CSS",
"bytes": "529"
},
{
"name": "F#",
"bytes": "1085985"
},
{
"name": "Shell",
"bytes": "1361"
}
],
"symlink_target": ""
} |
package android.support.v4.content;
import android.content.Context;
import android.graphics.drawable.Drawable;
import java.io.File;
class ContextCompatApi21
{
ContextCompatApi21()
{
}
public static File getCodeCacheDir(Context context)
{
return context.getCodeCacheDir();
}
public static Drawable getDrawable(Context context, int i)
{
return context.getDrawable(i);
}
public static File getNoBackupFilesDir(Context context)
{
return context.getNoBackupFilesDir();
}
}
| {
"content_hash": "608cf3320c9fb5bae992f68efb1a23da",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 62,
"avg_line_length": 19.5,
"alnum_prop": 0.6941391941391941,
"repo_name": "Hamz-a/MyCTFWriteUps",
"id": "376db48e44ae14c82b53be25ff2967bf7b74c360",
"size": "721",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "seccon_2015/Reverse-Engineering Android APK 1/files/source/src/android/support/v4/content/ContextCompatApi21.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "5341"
},
{
"name": "Java",
"bytes": "4932411"
},
{
"name": "PHP",
"bytes": "2945"
},
{
"name": "Python",
"bytes": "3392"
}
],
"symlink_target": ""
} |
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Error** | [**Error**](Error.md) | | [optional]
**Metadata** | [**ResponseMetadata**](ResponseMetadata.md) | | [optional]
**Success** | **bool?** | Indicates if API call was successful | [optional]
**Warning** | [**Warning**](Warning.md) | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
| {
"content_hash": "174fa2126294b8a54e99762992b22137",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 161,
"avg_line_length": 52.1,
"alnum_prop": 0.564299424184261,
"repo_name": "UltraCart/rest_api_v2_sdk_csharp",
"id": "66d5a960a1e83b8a25066b0c980947573dfd653f",
"size": "597",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/EmailFlowBackPopulateResponse.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "951"
},
{
"name": "C#",
"bytes": "11743806"
},
{
"name": "Shell",
"bytes": "4486"
}
],
"symlink_target": ""
} |
<link rel="stylesheet" href="<?php echo baseUrl ?>assets/bower/trumbowyg/dist/ui/trumbowyg.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"></script>
<script src="<?php echo baseUrl ?>assets/bower/trumbowyg/dist/trumbowyg.min.js"></script>
<div id="panel" class="panel panel-primary">
<div class="panel-heading" style="background-color: red">
<h3 class="panel-title text-muted"><i class="fa fa-university fa-2x"></i> INGRESAR SOLCIITUD</h3>
</div>
<br>
<div class="panel-body">
<form action="<?php echo baseUrlRole() ?>centrosSolicitudes" method="POST">
<?php echo Token() ?>
<input type="text" name="id_ubch" value="<?php echo $id_ubch ?>">
<div class="row">
<div class="col-lg-4">
<div class="form-group">
<select id="municipioSelect" class="form-control" name="tipo" required/>
<option>TIPO DE SOLICITUD</option>
<?php foreach ($tipo as $key => $t): ?>
<option value="<?php echo $t->id_tipo_solicitud ?>"><?php echo $t->nombre ?></option>
<?php endforeach ?>
</select>
</div>
</div>
</div>
<textarea name="observacion" class="editor">
</textarea>
<div class="col-lg-12">
<button onclick="enviar()" id="botonSubmit" type="submit" class="btn btn-lg btn-danger pull-right"><i class="fa fa-save fa-2x"></i></button>
</div>
<br>
</form>
</div>
<script>
$('.editor').trumbowyg({
lang: 'es'
});
</script> | {
"content_hash": "e45c983c21c4899f9af6274b245e663b",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 150,
"avg_line_length": 42.37837837837838,
"alnum_prop": 0.5924744897959183,
"repo_name": "dexternidia/redcomand",
"id": "d26ba6c1fa6a9d0db2b09168aa876822bf42499c",
"size": "1568",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/clp/views/centrosSolicitudes/create.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "370377"
},
{
"name": "CoffeeScript",
"bytes": "73"
},
{
"name": "HTML",
"bytes": "302223"
},
{
"name": "JavaScript",
"bytes": "1885966"
},
{
"name": "PHP",
"bytes": "1280649"
},
{
"name": "PowerShell",
"bytes": "471"
},
{
"name": "Python",
"bytes": "3523"
},
{
"name": "Ruby",
"bytes": "6836"
},
{
"name": "Shell",
"bytes": "36450"
}
],
"symlink_target": ""
} |
package com.facebook.buck.android;
import com.facebook.buck.cxx.CxxPlatformUtils;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.rules.AbstractNodeBuilder;
import com.facebook.buck.rules.CommandTool;
import com.facebook.buck.rules.PathSourcePath;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.testutil.FakeProjectFilesystem;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedSet;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
public class NdkLibraryBuilder
extends AbstractNodeBuilder<NdkLibraryDescription.Arg, NdkLibraryDescription, NdkLibrary> {
private static final NdkCxxPlatform DEFAULT_NDK_PLATFORM =
NdkCxxPlatform.builder()
.setCxxPlatform(CxxPlatformUtils.DEFAULT_PLATFORM)
.setCxxRuntime(NdkCxxPlatforms.CxxRuntime.GNUSTL)
.setCxxSharedRuntimePath(Paths.get("runtime"))
.setObjdump(new CommandTool.Builder().addArg("objdump").build())
.build();
private static final ImmutableMap<NdkCxxPlatforms.TargetCpuType, NdkCxxPlatform> NDK_PLATFORMS =
ImmutableMap.<NdkCxxPlatforms.TargetCpuType, NdkCxxPlatform>builder()
.put(NdkCxxPlatforms.TargetCpuType.ARM, DEFAULT_NDK_PLATFORM)
.put(NdkCxxPlatforms.TargetCpuType.ARMV7, DEFAULT_NDK_PLATFORM)
.put(NdkCxxPlatforms.TargetCpuType.X86, DEFAULT_NDK_PLATFORM)
.build();
public NdkLibraryBuilder(BuildTarget target) {
this(target, new FakeProjectFilesystem());
}
public NdkLibraryBuilder(BuildTarget target, ProjectFilesystem filesystem) {
super(
new NdkLibraryDescription(Optional.empty(), NDK_PLATFORMS) {
@Override
protected ImmutableSortedSet<SourcePath> findSources(
ProjectFilesystem filesystem,
Path buildRulePath) {
return ImmutableSortedSet.of(
new PathSourcePath(filesystem, buildRulePath.resolve("Android.mk")));
}
},
target,
filesystem);
}
public NdkLibraryBuilder addDep(BuildTarget target) {
arg.deps = amend(arg.deps, target);
return this;
}
public NdkLibraryBuilder setFlags(Iterable<String> flags) {
arg.flags = ImmutableList.copyOf(flags);
return this;
}
public NdkLibraryBuilder setIsAsset(boolean isAsset) {
arg.isAsset = Optional.of(isAsset);
return this;
}
}
| {
"content_hash": "bf4d89420a05e5c39488ca9d49f818ed",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 98,
"avg_line_length": 35.31944444444444,
"alnum_prop": 0.7333857648446717,
"repo_name": "grumpyjames/buck",
"id": "6e75b7ddf3728577f42d2b1575449aa7c28407c7",
"size": "3148",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "test/com/facebook/buck/android/NdkLibraryBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "579"
},
{
"name": "Batchfile",
"bytes": "726"
},
{
"name": "C",
"bytes": "248531"
},
{
"name": "C#",
"bytes": "237"
},
{
"name": "C++",
"bytes": "6074"
},
{
"name": "CSS",
"bytes": "54863"
},
{
"name": "D",
"bytes": "1017"
},
{
"name": "Go",
"bytes": "14733"
},
{
"name": "Groff",
"bytes": "440"
},
{
"name": "Groovy",
"bytes": "3362"
},
{
"name": "HTML",
"bytes": "5353"
},
{
"name": "Haskell",
"bytes": "764"
},
{
"name": "IDL",
"bytes": "128"
},
{
"name": "Java",
"bytes": "14327718"
},
{
"name": "JavaScript",
"bytes": "931960"
},
{
"name": "Lex",
"bytes": "2591"
},
{
"name": "Makefile",
"bytes": "1791"
},
{
"name": "Matlab",
"bytes": "47"
},
{
"name": "OCaml",
"bytes": "3060"
},
{
"name": "Objective-C",
"bytes": "124321"
},
{
"name": "Objective-C++",
"bytes": "34"
},
{
"name": "PowerShell",
"bytes": "244"
},
{
"name": "Python",
"bytes": "388781"
},
{
"name": "Rust",
"bytes": "938"
},
{
"name": "Scala",
"bytes": "898"
},
{
"name": "Shell",
"bytes": "35303"
},
{
"name": "Smalltalk",
"bytes": "3653"
},
{
"name": "Standard ML",
"bytes": "15"
},
{
"name": "Swift",
"bytes": "3735"
},
{
"name": "Thrift",
"bytes": "2452"
},
{
"name": "Yacc",
"bytes": "323"
}
],
"symlink_target": ""
} |
<?php
/**
* To unite the 5 parts of Kaspay API call
*/
class Kaspay_api_parameter {
/**
* @var string GET/POST/PUT/DELETE
*/
protected $verb;
/**
* @var string Full URL
*/
protected $url;
/**
* @var string User's identifier
*/
protected $uaccount;
/**
* @var int UNIX timestamp
*/
protected $timestamp;
/**
* @var string binary string
*/
protected $data;
public function __construct($verb, $url, $uaccount, $timestamp, $data)
{
$this->verb = $verb;
$this->url = $url;
$this->uaccount = $uaccount;
$this->timestamp = $timestamp;
$this->data = $data;
}
public function get_verb()
{
return $this->verb;
}
public function get_url()
{
return $this->url;
}
public function get_uaccount()
{
return $this->uaccount;
}
public function get_timestamp()
{
return $this->timestamp;
}
public function get_data()
{
return $this->data;
}
} | {
"content_hash": "1cdfe5b4391fad2ff84a4d4937d6bc0e",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 71,
"avg_line_length": 14.770491803278688,
"alnum_prop": 0.6137624861265261,
"repo_name": "kaspay/kaspay-php",
"id": "a07cc566e26283f46168b838ec53c32fc8204b3b",
"size": "901",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/kaspay_api_parameter.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "39528"
}
],
"symlink_target": ""
} |
var baseURL = window.location.protocol + "//" + window.location.host + "/";
/**
* prevent console.log errors on older browsers
*/
(function() {
var method;
var noop = function () {};
var methods = [
"assert", "clear", "count", "debug", "dir", "dirxml", "error",
"exception", "group", "groupCollapsed", "groupEnd", "info", "log",
"markTimeline", "profile", "profileEnd", "table", "time", "timeEnd",
"timeStamp", "trace", "warn"
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
if (!console[method]) {
console[method] = noop;
}
}
}());
/**
* determines if touch is available
* NOTE: This is not allways accurate
*/
var supportsTouch;
var supportsTransitions;
var supportsTransforms;
var isIE;
var transitionEndString = "webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd";
$(document).ready(function() {
var userAgent = window.navigator.userAgent;
userAgent = userAgent.toLowerCase();
// touch device detection
supportsTouch = "ontouchend" in document;
if (supportsTouch) {
$("html").addClass("touch-supported");
} else {
$("html").addClass("no-touch-supported");
}
supportsTransitions = $("html").hasClass("csstransitions");
supportsTransforms = $("html").hasClass("csstransforms");
isIE = /(msie) ([\w.]+)/.exec(userAgent);
if (isIE) {
$("html").addClass("ie");
$("img[src$='.png']").each(function() {
this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + this.src + ",sizingMethod='scale')";
});
}
var isAndroid = userAgent.indexOf("android") > -1;
if(isAndroid) {
$("html").addClass("is-android");
}
var game = new Game();
}); | {
"content_hash": "6a76a1860eb66b8aa44b0f337c3a365b",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 128,
"avg_line_length": 26.614285714285714,
"alnum_prop": 0.6065485775630703,
"repo_name": "OxiAction/softwprakt",
"id": "c4b19b1bfe2bd2ecfeddb12e152d738ce5fd8ce0",
"size": "1863",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "files/js/Main.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "414"
},
{
"name": "HTML",
"bytes": "2378"
},
{
"name": "JavaScript",
"bytes": "17000"
}
],
"symlink_target": ""
} |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_Protocol_deviation_form extends CI_Model {
function __construct() {
parent::__construct();
}
function all() {
$this->db->select('protocol_deviation_form.*');
$this->db->from('protocol_deviation_form');
#$this->db->join('perfil', 'usuario.perfil_id = perfil.id', 'left');
$query = $this->db->get();
return $query->result();
}
function allFiltered($field, $value) {
$this->db->select('protocol_deviation_form.*');
$this->db->from('protocol_deviation_form');
#$this->db->join('perfil', 'usuario.perfil_id = perfil.id', 'left');
$this->db->like($field, $value);
$query = $this->db->get();
return $query->result();
}
function allWhere($field, $value) {
$this->db->select('protocol_deviation_form.*');
$this->db->from('protocol_deviation_form');
$this->db->where($field, $value);
$query = $this->db->get();
return $query->result();
}
function find($id) {
$this->db->where('id', $id);
return $this->db->get('protocol_deviation_form')->row();
}
function insert($registro) {
$this->db->set($registro);
$this->db->insert('protocol_deviation_form');
}
function update($registro) {
$this->db->set($registro);
$this->db->where('id', $registro['id']);
$this->db->update('protocol_deviation_form');
}
} | {
"content_hash": "927f166111b2d1a8b5cb62cb16a74f8a",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 76,
"avg_line_length": 29.28301886792453,
"alnum_prop": 0.541881443298969,
"repo_name": "DeathEmpire/Subject-Management-Demo",
"id": "1965b7c3e5eeeb9b3e089694aa9c3592edb9f0b3",
"size": "1552",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/models/model_protocol_deviation_form.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "719"
},
{
"name": "CSS",
"bytes": "163749"
},
{
"name": "HTML",
"bytes": "82838"
},
{
"name": "JavaScript",
"bytes": "214266"
},
{
"name": "PHP",
"bytes": "7935894"
}
],
"symlink_target": ""
} |
/*
官方文档:https://work.weixin.qq.com/api/doc#13473
*/
using Senparc.CO2NET.Helpers.Serializers;
using Senparc.NeuChar;
using Senparc.Weixin.CommonAPIs;
using Senparc.Weixin.Entities;
using Senparc.Weixin.Work.AdvancedAPIs.External;
using Senparc.Weixin.Work.AdvancedAPIs.External.ExternalJson;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Senparc.Weixin.Work.AdvancedAPIs
{
/// <summary>
/// 外部联系人管理
/// </summary>
[NcApiBind(NeuChar.PlatformType.WeChat_Work, true)]
public static class ExternalApi
{
#region 同步方法
/// <summary>
/// 离职成员的外部联系人再分配
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="ExternalUserId"></param>
/// <param name="handoverUserId"></param>
/// <param name="takeoverUserId"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static WorkJsonResult TransferExternal(string accessTokenOrAppKey, string ExternalUserId, string handoverUserId, string takeoverUserId, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/crm/transfer_external_contact?access_token={0}", accessToken);
var data = new
{
external_userid = ExternalUserId,
handover_userid = handoverUserId,
takeover_userid = takeoverUserId
};
return CommonJsonSend.Send<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取外部联系人详情
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="ExternalUserId"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static GetExternalContactResultJson GetExternalContact(string accessTokenOrAppKey, string ExternalUserId, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/crm/get_external_contact?access_token={0}&external_userid={1}", accessToken, ExternalUserId);
return CommonJsonSend.Send<GetExternalContactResultJson>(null, url, null, CommonJsonSendType.GET, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取客户群列表
/// 权限说明:
/// 企业需要使用“客户联系”secret或配置到“可调用应用”列表中的自建应用secret所获取的accesstoken来调用。
/// 暂不支持第三方调用。
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="data">查询参数</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static GroupChatListResult GroupChatList(string accessTokenOrAppKey, GroupChatListParam data, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/groupchat/list?access_token={0}", accessToken);
return CommonJsonSend.Send<GroupChatListResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取客户群详情
/// 权限说明:
/// 企业需要使用“客户联系”secret或配置到“可调用应用”列表中的自建应用secret所获取的accesstoken来调用。
/// 暂不支持第三方调用。
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="chat_id">客户群ID</param>
/// <param name="timeOut"></param>
/// <param name="needName">是否需要返回群成员的名字group_chat.member_list.name。</param>
/// <returns></returns>
public static GroupChatGetResult GroupChatGet(string accessTokenOrAppKey, string chat_id, bool needName = false, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/groupchat/get?access_token={0}", accessToken);
var data = new
{
chat_id,
need_name = needName ? "1" : "0"//0-不返回;1-返回。默认不返回
};
return CommonJsonSend.Send<GroupChatGetResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
#region 客户管理
/// <summary>
/// 获取客户列表
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="userid">企业成员的userid</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static GetExternalContactListResult GetExternalContactList(string accessTokenOrAppKey, string userid, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/list?access_token={accessToken}&userid={userid}";
return CommonJsonSend.Send<GetExternalContactListResult>(null, url, null, CommonJsonSendType.GET, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取客户详情
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="externalUserId">外部联系人的userid,注意不是企业成员的帐号</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static GetExternalContactResultJson GetExternalContactInfo(string accessTokenOrAppKey, string externalUserId, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/get?access_token={accessToken}&external_userid={externalUserId}";
return CommonJsonSend.Send<GetExternalContactResultJson>(null, url, null, CommonJsonSendType.GET, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 批量获取客户详情
/// <para>文档:https://developer.work.weixin.qq.com/document/path/92994</para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="userid_list">(必须)企业成员的userid列表,字符串类型,最多支持100个</param>
/// <param name="cursor">用于分页查询的游标,字符串类型,由上一次调用返回,首次调用可不填</param>
/// <param name="limit">返回的最大记录数,整型,最大值100,默认值50,超过最大值时取最大值</param>
/// <param name="timeOut"></param>
public static GetExternalContactInfoBatchResult GetExternalContactInfoBatch(string accessTokenOrAppKey, string[] userid_list, string cursor = null, int limit = 50, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/batch/get_by_user?access_token={accessToken}";
var data = new
{
userid_list,
cursor,
limit
};
return CommonJsonSend.Send<GetExternalContactInfoBatchResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 修改客户备注信息
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="rquest">请求报文</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static WorkJsonResult UpdateExternalContactRemark(string accessTokenOrAppKey, UpdateExternalContactRemarkRequest rquest, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/remark?access_token={accessToken}";
return CommonJsonSend.Send<WorkJsonResult>(null, url, rquest, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取配置了客户联系功能的成员列表
/// <para>权限说明:</para>
/// <para>企业需要使用“客户联系”secret或配置到“可调用应用”列表中的自建应用secret所获取的accesstoken来调用</para>
/// <para>第三方应用需具有“企业客户权限->客户基础信息”权限</para>
/// <para>第三方/自建应用只能获取到可见范围内的配置了客户联系功能的成员。</para>
/// <para>文档:https://developer.work.weixin.qq.com/document/path/92571</para>
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static WorkJsonResult GetFollowUserList(string accessTokenOrAppKey, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/get_follow_user_list?access_token={accessToken}";
return CommonJsonSend.Send<WorkJsonResult>(null, url, null, CommonJsonSendType.GET, timeOut);
}, accessTokenOrAppKey);
}
#endregion
#region 联系我与客户入群方式
#region 客户联系「联系我」管理
//文档:https://developer.work.weixin.qq.com/document/path/92228
/// <summary>
/// 配置客户联系「联系我」方式
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="rquest">请求报文</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static AddContactWayResult AddContactWay(string accessTokenOrAppKey, AddContactWayRequest rquest, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/add_contact_way?access_token={accessToken}";
return CommonJsonSend.Send<AddContactWayResult>(null, url, rquest, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取企业已配置的「联系我」方式
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="configId">联系方式的配置id</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static GetContactWayResult AddContactWay(string accessTokenOrAppKey, string configId, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/get_contact_way?access_token={accessToken}";
var data = new { config_id = configId };
return CommonJsonSend.Send<GetContactWayResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取企业已配置的「联系我」列表
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="startTime">「联系我」创建起始时间戳, 默认为90天前</param>
/// <param name="endTime">「联系我」创建结束时间戳, 默认为当前时间</param>
/// <param name="cursor">分页查询使用的游标,为上次请求返回的 next_cursor</param>
/// <param name="limit">每次查询的分页大小,默认为100条,最多支持1000条</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static ListContactWayResult ListContactWay(string accessTokenOrAppKey, int? startTime = null, int? endTime = null, string? cursor = null, int? limit = null, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/list_contact_way?access_token={accessToken}";
var data = new
{
start_time = startTime,
end_time = endTime,
cursor,
limit
};
return CommonJsonSend.Send<ListContactWayResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 更新企业已配置的「联系我」方式
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="configId">联系方式的配置id</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static WorkJsonResult UpdateContactWay(string accessTokenOrAppKey, UpdateContactWayRequest request, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/update_contact_way?access_token={accessToken}";
return CommonJsonSend.Send<WorkJsonResult>(null, url, request, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 删除企业已配置的「联系我」方式
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="configId"> 企业联系方式的配置id</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static WorkJsonResult DeleteContactWay(string accessTokenOrAppKey, string configId, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/del_contact_way?access_token={accessToken}";
var data = new { config_id = configId };
return CommonJsonSend.Send<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 结束临时会话
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="userid">企业成员的userid</param>
/// <param name="externalUserid">客户的外部联系人userid</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static WorkJsonResult CloseTempChat(string accessTokenOrAppKey, string userid, string externalUserid, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/close_temp_chat?access_token={accessToken}";
var data = new { userid = userid, external_userid = externalUserid };
return CommonJsonSend.Send<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
#endregion
#region 客户群「加入群聊」管理
/// <summary>
/// 配置客户群进群方式
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="requet">请求参数</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static GroupChat_AddJoinWayResult GroupChat_AddJoinWay(string accessTokenOrAppKey, GroupChat_AddJoinWayRequest requet, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/groupchat/add_join_way?access_token={accessToken}";
return CommonJsonSend.Send<GroupChat_AddJoinWayResult>(null, url, requet, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取客户群进群方式配置
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="configId">联系方式的配置id</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static GroupChat_GetJoinWayResult GroupChat_GetJoinWay(string accessTokenOrAppKey, string configId, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/groupchat/get_join_way?access_token={accessToken}";
var data = new { config_id = configId };
return CommonJsonSend.Send<GroupChat_GetJoinWayResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取客户群进群方式配置
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="request">请求参数</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static WorkJsonResult GroupChat_UpdateJoinWay(string accessTokenOrAppKey, GroupChat_UpdateJoinWayRequest request, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/groupchat/update_join_way?access_token={accessToken}";
return CommonJsonSend.Send<WorkJsonResult>(null, url, request, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取客户群进群方式配置
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="configId">企业联系方式的配置id</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static WorkJsonResult GroupChat_DelJoinWay(string accessTokenOrAppKey, string configId, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/groupchat/del_join_way?access_token={accessToken}";
var data = new { config_id = configId };
return CommonJsonSend.Send<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
#endregion
#endregion
#region 统计管理
/// <summary>
/// 获取「联系客户统计」数据
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="data"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static GetUserBehaviorDataListResult GetUserBehaviorData(string accessTokenOrAppKey, GetUserBehaviorDataParam data, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/get_user_behavior_data?access_token={0}", accessToken);
return CommonJsonSend.Send<GetUserBehaviorDataListResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取「群聊数据统计」数据 按群主聚合的方式
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="data"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static GetGroupChatListResult GroupChatStatisticOwner(string accessTokenOrAppKey, GetGroupChatParam data, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/groupchat/statistic?access_token={0}", accessToken);
return CommonJsonSend.Send<GetGroupChatListResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取「群聊数据统计」数据 按自然日聚合的方式
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="data"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static GetGroupChatGroupByDayListResult GroupChatStatisticGroupByDay(string accessTokenOrAppKey, GetGroupChatGroupByDayParam data, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/groupchat/statistic_group_by_day?access_token={0}", accessToken);
return CommonJsonSend.Send<GetGroupChatGroupByDayListResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
#endregion
#region 客户标签管理
#region 管理企业标签
/// <summary>
/// 获取企业标签库
/// <para><see href="https://developer.work.weixin.qq.com/document/path/92117">官方文档</see></para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="tag_id">(可选)要查询的标签id</param>
/// <param name="group_id">(可选)要查询的标签组id,返回该标签组以及其下的所有标签信息</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static GetCorpTagListResult GetCropTagList(string accessTokenOrAppKey, List<string> tag_id = null, List<string> group_id = null, int timeOut = Config.TIME_OUT)
{
//文档:https://developer.work.weixin.qq.com/document/path/94882
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/get_corp_tag_list?access_token={0}", accessToken);
var data = new
{
tag_id,
group_id
};
return CommonJsonSend.Send<GetCorpTagListResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 添加企业客户标签
/// <para><see href="https://developer.work.weixin.qq.com/document/path/92117">官方文档</see></para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="data"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static AddCorpTagResult AddCropTag(string accessTokenOrAppKey, AddCorpTagRequest data, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/add_corp_tag?access_token={0}", accessToken);
return CommonJsonSend.Send<AddCorpTagResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 编辑企业客户标签
/// <para>注意:修改后的标签组不能和已有的标签组重名,标签也不能和同一标签组下的其他标签重名。</para>
/// <para><see href="https://developer.work.weixin.qq.com/document/path/92117">官方文档</see></para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="id">(必须)标签或标签组的id</param>
/// <param name="name">(可选)新的标签或标签组名称,最长为30个字符</param>
/// <param name="order">(可选)标签/标签组的次序值。order值大的排序靠前。有效的值范围是[0, 2^32)</param>
/// <param name="agentid">授权方安装的应用agentid。仅旧的第三方多应用套件需要填此参数</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static WorkJsonResult EditCropTag(string accessTokenOrAppKey, string id, string name = null, int? order = null, int? agentid = null, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/edit_corp_tag?access_token={0}", accessToken);
var data = new
{
id,
name,
order,
agentid
};
return CommonJsonSend.Send<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 删除企业标签,企业可通过此接口删除客户标签库中的标签,或删除整个标签组。
/// <para><see href="https://developer.work.weixin.qq.com/document/path/92117">官方文档</see></para>
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="tag_id">(可选)标签的id列表</param>
/// <param name="group_id">(可选)标签组的id列表</param>
/// <param name="agentid">(可选)授权方安装的应用agentid。仅旧的第三方多应用套件需要填此参数</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static WorkJsonResult DeleteCropTag(string accessTokenOrAppKey, List<string> tag_id = null, List<string> group_id = null, int? agentid = null, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/del_corp_tag?access_token={0}", accessToken);
var data = new
{
tag_id,
group_id,
agentid
};
return CommonJsonSend.Send<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
#endregion
#region 管理企业规则组下的客户标签
/// <summary>
/// 获取指定规则组下的企业客户标签
/// <para><see href="https://developer.work.weixin.qq.com/document/path/94882">官方文档</see></para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="tag_id">(可选)要查询的标签id</param>
/// <param name="group_id">(可选)要查询的标签组id,返回该标签组以及其下的所有标签信息</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static GetStrategyTagListResult GetStrategyTagList(string accessTokenOrAppKey, List<string> tag_id = null, List<string> group_id = null, int timeOut = Config.TIME_OUT)
{
//文档:https://developer.work.weixin.qq.com/document/path/94882
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/get_strategy_tag_list?access_token={0}", accessToken);
var data = new
{
tag_id,
group_id
};
return CommonJsonSend.Send<GetStrategyTagListResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 为指定规则组创建企业客户标签
/// <para><see href="https://developer.work.weixin.qq.com/document/path/94882">官方文档</see></para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="data"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static AddStrategyTagResult AddStrategyTag(string accessTokenOrAppKey, AddStrategyTagRequest data, int timeOut = Config.TIME_OUT)
{
//文档:https://developer.work.weixin.qq.com/document/path/94882
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/add_strategy_tag?access_token={0}", accessToken);
return CommonJsonSend.Send<AddStrategyTagResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 编辑指定规则组下的企业客户标签
/// <para>企业可通过此接口编辑指定规则组下的客户标签/标签组的名称或次序值,但不可重新指定标签/标签组所属规则组。</para>
/// <para><see href="https://developer.work.weixin.qq.com/document/path/94882">官方文档</see></para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="id">(必须)标签或标签组的id</param>
/// <param name="name">(可选)新的标签或标签组名称,最长为30个字符</param>
/// <param name="order">(可选)标签/标签组的次序值。order值大的排序靠前。有效的值范围是[0, 2^32)</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static WorkJsonResult EditStrategyTag(string accessTokenOrAppKey, string id, string name = null, int? order = null, int timeOut = Senparc.Weixin.Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/edit_strategy_tag?access_token={0}", accessToken);
var data = new
{
id,
name,
order
};
return CommonJsonSend.Send<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 删除指定规则组下的企业客户标签
/// <para><see href="https://developer.work.weixin.qq.com/document/path/94882">官方文档</see></para>
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="tag_id">(可选)标签的id列表</param>
/// <param name="group_id">(可选)标签组的id列表</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static WorkJsonResult DeleteStrategyTag(string accessTokenOrAppKey, List<string> tag_id = null, List<string> group_id = null, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/del_strategy_tag?access_token={0}", accessToken);
var data = new
{
tag_id,
group_id
};
return CommonJsonSend.Send<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
#endregion
#region 编辑客户企业标签
/// <summary>
/// 编辑客户企业标签
/// <para><see href="https://developer.work.weixin.qq.com/document/path/92118">官方文档</see></para>
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="userid">(必须)添加外部联系人的userid</param>
/// <param name="external_userid">(必须)外部联系人userid</param>
/// <param name="add_tag">(可选)要标记的标签列表</param>
/// <param name="remove_tag">(可选)要移除的标签列表</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static WorkJsonResult DeleteStrategyTag(string accessTokenOrAppKey, string userid, string external_userid, List<string> add_tag = null, List<string> remove_tag = null, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/mark_tag?access_token={0}", accessToken);
var data = new
{
userid,
external_userid,
add_tag,
remove_tag
};
return CommonJsonSend.Send<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
#endregion
#endregion
#region 朋友圈
/// <summary>
/// 获取企业全部的发表内容。
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="data"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static GetMomentListResult GetMomentList(string accessTokenOrAppKey, GetMomentListParam data, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/get_moment_list?access_token={0}", accessToken);
return CommonJsonSend.Send<GetMomentListResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取企业发表的朋友圈成员执行情况
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="data"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static GetMomentTaskResult GetMomentTask(string accessTokenOrAppKey, GetMomentTaskParam data, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/get_moment_task?access_token={0}", accessToken);
return CommonJsonSend.Send<GetMomentTaskResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
#endregion
#region 消息推送
/// <summary>
/// 创建企业群发
/// <para>文档:https://developer.work.weixin.qq.com/document/path/92135</para>
/// <para></para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="requestData"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static AddMessageTemplateResult AddMsgTemplate(string accessTokenOrAppKey, AddMessageTemplateRequest requestData, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/add_msg_template?access_token={0}", accessToken);
return CommonJsonSend.Send<AddMessageTemplateResult>(null, url, requestData, CommonJsonSendType.POST, timeOut, jsonSetting: new JsonSetting(true));
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取群发记录列表
/// <para>https://developer.work.weixin.qq.com/document/path/93338</para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="requestData"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static GetGroupMsgListV2Result GetGroupMsgListV2(string accessTokenOrAppKey, GetGroupMsgListV2Request requestData, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/get_groupmsg_list_v2?access_token={0}", accessToken);
return CommonJsonSend.Send<GetGroupMsgListV2Result>(null, url, requestData, CommonJsonSendType.POST, timeOut, jsonSetting: new JsonSetting(true));
}, accessTokenOrAppKey);
}
#nullable enable
/// <summary>
/// 获取群发记录列表
/// <para>https://developer.work.weixin.qq.com/document/path/93338</para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="msgid">群发消息的id,通过<see href="https://developer.work.weixin.qq.com/document/path/93338#%E8%8E%B7%E5%8F%96%E7%BE%A4%E5%8F%91%E8%AE%B0%E5%BD%95%E5%88%97%E8%A1%A8">获取群发记录列表</see>接口返回</param>
/// <param name="limit">返回的最大记录数,整型,最大值1000,默认值500,超过最大值时取默认值</param>
/// <param name="cursor">用于分页查询的游标,字符串类型,由上一次调用返回,首次调用可不填</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static GetGroupMsgTaskResult GetGroupMsgTask(string accessTokenOrAppKey, string msgid, int? limit = null, string? cursor = null, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/get_groupmsg_task?access_token={0}", accessToken);
var data = new
{
msgid,
limit,
cursor
};
return CommonJsonSend.Send<GetGroupMsgTaskResult>(null, url, data, CommonJsonSendType.POST, timeOut, jsonSetting: new JsonSetting(true));
}, accessTokenOrAppKey);
}
#nullable disable
/// <summary>
/// 获取企业群发成员执行结果
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="msgid">群发消息的id,通过<see href="https://developer.work.weixin.qq.com/document/path/93338#%E8%8E%B7%E5%8F%96%E7%BE%A4%E5%8F%91%E8%AE%B0%E5%BD%95%E5%88%97%E8%A1%A8">获取群发记录列表</see>接口返回</param>
/// <param name="userid">发送成员userid,通过<see href="https://developer.work.weixin.qq.com/document/path/93338#%E8%8E%B7%E5%8F%96%E7%BE%A4%E5%8F%91%E6%88%90%E5%91%98%E5%8F%91%E9%80%81%E4%BB%BB%E5%8A%A1%E5%88%97%E8%A1%A8">获取群发成员发送任务列表</see>接口返回</param>
/// <param name="limit">返回的最大记录数,整型,最大值1000,默认值500,超过最大值时取默认值</param>
/// <param name="cursor">用于分页查询的游标,字符串类型,由上一次调用返回,首次调用可不填</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static GetGroupMsgSendResultResult GetGroupMsgSendResult(string accessTokenOrAppKey, string msgid, string userid, int? limit = null, string? cursor = null, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/get_groupmsg_send_result?access_token={0}", accessToken);
var data = new
{
msgid,
userid,
limit,
cursor
};
return CommonJsonSend.Send<GetGroupMsgSendResultResult>(null, url, data, CommonJsonSendType.POST, timeOut, jsonSetting: new JsonSetting(true));
}, accessTokenOrAppKey);
}
/// <summary>
/// 发送新客户欢迎语
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="requestData"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static WorkJsonResult SendWelcomeMsg(string accessTokenOrAppKey, SendWelcomeMsgRequest requestData, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/send_welcome_msg?access_token={0}", accessToken);
return CommonJsonSend.Send<WorkJsonResult>(null, url, requestData, CommonJsonSendType.POST, timeOut, jsonSetting: new JsonSetting(true));
}, accessTokenOrAppKey);
}
#region 入群欢迎语素材管理
/// <summary>
/// 添加入群欢迎语素材
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="data"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static GroupWelcomeTemplateAddResult GroupWelcomeTemplateAdd(string accessTokenOrAppKey, GroupWelcomeTemplateAddRequest data, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/group_welcome_template/add?access_token={0}", accessToken);
return CommonJsonSend.Send<GroupWelcomeTemplateAddResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 编辑入群欢迎语素材
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="data"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static WorkJsonResult GroupWelcomeTemplateEdit(string accessTokenOrAppKey, GroupWelcomeTemplateEditRequest data, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/group_welcome_template/edit?access_token={0}", accessToken);
return CommonJsonSend.Send<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取入群欢迎语素材
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="template_id"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static GroupWelcomeTemplateGetResult GroupWelcomeTemplateGet(string accessTokenOrAppKey, string template_id, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var data = new
{
template_id = template_id
};
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/group_welcome_template/get?access_token={0}", accessToken);
return CommonJsonSend.Send<GroupWelcomeTemplateGetResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 删除入群欢迎语素材
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="template_id"></param>
/// <param name="agentid"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static WorkJsonResult GroupWelcomeTemplateDel(string accessTokenOrAppKey, string template_id, long? agentid, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var data = new
{
template_id = template_id,
agentid = agentid
};
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/group_welcome_template/del?access_token={0}", accessToken);
return CommonJsonSend.Send<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
#endregion
#endregion
#endregion
#region 异步方法
/// <summary>
/// 【异步方法】离职成员的外部联系人再分配
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="ExternalUserId"></param>
/// <param name="handoverUserId"></param>
/// <param name="takeoverUserId"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GetFollowUserListResult> TransferExternalAsync(string accessTokenOrAppKey, string ExternalUserId, string handoverUserId, string takeoverUserId, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/crm/transfer_external_contact?access_token={0}", accessToken);
var data = new
{
external_userid = ExternalUserId,
handover_userid = handoverUserId,
takeover_userid = takeoverUserId
};
return await CommonJsonSend.SendAsync<GetFollowUserListResult>(null, url, data, CommonJsonSendType.POST, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
/// <summary>
/// 【异步方法】获取外部联系人详情
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="ExternalUserId"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GetExternalContactResultJson> GetExternalContactAsync(string accessTokenOrAppKey, string ExternalUserId, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/crm/get_external_contact?access_token={0}&external_userid={1}", accessToken, ExternalUserId);
return await CommonJsonSend.SendAsync<GetExternalContactResultJson>(null, url, null, CommonJsonSendType.GET, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
/// <summary>
/// 【异步方法】获取客户群列表
/// 权限说明:
/// 企业需要使用“客户联系”secret或配置到“可调用应用”列表中的自建应用secret所获取的accesstoken来调用(accesstoken如何获取?)。
/// 暂不支持第三方调用。
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="data">查询参数</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GroupChatListResult> GroupChatListAsync(string accessTokenOrAppKey, GroupChatListParam data, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/groupchat/list?access_token={0}", accessToken);
return await CommonJsonSend.SendAsync<GroupChatListResult>(null, url, data, CommonJsonSendType.POST, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
/// <summary>
/// 【异步方法】获取客户群详情
/// 权限说明:
/// 企业需要使用“客户联系”secret或配置到“可调用应用”列表中的自建应用secret所获取的accesstoken来调用。
/// 暂不支持第三方调用。
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="chat_id">客户群ID</param>
/// <param name="timeOut"></param>
/// <param name="needName">是否需要返回群成员的名字group_chat.member_list.name。</param>
/// <returns></returns>
public static async Task<GroupChatGetResult> GroupChatGetAsync(string accessTokenOrAppKey, string chat_id, bool needName = false, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/groupchat/get?access_token={0}", accessToken);
var data = new
{
chat_id,
need_name = needName ? "1" : "0"//0-不返回;1-返回。默认不返回
};
return await CommonJsonSend.SendAsync<GroupChatGetResult>(null, url, data, CommonJsonSendType.POST, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
#region 客户管理
/// <summary>
/// 【异步方法】获取客户列表
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="userid">企业成员的userid</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GetExternalContactListResult> GetExternalContactListAsync(string accessTokenOrAppKey, string userid, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/list?access_token={accessToken}&userid={userid}";
return await CommonJsonSend.SendAsync<GetExternalContactListResult>(null, url, null, CommonJsonSendType.GET, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
/// <summary>
/// 【异步方法】获取客户详情
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="externalUserId">外部联系人的userid,注意不是企业成员的帐号</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GetExternalContactResultJson> GetExternalContactInfoAsync(string accessTokenOrAppKey, string externalUserId, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/get?access_token={accessToken}&external_userid={externalUserId}";
return await CommonJsonSend.SendAsync<GetExternalContactResultJson>(null, url, null, CommonJsonSendType.GET, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
/// <summary>
/// 【异步方法】批量获取客户详情
/// <para>文档:https://developer.work.weixin.qq.com/document/path/92994</para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="userid_list">(必须)企业成员的userid列表,字符串类型,最多支持100个</param>
/// <param name="cursor">用于分页查询的游标,字符串类型,由上一次调用返回,首次调用可不填</param>
/// <param name="limit">返回的最大记录数,整型,最大值100,默认值50,超过最大值时取最大值</param>
/// <param name="timeOut"></param>
public static async Task<GetExternalContactInfoBatchResult> GetExternalContactInfoBatchAsync(string accessTokenOrAppKey, string[] userid_list, string cursor = null, int limit = 50, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/batch/get_by_user?access_token={accessToken}";
var data = new
{
userid_list,
cursor,
limit
};
return await CommonJsonSend.SendAsync<GetExternalContactInfoBatchResult>(null, url, data, CommonJsonSendType.POST, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
/// <summary>
/// 修改客户备注信息
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="rquest">请求报文</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<WorkJsonResult> UpdateExternalContactRemarkAsync(string accessTokenOrAppKey, UpdateExternalContactRemarkRequest rquest, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/remark?access_token={accessToken}";
return await CommonJsonSend.SendAsync<WorkJsonResult>(null, url, rquest, CommonJsonSendType.POST, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
/// <summary>
/// 【异步方法】获取配置了客户联系功能的成员列表
/// <para>权限说明:</para>
/// <para>企业需要使用“客户联系”secret或配置到“可调用应用”列表中的自建应用secret所获取的accesstoken来调用</para>
/// <para>第三方应用需具有“企业客户权限->客户基础信息”权限</para>
/// <para>第三方/自建应用只能获取到可见范围内的配置了客户联系功能的成员。</para>
/// <para>文档:https://developer.work.weixin.qq.com/document/path/92571</para>
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GetFollowUserListResult> GetFollowUserListAsync(string accessTokenOrAppKey, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/get_follow_user_list?access_token={accessToken}";
return await CommonJsonSend.SendAsync<GetFollowUserListResult>(null, url, null, CommonJsonSendType.GET, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey);
}
#endregion
#region 统计管理
/// <summary>
/// 获取「联系客户统计」数据
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="data"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GetUserBehaviorDataListResult> GetUserBehaviorDataAsync(string accessTokenOrAppKey, GetUserBehaviorDataParam data, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/get_user_behavior_data?access_token={0}", accessToken);
return await CommonJsonSend.SendAsync<GetUserBehaviorDataListResult>(null, url, data, CommonJsonSendType.POST, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
/// <summary>
/// 获取「群聊数据统计」数据 按群主聚合的方式
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="data"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GetGroupChatListResult> GroupChatStatisticOwnerAsync(string accessTokenOrAppKey, GetGroupChatParam data, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/groupchat/statistic?access_token={0}", accessToken);
return await CommonJsonSend.SendAsync<GetGroupChatListResult>(null, url, data, CommonJsonSendType.POST, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
/// <summary>
/// 获取「群聊数据统计」数据 按自然日聚合的方式
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="data"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GetGroupChatGroupByDayListResult> GroupChatStatisticGroupByDayAsync(string accessTokenOrAppKey, GetGroupChatGroupByDayParam data, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/groupchat/statistic_group_by_day?access_token={0}", accessToken);
return await CommonJsonSend.SendAsync<GetGroupChatGroupByDayListResult>(null, url, data, CommonJsonSendType.POST, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
#endregion
#region 客户标签管理
#region 管理企业标签
/// <summary>
/// 【异步方法】获取企业标签库
/// <para><see href="https://developer.work.weixin.qq.com/document/path/94882">官方文档</see></para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="tag_id">(可选)要查询的标签id</param>
/// <param name="group_id">(可选)要查询的标签组id,返回该标签组以及其下的所有标签信息</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GetCorpTagListResult> GetCropTagListAsync(string accessTokenOrAppKey, List<string> tag_id = null, List<string> group_id = null, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/get_corp_tag_list?access_token={0}", accessToken);
var data = new
{
tag_id,
group_id
};
return await CommonJsonSend.SendAsync<GetCorpTagListResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 【异步方法】添加企业客户标签
/// <para><see href="https://developer.work.weixin.qq.com/document/path/92117">官方文档</see></para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="data"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<AddCorpTagResult> AddCropTagAsync(string accessTokenOrAppKey, AddCorpTagRequest data, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/add_corp_tag?access_token={0}", accessToken);
return await CommonJsonSend.SendAsync<AddCorpTagResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 【异步方法】编辑企业客户标签
/// <para>注意:修改后的标签组不能和已有的标签组重名,标签也不能和同一标签组下的其他标签重名。</para>
/// <para><see href="https://developer.work.weixin.qq.com/document/path/92117">官方文档</see></para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="id">(必须)标签或标签组的id</param>
/// <param name="name">(可选)新的标签或标签组名称,最长为30个字符</param>
/// <param name="order">(可选)标签/标签组的次序值。order值大的排序靠前。有效的值范围是[0, 2^32)</param>
/// <param name="agentid">授权方安装的应用agentid。仅旧的第三方多应用套件需要填此参数</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<WorkJsonResult> EditCropTagAsync(string accessTokenOrAppKey, int id, string name = null, int? order = null, int? agentid = null, int timeOut = Senparc.Weixin.Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/edit_corp_tag?access_token={0}", accessToken);
var data = new
{
id,
name,
order,
agentid
};
return await CommonJsonSend.SendAsync<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 【异步方法】删除企业标签,企业可通过此接口删除客户标签库中的标签,或删除整个标签组。
/// <para><see href="https://developer.work.weixin.qq.com/document/path/92117">官方文档</see></para>
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="tag_id">(可选)标签的id列表</param>
/// <param name="group_id">(可选)标签组的id列表</param>
/// <param name="agentid">(可选)授权方安装的应用agentid。仅旧的第三方多应用套件需要填此参数</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<WorkJsonResult> DeleteCropTagAsync(string accessTokenOrAppKey, List<string> tag_id = null, List<string> group_id = null, int? agentid = null, int timeOut = Senparc.Weixin.Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/del_corp_tag?access_token={0}", accessToken);
var data = new
{
tag_id,
group_id,
agentid
};
return await CommonJsonSend.SendAsync<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
#endregion
#region 管理企业规则组下的客户标签
/// <summary>
/// 【异步方法】获取指定规则组下的企业客户标签
/// <para><see href="https://developer.work.weixin.qq.com/document/path/94882">官方文档</see></para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="tag_id">(可选)要查询的标签id</param>
/// <param name="group_id">(可选)要查询的标签组id,返回该标签组以及其下的所有标签信息</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GetStrategyTagListResult> GetStrategyTagListAsync(string accessTokenOrAppKey, List<string> tag_id = null, List<string> group_id = null, int timeOut = Config.TIME_OUT)
{
//文档:https://developer.work.weixin.qq.com/document/path/94882
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/get_strategy_tag_list?access_token={0}", accessToken);
var data = new
{
tag_id,
group_id
};
return await CommonJsonSend.SendAsync<GetStrategyTagListResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 为指定规则组创建企业客户标签
/// <para><see href="https://developer.work.weixin.qq.com/document/path/94882">官方文档</see></para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="data"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<AddStrategyTagResult> AddStrategyTagAsync(string accessTokenOrAppKey, AddStrategyTagRequest data, int timeOut = Config.TIME_OUT)
{
//文档:https://developer.work.weixin.qq.com/document/path/94882
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/add_strategy_tag?access_token={0}", accessToken);
return await CommonJsonSend.SendAsync<AddStrategyTagResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 【异步方法】编辑指定规则组下的企业客户标签
/// <para>企业可通过此接口编辑指定规则组下的客户标签/标签组的名称或次序值,但不可重新指定标签/标签组所属规则组。</para>
/// <para><see href="https://developer.work.weixin.qq.com/document/path/94882">官方文档</see></para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="id">(必须)标签或标签组的id</param>
/// <param name="name">(可选)新的标签或标签组名称,最长为30个字符</param>
/// <param name="order">(可选)标签/标签组的次序值。order值大的排序靠前。有效的值范围是[0, 2^32)</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<WorkJsonResult> EditStrategyTagAsync(string accessTokenOrAppKey, string id, string name = null, int? order = null, int timeOut = Senparc.Weixin.Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/edit_strategy_tag?access_token={0}", accessToken);
var data = new
{
id,
name,
order
};
return await CommonJsonSend.SendAsync<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 【异步方法】删除指定规则组下的企业客户标签
/// <para><see href="https://developer.work.weixin.qq.com/document/path/94882">官方文档</see></para>
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="tag_id">(可选)标签的id列表</param>
/// <param name="group_id">(可选)标签组的id列表</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<WorkJsonResult> DeleteStrategyTagAsync(string accessTokenOrAppKey, List<string> tag_id = null, List<string> group_id = null, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/del_strategy_tag?access_token={0}", accessToken);
var data = new
{
tag_id,
group_id
};
return await CommonJsonSend.SendAsync<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
#endregion
#region 编辑客户企业标签
/// <summary>
/// 【异步方法】编辑客户企业标签
/// <para><see href="https://developer.work.weixin.qq.com/document/path/92118">官方文档</see></para>
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="userid">(必须)添加外部联系人的userid</param>
/// <param name="external_userid">(必须)外部联系人userid</param>
/// <param name="add_tag">(可选)要标记的标签列表</param>
/// <param name="remove_tag">(可选)要移除的标签列表</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<WorkJsonResult> DeleteStrategyTagAsync(string accessTokenOrAppKey, string userid, string external_userid, List<string> add_tag = null, List<string> remove_tag = null, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/mark_tag?access_token={0}", accessToken);
var data = new
{
userid,
external_userid,
add_tag,
remove_tag
};
return await CommonJsonSend.SendAsync<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
#endregion
#endregion
#region 朋友圈
/// <summary>
/// 获取企业全部的发表内容。
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="data"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GetMomentListResult> GetMomentListAsync(string accessTokenOrAppKey, GetMomentListParam data, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/get_moment_list?access_token={0}", accessToken);
return await CommonJsonSend.SendAsync<GetMomentListResult>(null, url, data, CommonJsonSendType.POST, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
/// <summary>
/// 获取企业发表的朋友圈成员执行情况
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="data"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GetMomentTaskResult> GetMomentTaskAsync(string accessTokenOrAppKey, GetMomentTaskParam data, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/get_moment_task?access_token={0}", accessToken);
return await CommonJsonSend.SendAsync<GetMomentTaskResult>(null, url, data, CommonJsonSendType.POST, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
#endregion
#region 联系我与客户入群方式
#region 客户联系「联系我」管理
//文档:https://developer.work.weixin.qq.com/document/path/92228
/// <summary>
/// 配置客户联系「联系我」方式
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="rquest">请求报文</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<AddContactWayResult> AddContactWayAsync(string accessTokenOrAppKey, AddContactWayRequest rquest, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/add_contact_way?access_token={accessToken}";
return await CommonJsonSend.SendAsync<AddContactWayResult>(null, url, rquest, CommonJsonSendType.POST, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey);
}
/// <summary>
/// 【异步方法】获取企业已配置的「联系我」方式
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="configId">联系方式的配置id</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public async static Task<GetContactWayResult> AddContactWayAsync(string accessTokenOrAppKey, string configId, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/get_contact_way?access_token={accessToken}";
var data = new { config_id = configId };
return await CommonJsonSend.SendAsync<GetContactWayResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 【异步方法】获取企业已配置的「联系我」列表
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="startTime">「联系我」创建起始时间戳, 默认为90天前</param>
/// <param name="endTime">「联系我」创建结束时间戳, 默认为当前时间</param>
/// <param name="cursor">分页查询使用的游标,为上次请求返回的 next_cursor</param>
/// <param name="limit">每次查询的分页大小,默认为100条,最多支持1000条</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public async static Task<ListContactWayResult> ListContactWayAsync(string accessTokenOrAppKey, int? startTime = null, int? endTime = null, string? cursor = null, int? limit = null, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/list_contact_way?access_token={accessToken}";
var data = new
{
start_time = startTime,
end_time = endTime,
cursor,
limit
};
return await CommonJsonSend.SendAsync<ListContactWayResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 【异步方法】更新企业已配置的「联系我」方式
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="configId">联系方式的配置id</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public async static Task<WorkJsonResult> UpdateContactWayAsync(string accessTokenOrAppKey, UpdateContactWayRequest request, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/update_contact_way?access_token={accessToken}";
return await CommonJsonSend.SendAsync<WorkJsonResult>(null, url, request, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 【异步方法】删除企业已配置的「联系我」方式
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="configId"> 企业联系方式的配置id</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public async static Task<WorkJsonResult> DeleteContactWayAsync(string accessTokenOrAppKey, string configId, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/del_contact_way?access_token={accessToken}";
var data = new { config_id = configId };
return await CommonJsonSend.SendAsync<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 【异步方法】结束临时会话
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="userid">企业成员的userid</param>
/// <param name="externalUserid">客户的外部联系人userid</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public async static Task<WorkJsonResult> CloseTempChatAsync(string accessTokenOrAppKey, string userid, string externalUserid, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/close_temp_chat?access_token={accessToken}";
var data = new { userid = userid, external_userid = externalUserid };
return await CommonJsonSend.SendAsync<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
#endregion
#region 客户群「加入群聊」管理
/// <summary>
/// 【异步方法】配置客户群进群方式
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="requet">请求参数</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GroupChat_AddJoinWayResult> GroupChat_AddJoinWayAsync(string accessTokenOrAppKey, GroupChat_AddJoinWayRequest requet, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/groupchat/add_join_way?access_token={accessToken}";
return await CommonJsonSend.SendAsync<GroupChat_AddJoinWayResult>(null, url, requet, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 【异步方法】获取客户群进群方式配置
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="configId">联系方式的配置id</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GroupChat_GetJoinWayResult> GroupChat_GetJoinWayAsync(string accessTokenOrAppKey, string configId, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/groupchat/get_join_way?access_token={accessToken}";
var data = new { config_id = configId };
return await CommonJsonSend.SendAsync<GroupChat_GetJoinWayResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 【异步方法】获取客户群进群方式配置
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="request">请求参数</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<WorkJsonResult> GroupChat_UpdateJoinWayAsync(string accessTokenOrAppKey, GroupChat_UpdateJoinWayRequest request, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/groupchat/update_join_way?access_token={accessToken}";
return await CommonJsonSend.SendAsync<WorkJsonResult>(null, url, request, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取客户群进群方式配置
/// </summary>
/// <param name="accessTokenOrAppKey">调用接口凭证</param>
/// <param name="configId">企业联系方式的配置id</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<WorkJsonResult> GroupChat_DelJoinWayAsync(string accessTokenOrAppKey, string configId, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = $"{Config.ApiWorkHost}/cgi-bin/externalcontact/groupchat/del_join_way?access_token={accessToken}";
var data = new { config_id = configId };
return await CommonJsonSend.SendAsync<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
#endregion
#endregion
#region 消息推送
/// <summary>
/// 创建企业群发
/// <para>文档:https://developer.work.weixin.qq.com/document/path/92135</para>
/// <para></para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="requestData"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<AddMessageTemplateResult> AddMsgTemplateAsync(string accessTokenOrAppKey, AddMessageTemplateRequest requestData, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/add_msg_template?access_token={0}", accessToken);
return await CommonJsonSend.SendAsync<AddMessageTemplateResult>(null, url, requestData, CommonJsonSendType.POST, timeOut, jsonSetting: new JsonSetting(true));
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取群发记录列表
/// <para>https://developer.work.weixin.qq.com/document/path/93338</para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="requestData"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GetGroupMsgListV2Result> GetGroupMsgListV2Async(string accessTokenOrAppKey, GetGroupMsgListV2Request requestData, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/get_groupmsg_list_v2?access_token={0}", accessToken);
return await CommonJsonSend.SendAsync<GetGroupMsgListV2Result>(null, url, requestData, CommonJsonSendType.POST, timeOut, jsonSetting: new JsonSetting(true));
}, accessTokenOrAppKey);
}
#nullable enable
/// <summary>
/// 获取群发记录列表
/// <para>https://developer.work.weixin.qq.com/document/path/93338</para>
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="msgid">群发消息的id,通过<see href="https://developer.work.weixin.qq.com/document/path/93338#%E8%8E%B7%E5%8F%96%E7%BE%A4%E5%8F%91%E8%AE%B0%E5%BD%95%E5%88%97%E8%A1%A8">获取群发记录列表</see>接口返回</param>
/// <param name="limit">返回的最大记录数,整型,最大值1000,默认值500,超过最大值时取默认值</param>
/// <param name="cursor">用于分页查询的游标,字符串类型,由上一次调用返回,首次调用可不填</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GetGroupMsgTaskResult> GetGroupMsgTaskAsync(string accessTokenOrAppKey, string msgid, int? limit = null, string? cursor = null, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/get_groupmsg_task?access_token={0}", accessToken);
var data = new
{
msgid,
limit,
cursor
};
return await CommonJsonSend.SendAsync<GetGroupMsgTaskResult>(null, url, data, CommonJsonSendType.POST, timeOut, jsonSetting: new JsonSetting(true));
}, accessTokenOrAppKey);
}
#nullable disable
/// <summary>
/// 获取企业群发成员执行结果
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="msgid">群发消息的id,通过<see href="https://developer.work.weixin.qq.com/document/path/93338#%E8%8E%B7%E5%8F%96%E7%BE%A4%E5%8F%91%E8%AE%B0%E5%BD%95%E5%88%97%E8%A1%A8">获取群发记录列表</see>接口返回</param>
/// <param name="userid">发送成员userid,通过<see href="https://developer.work.weixin.qq.com/document/path/93338#%E8%8E%B7%E5%8F%96%E7%BE%A4%E5%8F%91%E6%88%90%E5%91%98%E5%8F%91%E9%80%81%E4%BB%BB%E5%8A%A1%E5%88%97%E8%A1%A8">获取群发成员发送任务列表</see>接口返回</param>
/// <param name="limit">返回的最大记录数,整型,最大值1000,默认值500,超过最大值时取默认值</param>
/// <param name="cursor">用于分页查询的游标,字符串类型,由上一次调用返回,首次调用可不填</param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GetGroupMsgSendResultResult> GetGroupMsgSendResultAsync(string accessTokenOrAppKey, string msgid, string userid, int? limit = null, string? cursor = null, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/get_groupmsg_send_result?access_token={0}", accessToken);
var data = new
{
msgid,
userid,
limit,
cursor
};
return await CommonJsonSend.SendAsync<GetGroupMsgSendResultResult>(null, url, data, CommonJsonSendType.POST, timeOut, jsonSetting: new JsonSetting(true));
}, accessTokenOrAppKey);
}
/// <summary>
/// 发送新客户欢迎语
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="requestData"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<WorkJsonResult> SendWelcomeMsgAsync(string accessTokenOrAppKey, SendWelcomeMsgRequest requestData, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/send_welcome_msg?access_token={0}", accessToken);
return await CommonJsonSend.SendAsync<WorkJsonResult>(null, url, requestData, CommonJsonSendType.POST, timeOut, jsonSetting: new JsonSetting(true));
}, accessTokenOrAppKey);
}
#region 入群欢迎语素材管理
/// <summary>
/// 添加入群欢迎语素材
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="data"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GroupWelcomeTemplateAddResult> GroupWelcomeTemplateAddAsync(string accessTokenOrAppKey, GroupWelcomeTemplateAddRequest data, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/group_welcome_template/add?access_token={0}", accessToken);
return await CommonJsonSend.SendAsync<GroupWelcomeTemplateAddResult>(null, url, data, CommonJsonSendType.POST, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
/// <summary>
/// 编辑入群欢迎语素材
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="data"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<WorkJsonResult> GroupWelcomeTemplateEditAsync(string accessTokenOrAppKey, GroupWelcomeTemplateEditRequest data, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/group_welcome_template/edit?access_token={0}", accessToken);
return await CommonJsonSend.SendAsync<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
/// <summary>
/// 获取入群欢迎语素材
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="template_id"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<GroupWelcomeTemplateGetResult> GroupWelcomeTemplateGetAsync(string accessTokenOrAppKey, string template_id, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var data = new
{
template_id = template_id
};
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/group_welcome_template/get?access_token={0}", accessToken);
return await CommonJsonSend.SendAsync<GroupWelcomeTemplateGetResult>(null, url, data, CommonJsonSendType.POST, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
/// <summary>
/// 删除入群欢迎语素材
/// </summary>
/// <param name="accessTokenOrAppKey"></param>
/// <param name="template_id"></param>
/// <param name="agentid"></param>
/// <param name="timeOut"></param>
/// <returns></returns>
public static async Task<WorkJsonResult> GroupWelcomeTemplateDelAsync(string accessTokenOrAppKey, string template_id, long? agentid, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var data = new
{
template_id = template_id,
agentid = agentid
};
var url = string.Format(Config.ApiWorkHost + "/cgi-bin/externalcontact/group_welcome_template/del?access_token={0}", accessToken);
return await CommonJsonSend.SendAsync<WorkJsonResult>(null, url, data, CommonJsonSendType.POST, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
#endregion
#endregion
#endregion
}
}
| {
"content_hash": "eafea3651025ac5d34be79ce5c38568e",
"timestamp": "",
"source": "github",
"line_count": 1852,
"max_line_length": 254,
"avg_line_length": 46.95194384449244,
"alnum_prop": 0.603680064401127,
"repo_name": "JeffreySu/WeiXinMPSDK",
"id": "0c7f8e0dbc448ad8aa416a49e7d29321e766b906",
"size": "96709",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Senparc.Weixin.Work/Senparc.Weixin.Work/AdvancedAPIs/External/ExternalApi.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "7980825"
},
{
"name": "HTML",
"bytes": "560"
},
{
"name": "JavaScript",
"bytes": "214247"
}
],
"symlink_target": ""
} |
layout: archive
title: "Useful for Developers"
permalink: /collection-archive/
author_profile: true
---
{% capture written_label %}'None'{% endcapture %}
{% for collection in site.collections %}
{% unless collection.output == false or collection.label == "posts" %}
{% capture label %}{{ collection.label }}{% endcapture %}
{% if label != written_label %}
<h2 id="{{ label | slugify }}" class="archive__subtitle">{{ label }}</h2>
{% capture written_label %}{{ label }}{% endcapture %}
{% endif %}
{% endunless %}
{% for post in collection.docs %}
{% unless collection.output == false or collection.label == "posts" %}
{% include archive-single.html %}
{% endunless %}
{% endfor %}
{% endfor %}
| {
"content_hash": "5db6b8ee3e31782556571fa2623c89f8",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 79,
"avg_line_length": 33.72727272727273,
"alnum_prop": 0.6145552560646901,
"repo_name": "w9wen/w9wen.github.io",
"id": "05c0e7166f88e71b189e01ff20fbf393808d68bd",
"size": "746",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_pages/collection-archive.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "464877"
},
{
"name": "JavaScript",
"bytes": "217462"
},
{
"name": "Ruby",
"bytes": "1689"
}
],
"symlink_target": ""
} |
/* FileServer loads files from FileList.bin. Stores files in shared_files directory. */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer extends Server {
public static final int SERVER_PORT = 4321;
public static FileList fileList;
public FileServer() {
super(SERVER_PORT, "FilePile");
}
public FileServer(int _port) {
super(_port, "FilePile");
}
public void start() {
String fileFile = "FileList.bin";
ObjectInputStream fileStream;
File directory = new File("SystemKeys");
if (!directory.exists()) {
System.out.println("Error: No RSA keys have been generated.");
System.exit(0);
}
//This runs a thread that saves the lists on program exit
Runtime runtime = Runtime.getRuntime();
Thread catchExit = new Thread(new ShutDownListenerFS());
runtime.addShutdownHook(catchExit);
//Open user file to get user list
try {
FileInputStream fis = new FileInputStream(fileFile);
fileStream = new ObjectInputStream(fis);
fileList = (FileList) fileStream.readObject();
} catch (FileNotFoundException e) {
System.out.println("FileList Does Not Exist. Creating FileList...");
fileList = new FileList();
} catch (IOException e) {
System.out.println("Error reading from FileList file");
System.exit(-1);
} catch (ClassNotFoundException e) {
System.out.println("Error reading from FileList file");
System.exit(-1);
}
File file = new File("shared_files");
if (file.mkdir()) {
System.out.println("Created new shared_files directory");
} else if (file.exists()) {
System.out.println("Found shared_files directory");
} else {
System.out.println("Error creating shared_files directory");
}
//Autosave Daemon. Saves lists every 5 minutes
AutoSaveFS aSave = new AutoSaveFS();
aSave.setDaemon(true);
aSave.start();
boolean running = true;
try {
final ServerSocket serverSock = new ServerSocket(port);
System.out.printf("%s up and running\n", this.getClass().getName());
Socket sock = null;
Thread thread = null;
while (running) {
sock = serverSock.accept();
thread = new FileThread(sock);
thread.start();
}
System.out.printf("%s shut down\n", this.getClass().getName());
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace(System.err);
}
}
}
//This thread saves user and group lists
class ShutDownListenerFS implements Runnable {
public void run() {
System.out.println("Shutting down server");
ObjectOutputStream outStream;
try {
outStream = new ObjectOutputStream(new FileOutputStream("FileList.bin"));
outStream.writeObject(FileServer.fileList);
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace(System.err);
}
}
}
class AutoSaveFS extends Thread {
public void run() {
do {
try {
Thread.sleep(300000); //Save group and user lists every 5 minutes
System.out.println("Autosave file list...");
ObjectOutputStream outStream;
try {
outStream = new ObjectOutputStream(new FileOutputStream("FileList.bin"));
outStream.writeObject(FileServer.fileList);
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace(System.err);
}
} catch (Exception e) {
System.out.println("Autosave Interrupted");
}
} while (true);
}
}
| {
"content_hash": "26b3cadb071610ec3ebb7fc62d51813a",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 93,
"avg_line_length": 32.16417910447761,
"alnum_prop": 0.582830626450116,
"repo_name": "Bryan-Heim/CodingSamples",
"id": "1ca36a323723221f253d32bac593b802af3e819a",
"size": "4310",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Java/SecurityTermProject/src/FileServer.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "8273"
},
{
"name": "C",
"bytes": "104607"
},
{
"name": "HTML",
"bytes": "9884"
},
{
"name": "Java",
"bytes": "316308"
},
{
"name": "PHP",
"bytes": "68814"
}
],
"symlink_target": ""
} |
module Announcer
RSpec.describe Subscription do
let(:event_name) { :name }
let(:params) { Hash.new }
subject { Subscription.new(event_name, params.merge(instance: Instance.new))}
context 'with string event name' do
let(:event_name) { 'name' }
it 'should convert event_name to symbol' do
expect(subject.event_name).to eq :name
end
end
describe 'priority' do
let(:params) { { priority: priority } }
context 'integer priority' do
let(:priority) { 1 }
it { is_expected.to have_attributes(priority: 1) }
end
context 'default priority' do
let(:priority) { nil }
it { is_expected.to have_attributes(priority: 3) }
end
context 'symbol priority' do
let(:priority) { :low }
it { is_expected.to have_attributes(priority: 4) }
end
context 'string priority' do
let(:priority) { 'highest' }
it { is_expected.to have_attributes(priority: 1) }
end
context 'invalid symbol priority' do
let(:priority) { :bad }
it { expect { subject }.to raise_error(Errors::InvalidPriorityError, ':bad') }
end
context 'invalid string priority' do
let(:priority) { 'bad' }
it { expect { subject }.to raise_error(Errors::InvalidPriorityError, ':bad') }
end
context 'with integer priority below range' do
let(:priority) { 0 }
it { expect { subject }.to raise_error(Errors::InvalidPriorityError, '0') }
end
context 'with integer priority above range' do
let(:priority) { 6 }
it { expect { subject }.to raise_error(Errors::InvalidPriorityError, '6') }
end
context 'with floating-point priority' do
let(:priority) { 5.5 }
it { expect { subject }.to raise_error(Errors::InvalidPriorityError, '5.5') }
end
end # priority
describe 'subscription name' do
let(:params) { { name: 'subscription name' } }
it 'can be defined' do
is_expected.to have_attributes(name: 'subscription name')
end
end # subscription name
describe 'identifier' do
it 'raises error for duplicate identifers' do
expect { Subscription.new(event_name, instance: subject.instance) }. to(
raise_error(Errors::DuplicateIdentifierError, "give this subscription a unique name")
)
end
end # identifier
end
end
| {
"content_hash": "82fc9b6d3bb753acce31653f10d44fb4",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 95,
"avg_line_length": 30.4875,
"alnum_prop": 0.6084460844608446,
"repo_name": "ribbon/event_bus",
"id": "008dbfe3fc3db2b6b96facc2f5e950863cd53fbf",
"size": "2439",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/subscription_spec.rb",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "546"
},
{
"name": "HTML",
"bytes": "4246"
},
{
"name": "JavaScript",
"bytes": "599"
},
{
"name": "Ruby",
"bytes": "92588"
}
],
"symlink_target": ""
} |
<?xml version='1.0' encoding='utf-8' ?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "file:///C:/Program%20Files%20(x86)/Publican/DocBook_DTD/docbookx.dtd" [
<!ENTITY % BOOK_ENTITIES SYSTEM "cloudstack.ent">
%BOOK_ENTITIES;
]>
<section id="roles">
<title>Roles</title>
<para>
The CloudPlatform API supports three access roles:</para>
<orderedlist>
<listitem><para>Root Admin. Access to all features of the cloud, including both virtual and physical resource management.</para></listitem>
<listitem><para>Domain Admin. Access to only the virtual resources of the clouds that belong to the administrator’s domain.</para></listitem>
<listitem><para>User. Access to only the features that allow management of the user’s virtual instances, storage, and network.</para></listitem>
</orderedlist>
</section>
| {
"content_hash": "38fb4db510cc267cb1cae4d28471369c",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 147,
"avg_line_length": 52.25,
"alnum_prop": 0.7308612440191388,
"repo_name": "cinderella/incubator-cloudstack",
"id": "8e027278c2487ec5bc9bff20eb028eaedb0385ec",
"size": "840",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/en-US/roles.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "30051196"
},
{
"name": "JavaScript",
"bytes": "2530360"
},
{
"name": "Perl",
"bytes": "184903"
},
{
"name": "Python",
"bytes": "2076305"
},
{
"name": "Shell",
"bytes": "471280"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>weak-up-to: 21 s 🏆</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.9.0 / weak-up-to - 8.9.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
weak-up-to
<small>
8.9.0
<span class="label label-success">21 s 🏆</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-25 09:17:08 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-25 09:17:08 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler
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.9.0 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.02.3 The OCaml compiler (virtual package)
ocaml-base-compiler 4.02.3 Official 4.02.3 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "http://perso.ens-lyon.fr/damien.pous/upto/"
license: "GPL"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/WeakUpTo"]
depends: [
"ocaml"
"coq" {>= "8.9" & < "8.10~"}
]
tags: [
"keyword: weak bisimilarity"
"keyword: weak bisimulation"
"keyword: up-to techniques"
"keyword: termination"
"keyword: commutation"
"keyword: Newman's lemma"
"category: Computer Science/Concurrent Systems and Protocols/Theory of concurrent systems"
"date: 2005-02-22"
]
authors: [
"Damien Pous <damien.pous at ens-lyon.fr> [http://perso.ens-lyon.fr/damien.pous/]"
]
bug-reports: "https://github.com/coq-contribs/weak-up-to/issues"
dev-repo: "git+https://github.com/coq-contribs/weak-up-to.git"
synopsis: "New Up-to Techniques for Weak Bisimulation"
description: """
This contribution is the formalisation of a paper that appeared in
Proc. of ICALP 2005: "Up-to Techniques for Weak Bisimulation".
First we define a framework for defining up-to techniques for weak
bisimulation in a modular way. Then we prove the correctness of some
new up-to techniques, based on termination guarantees. Notably, a
generalisation of Newman's Lemma to commutation results is
established."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/weak-up-to/archive/v8.9.0.tar.gz"
checksum: "md5=6c91d9b73aee52981c01c0f5b300aafe"
}
</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-weak-up-to.8.9.0 coq.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</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>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-weak-up-to.8.9.0 coq.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>12 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-weak-up-to.8.9.0 coq.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>21 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 593 K</p>
<ul>
<li>57 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Settings.vo</code></li>
<li>46 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Relations.vo</code></li>
<li>42 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Theory.glob</code></li>
<li>40 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Diagrams.vo</code></li>
<li>35 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Settings.glob</code></li>
<li>34 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Relations.glob</code></li>
<li>31 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Diagrams.glob</code></li>
<li>27 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Theory.vo</code></li>
<li>25 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/WeakMonotonic.vo</code></li>
<li>23 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Applications.glob</code></li>
<li>20 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/WeakMonotonic.glob</code></li>
<li>19 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Controlled.vo</code></li>
<li>19 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Functions.vo</code></li>
<li>18 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Monotonic.vo</code></li>
<li>15 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Reductions.vo</code></li>
<li>15 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Controlled.glob</code></li>
<li>14 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Functions.glob</code></li>
<li>14 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Applications.vo</code></li>
<li>13 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Settings.v</code></li>
<li>13 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Monotonic.glob</code></li>
<li>13 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Diagrams.v</code></li>
<li>11 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Reductions.glob</code></li>
<li>10 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Relations.v</code></li>
<li>10 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Theory.v</code></li>
<li>7 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/WeakMonotonic.v</code></li>
<li>5 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Monotonic.v</code></li>
<li>5 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Controlled.v</code></li>
<li>5 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Applications.v</code></li>
<li>4 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Functions.v</code></li>
<li>4 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/WeakUpTo/Reductions.v</code></li>
</ul>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-weak-up-to.8.9.0</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": "f4c3da04592dba17faa759ae0d6b0056",
"timestamp": "",
"source": "github",
"line_count": 207,
"max_line_length": 159,
"avg_line_length": 52.56038647342995,
"alnum_prop": 0.5799632352941176,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "6ec3d694a627e2809ecbf996717138a8fa938589",
"size": "10905",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.02.3-2.0.6/released/8.9.0/weak-up-to/8.9.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?php
namespace PHPExiftool\Driver\Tag\FLIR;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class AboveColor extends AbstractTag
{
protected $Id = 6;
protected $Name = 'AboveColor';
protected $FullName = 'FLIR::PaletteInfo';
protected $GroupName = 'FLIR';
protected $g0 = 'APP1';
protected $g1 = 'FLIR';
protected $g2 = 'Image';
protected $Type = 'int8u';
protected $Writable = false;
protected $Description = 'Above Color';
protected $MaxLength = 3;
}
| {
"content_hash": "ffd29503dcec4910b171de8cd02d7936",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 46,
"avg_line_length": 15.783783783783784,
"alnum_prop": 0.6558219178082192,
"repo_name": "romainneutron/PHPExiftool",
"id": "44bf92e7799a4739b443d2d6ae8e57b8ec5e922e",
"size": "806",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/PHPExiftool/Driver/Tag/FLIR/AboveColor.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "22042446"
}
],
"symlink_target": ""
} |
<div class="navbar navbar-default navbar-static-top" ng-controller="NavbarCtrl">
<div class="container">
<div class="navbar-header">
<button class="navbar-toggle" type="button" ng-click="isCollapsed = !isCollapsed">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="/" class="navbar-brand">secret-lana</a>
</div>
<div collapse="isCollapsed" class="navbar-collapse collapse" id="navbar-main">
<ul class="nav navbar-nav">
<li ng-repeat="item in menu" ng-class="{active: isActive(item.link)}">
<a ng-href="{{item.link}}">{{item.title}}</a>
</li>
</ul>
</div>
</div>
</div>
| {
"content_hash": "83dc4a28daa799614199f08e18d46ff0",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 88,
"avg_line_length": 39.45,
"alnum_prop": 0.5906210392902408,
"repo_name": "richbs/secret-lana",
"id": "4213988d9727580f44f38d00e07dd38453324b0c",
"size": "789",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/components/navbar/navbar.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2336"
},
{
"name": "JavaScript",
"bytes": "39275"
}
],
"symlink_target": ""
} |
'use strict'
/* npm modules */
var Ajv = require('ajv');
var ajvErrors = require('ajv-errors')
/* exports */
module.exports = initGlobal
/**
* @function initGlobal
*
* initialize global data
*/
function initGlobal (args) {
// do nothing if global data already defined
if (global.__immutable_core_model__) {
return
}
// create new global object
var GLOBAL = global.__immutable_core_model__ = {
// number of concurrent related queries to allow per query
concurrency: 5,
// default to use binary columns for ids
defaultBinaryIds: true,
// default character set
defaultCharset: 'utf8',
// default compression setting
defaultCompression: true,
// default elastic search client
defaultElasticsearch: undefined,
// default database engine
defaultEngine: 'InnoDB',
// default insert delayed option for myisam tables
defaultInsertDelayed: false,
// map of models indexed by name
models: {},
}
// create validator as global object so that schemas will be shared
// between all model classes
GLOBAL.validator = new Ajv({
allErrors: true,
coerceTypes: 'array',
removeAdditional: true,
useDefaults: true,
v5: true,
})
ajvErrors(GLOBAL.validator)
} | {
"content_hash": "7d828ea521ea3b2278eb19da9c2652e4",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 71,
"avg_line_length": 27.24,
"alnum_prop": 0.6240822320117474,
"repo_name": "warncke/immutable-core-model",
"id": "201478cacd8f112c63cc034a1fea3f88284ca6c8",
"size": "1362",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/immutable-core-model/init-global.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "579237"
}
],
"symlink_target": ""
} |
package com.shansown.androidarchitecture.ui.bugreport;
import android.app.Dialog;
import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import com.shansown.androidarchitecture.R;
import static com.shansown.androidarchitecture.ui.bugreport.BugReportView.Report;
import static com.shansown.androidarchitecture.ui.bugreport.BugReportView.ReportDetailsListener;
public final class BugReportDialog extends AlertDialog implements ReportDetailsListener {
public interface ReportListener {
void onBugReportSubmit(Report report);
}
private ReportListener listener;
public BugReportDialog(Context context) {
super(context);
final BugReportView view =
(BugReportView) LayoutInflater.from(context).inflate(R.layout.bugreport_view, null);
view.setBugReportListener(this);
setTitle("Report a bug");
setView(view);
setButton(Dialog.BUTTON_NEGATIVE, "Cancel", (OnClickListener) null);
setButton(Dialog.BUTTON_POSITIVE, "Submit", (dialog, which) -> {
if (listener != null) {
listener.onBugReportSubmit(view.getReport());
}
});
}
public void setReportListener(ReportListener listener) {
this.listener = listener;
}
@Override protected void onStart() {
getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);
}
@Override public void onStateChanged(boolean valid) {
getButton(Dialog.BUTTON_POSITIVE).setEnabled(valid);
}
}
| {
"content_hash": "cb0363b3ad3b702d220d6c11aa5f934f",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 96,
"avg_line_length": 30.541666666666668,
"alnum_prop": 0.7551159618008185,
"repo_name": "ShansOwn/android-architecture",
"id": "45ebadcf66d2d91fa6fd938ba730a56d1d94ada7",
"size": "1466",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/internal/java/com/shansown/androidarchitecture/ui/bugreport/BugReportDialog.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "190845"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>cours-de-coq: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.13.1 / cours-de-coq - 8.5.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
cours-de-coq
<small>
8.5.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-10-22 14:17:30 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-22 14:17:30 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.13.1 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.5 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "matej.kosik@inria.fr"
homepage: "https://github.com/coq-contribs/cours-de-coq"
license: "Proprietary"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/CoursDeCoq"]
depends: [
"ocaml"
"coq" {>= "8.5" & < "8.6~"}
]
tags: [
"category:Miscellaneous/Coq Use Examples"
]
authors: [ "Frédéric Prost <>" "Gilles Kahn <>" ]
bug-reports: "https://github.com/coq-contribs/cours-de-coq/issues"
dev-repo: "git+https://github.com/coq-contribs/cours-de-coq.git"
synopsis: "Various examples of Coq proofs"
description: "Various simple examples of Coq proofs"
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/cours-de-coq/archive/v8.5.0.tar.gz"
checksum: "md5=957a863da31a9aa3abdb23491b0051e0"
}
</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-cours-de-coq.8.5.0 coq.8.13.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.13.1).
The following dependencies couldn't be met:
- coq-cours-de-coq -> coq < 8.6~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
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-cours-de-coq.8.5.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": "14bc0e75921fdbcda14fe4eda9c79489",
"timestamp": "",
"source": "github",
"line_count": 164,
"max_line_length": 159,
"avg_line_length": 41.3719512195122,
"alnum_prop": 0.5357406042741342,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "fc13d87f67cb56fe801be5debafc2aabfe862b3e",
"size": "6812",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.06.1-2.0.5/released/8.13.1/cours-de-coq/8.5.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package org.hisp.dhis.dxf2.metadata;
import java.util.Set;
/**
* Acts as a bridge between the importer and the persistence/cache layer.
* <p/>
* The flag {@code writeEnabled} is used to indicate if writing to the persistence layer
* is enabled or not.
*
* @author Morten Olav Hansen <mortenoh@gmail.com>
*/
public interface ObjectBridge
{
void init(); // FIXME rename or remove.. @PostConstruct worked badly here, some kind of workaround would be nice
void destroy(); // FIXME
/**
* Save object. Will save to persistence layer if {@code writeEnabled} is {@code true}.
*
* @param object Object to write
*/
void saveObject( Object object );
/**
* Save object. Will save to persistence layer if {@code writeEnabled} is {@code true}.
*
* @param object Object to write
*/
void saveObject( Object object, boolean clearSharing );
/**
* Update object. Will save to persistence layer if {@code writeEnabled} is {@code true}.
*
* @param object Object to update
*/
void updateObject( Object object );
/**
* Delete object. Will delete from persistence layer if {@code writeEnabled} is {@code true}.
*
* @param object Object to delete
*/
void deleteObject( Object object );
/**
* Get an object from the internal store. This object might not be a persisted object
* depending on the flag {@code writeEnabled}.
*
* @param object Object to match against
* @return Matched object or {@code null} if matched > 1 or no match found
*/
<T> T getObject( T object );
/**
* Return all matches for a given object. These objects might not be a persisted object
* depending on the flag {@code writeEnabled}.
*
* @param object Object to match against
* @return A collection of matched objects
*/
<T> Set<T> getObjects( T object );
/**
* Get all objects for a specified class. These objects might not be persisted
* depending on the flag {@code writeEnabled}.
*
* @param clazz Clazz to match against
* @return Collection of matches
*/
<T> Set<T> getAllObjects( Class<T> clazz );
/**
* Enable or disable writing to the persistence store.
*
* @param enabled {@code boolean} turning writing on or off
*/
void setWriteEnabled( boolean enabled );
/**
* Is persistence storage enabled?
*
* @return {@code boolean} indicating status of {@code writeEnabled}
*/
boolean isWriteEnabled();
/**
* Enable or disable preheating the internal cache. This should be left on for most cases,
* but for very small imports (1-10 objects) turning this off will generally speed up import by a factor of 100.
*
* @param enabled {@code boolean} turning preheating on or off
*/
void setPreheatCache( boolean enabled );
/**
* Is preheat cache enabled?
*
* @return {@code boolean} indicating status of {@code preheatCache}
*/
boolean isPreheatCache();
}
| {
"content_hash": "11f3ccbc1cf87a88095c1bb0c0e02ed3",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 116,
"avg_line_length": 29.805825242718445,
"alnum_prop": 0.6400651465798045,
"repo_name": "kakada/dhis2",
"id": "b73bd0968e76b9ce7e2c1fe4b92d2eba3589a40c",
"size": "4633",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/ObjectBridge.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "396164"
},
{
"name": "Game Maker Language",
"bytes": "20893"
},
{
"name": "HTML",
"bytes": "340997"
},
{
"name": "Java",
"bytes": "18116166"
},
{
"name": "JavaScript",
"bytes": "7103857"
},
{
"name": "Ruby",
"bytes": "1011"
},
{
"name": "Shell",
"bytes": "376"
},
{
"name": "XSLT",
"bytes": "24103"
}
],
"symlink_target": ""
} |
#include <aws/ec2/model/MemoryMiBRequest.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::Utils::Xml;
using namespace Aws::Utils;
namespace Aws
{
namespace EC2
{
namespace Model
{
MemoryMiBRequest::MemoryMiBRequest() :
m_min(0),
m_minHasBeenSet(false),
m_max(0),
m_maxHasBeenSet(false)
{
}
MemoryMiBRequest::MemoryMiBRequest(const XmlNode& xmlNode) :
m_min(0),
m_minHasBeenSet(false),
m_max(0),
m_maxHasBeenSet(false)
{
*this = xmlNode;
}
MemoryMiBRequest& MemoryMiBRequest::operator =(const XmlNode& xmlNode)
{
XmlNode resultNode = xmlNode;
if(!resultNode.IsNull())
{
XmlNode minNode = resultNode.FirstChild("Min");
if(!minNode.IsNull())
{
m_min = StringUtils::ConvertToInt32(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(minNode.GetText()).c_str()).c_str());
m_minHasBeenSet = true;
}
XmlNode maxNode = resultNode.FirstChild("Max");
if(!maxNode.IsNull())
{
m_max = StringUtils::ConvertToInt32(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(maxNode.GetText()).c_str()).c_str());
m_maxHasBeenSet = true;
}
}
return *this;
}
void MemoryMiBRequest::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
if(m_minHasBeenSet)
{
oStream << location << index << locationValue << ".Min=" << m_min << "&";
}
if(m_maxHasBeenSet)
{
oStream << location << index << locationValue << ".Max=" << m_max << "&";
}
}
void MemoryMiBRequest::OutputToStream(Aws::OStream& oStream, const char* location) const
{
if(m_minHasBeenSet)
{
oStream << location << ".Min=" << m_min << "&";
}
if(m_maxHasBeenSet)
{
oStream << location << ".Max=" << m_max << "&";
}
}
} // namespace Model
} // namespace EC2
} // namespace Aws
| {
"content_hash": "f9cf87c38982b4498e00975682a4be5c",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 135,
"avg_line_length": 22.40909090909091,
"alnum_prop": 0.6526369168356998,
"repo_name": "cedral/aws-sdk-cpp",
"id": "f7d0f71f094a5b0a279c50c8831e5ab60ab8070d",
"size": "2091",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-ec2/source/model/MemoryMiBRequest.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "294220"
},
{
"name": "C++",
"bytes": "428637022"
},
{
"name": "CMake",
"bytes": "862025"
},
{
"name": "Dockerfile",
"bytes": "11688"
},
{
"name": "HTML",
"bytes": "7904"
},
{
"name": "Java",
"bytes": "352201"
},
{
"name": "Python",
"bytes": "106761"
},
{
"name": "Shell",
"bytes": "10891"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template otherwise</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../proto/reference.html#header.boost.proto.transform.when_hpp" title="Header <boost/proto/transform/when.hpp>">
<link rel="prev" href="when_Grammar__idp203407488/impl.html" title="Struct template impl">
<link rel="next" href="external_transform.html" title="Struct external_transform">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="when_Grammar__idp203407488/impl.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../proto/reference.html#header.boost.proto.transform.when_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="external_transform.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.proto.otherwise"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template otherwise</span></h2>
<p>boost::proto::otherwise —
Syntactic sugar for <code class="computeroutput"><a class="link" href="when.html" title="Struct template when">proto::when</a>< <a class="link" href="_.html" title="Struct _">proto::_</a>, Fun ></code>,
for use in grammars to handle all the cases not yet handled.
</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../proto/reference.html#header.boost.proto.transform.when_hpp" title="Header <boost/proto/transform/when.hpp>">boost/proto/transform/when.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Fun<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="otherwise.html" title="Struct template otherwise">otherwise</a> <span class="special">:</span> <span class="keyword"></span> <a class="link" href="when.html" title="Struct template when">proto::when</a>< <a class="link" href="_.html" title="Struct _">proto::_</a>, Fun > <span class="special">{</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp385925232"></a><h2>Description</h2>
<p>
Use <code class="computeroutput">proto::otherwise<T></code> in your grammars as a synonym for
<code class="computeroutput"><a class="link" href="when.html" title="Struct template when">proto::when</a>< <a class="link" href="_.html" title="Struct _">proto::_</a>, Fun ></code>
as in the following transform which counts the number of terminals in an expression.
</p>
<p>
</p>
<pre class="programlisting"><span class="comment">// Count the terminals in an expression tree.</span>
<span class="comment">// Must be invoked with initial state == mpl::int_<0>().</span>
<span class="keyword">struct</span> <span class="identifier">CountLeaves</span> <span class="special">:</span>
<a class="link" href="or_.html" title="Struct template or_">proto::or_</a><span class="special"><</span>
<span class="identifier">proto</span><span class="special">::</span><span class="identifier">when</span><span class="special"><</span><a class="link" href="terminal.html" title="Struct template terminal">proto::terminal</a><span class="special"><</span><a class="link" href="_.html" title="Struct _">proto::_</a><span class="special">></span><span class="special">,</span> <span class="identifier">mpl</span><span class="special">::</span><span class="identifier">next</span><span class="special"><</span><a class="link" href="_state.html" title="Struct _state">proto::_state</a><span class="special">></span><span class="special">(</span><span class="special">)</span><span class="special">></span><span class="special">,</span>
<span class="identifier">proto</span><span class="special">::</span><span class="identifier">otherwise</span><span class="special"><</span><a class="link" href="fold.html" title="Struct template fold">proto::fold</a><span class="special"><</span><a class="link" href="_.html" title="Struct _">proto::_</a><span class="special">,</span> <a class="link" href="_state.html" title="Struct _state">proto::_state</a><span class="special">,</span> <span class="identifier">CountLeaves</span><span class="special">></span> <span class="special">></span>
<span class="special">></span>
<span class="special">{</span><span class="special">}</span><span class="special">;</span></pre>
<p>
</p>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2008 Eric Niebler<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="when_Grammar__idp203407488/impl.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../proto/reference.html#header.boost.proto.transform.when_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="external_transform.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "0f6020ee7bc00d28f2c251951e261679",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 751,
"avg_line_length": 92.4054054054054,
"alnum_prop": 0.6623281661304475,
"repo_name": "babycaseny/poedit",
"id": "7d31b189a423bdec2befa15f15aabb88a454220e",
"size": "6838",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "deps/boost/doc/html/boost/proto/otherwise.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "22780"
},
{
"name": "C++",
"bytes": "874973"
},
{
"name": "Inno Setup",
"bytes": "10822"
},
{
"name": "Objective-C",
"bytes": "4458"
},
{
"name": "Objective-C++",
"bytes": "12149"
},
{
"name": "Python",
"bytes": "3040"
},
{
"name": "Ruby",
"bytes": "220"
},
{
"name": "Shell",
"bytes": "10374"
}
],
"symlink_target": ""
} |
import {TmplAstTemplate} from '@angular/compiler';
import ts from 'typescript';
import {absoluteFrom, getSourceFileOrError} from '../../file_system';
import {runInEachFileSystem} from '../../file_system/testing';
import {getTokenAtPosition} from '../../util/src/typescript';
import {CompletionKind, GlobalCompletion, TemplateTypeChecker, TypeCheckingConfig} from '../api';
import {getClass, setup, TypeCheckingTarget} from '../testing';
runInEachFileSystem(() => {
describe('TemplateTypeChecker.getGlobalCompletions()', () => {
it('should return a completion point in the TCB for the component context', () => {
const {completions, program} = setupCompletions(`No special template needed`);
expect(completions.templateContext.size).toBe(0);
const {tcbPath, positionInFile} = completions.componentContext;
const tcbSf = getSourceFileOrError(program, tcbPath);
const node = getTokenAtPosition(tcbSf, positionInFile).parent;
if (!ts.isExpressionStatement(node)) {
return fail(`Expected a ts.ExpressionStatement`);
}
expect(node.expression.getText()).toEqual('this.');
// The position should be between the '.' and a following space.
expect(tcbSf.text.slice(positionInFile - 1, positionInFile + 1)).toEqual('. ');
});
it('should return additional completions for references and variables when available', () => {
const template = `
<div *ngFor="let user of users">
<div #innerRef></div>
<div *ngIf="user">
<div #notInScope></div>
</div>
</div>
<div #topLevelRef></div>
`;
const members = `users: string[];`;
// Embedded view in question is the first node in the template (index 0).
const {completions} = setupCompletions(template, members, 0);
expect(new Set(completions.templateContext.keys())).toEqual(new Set([
'innerRef', 'user', 'topLevelRef'
]));
});
it('should support shadowing between outer and inner templates ', () => {
const template = `
<div *ngFor="let user of users">
Within this template, 'user' should be a variable, not a reference.
</div>
<div #user>Out here, 'user' is the reference.</div>
`;
const members = `users: string[];`;
// Completions for the top level.
const {completions: topLevel} = setupCompletions(template, members);
// Completions within the embedded view at index 0.
const {completions: inNgFor} = setupCompletions(template, members, 0);
expect(topLevel.templateContext.has('user')).toBeTrue();
const userAtTopLevel = topLevel.templateContext.get('user')!;
expect(inNgFor.templateContext.has('user')).toBeTrue();
const userInNgFor = inNgFor.templateContext.get('user')!;
expect(userAtTopLevel.kind).toBe(CompletionKind.Reference);
expect(userInNgFor.kind).toBe(CompletionKind.Variable);
});
});
describe('TemplateTypeChecker scopes', () => {
it('should get directives and pipes in scope for a component', () => {
const MAIN_TS = absoluteFrom('/main.ts');
const {program, templateTypeChecker} = setup([{
fileName: MAIN_TS,
templates: {
'SomeCmp': 'Not important',
},
declarations: [
{
type: 'directive',
file: MAIN_TS,
name: 'OtherDir',
selector: 'other-dir',
},
{
type: 'pipe',
file: MAIN_TS,
name: 'OtherPipe',
pipeName: 'otherPipe',
}
],
source: `
export class SomeCmp {}
export class OtherDir {}
export class OtherPipe {}
export class SomeCmpModule {}
`
}]);
const sf = getSourceFileOrError(program, MAIN_TS);
const SomeCmp = getClass(sf, 'SomeCmp');
const directives = templateTypeChecker.getDirectivesInScope(SomeCmp) ?? [];
const pipes = templateTypeChecker.getPipesInScope(SomeCmp) ?? [];
expect(directives.map(dir => dir.selector)).toEqual(['other-dir']);
expect(pipes.map(pipe => pipe.name)).toEqual(['otherPipe']);
});
});
});
function setupCompletions(
template: string, componentMembers: string = '', inChildTemplateAtIndex: number|null = null): {
completions: GlobalCompletion,
program: ts.Program,
templateTypeChecker: TemplateTypeChecker,
component: ts.ClassDeclaration,
} {
const MAIN_TS = absoluteFrom('/main.ts');
const {templateTypeChecker, programStrategy} = setup(
[{
fileName: MAIN_TS,
templates: {'SomeCmp': template},
source: `export class SomeCmp { ${componentMembers} }`,
}],
({inlining: false, config: {enableTemplateTypeChecker: true}}));
const sf = getSourceFileOrError(programStrategy.getProgram(), MAIN_TS);
const SomeCmp = getClass(sf, 'SomeCmp');
let context: TmplAstTemplate|null = null;
if (inChildTemplateAtIndex !== null) {
const tmpl = templateTypeChecker.getTemplate(SomeCmp)![inChildTemplateAtIndex];
if (!(tmpl instanceof TmplAstTemplate)) {
throw new Error(
`AssertionError: expected TmplAstTemplate at index ${inChildTemplateAtIndex}`);
}
context = tmpl;
}
const completions = templateTypeChecker.getGlobalCompletions(context, SomeCmp, null!)!;
expect(completions).toBeDefined();
return {
completions,
program: programStrategy.getProgram(),
templateTypeChecker,
component: SomeCmp,
};
}
| {
"content_hash": "8f0d8ea1336978576ee08f19204b217c",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 99,
"avg_line_length": 38.227586206896554,
"alnum_prop": 0.6379217030488905,
"repo_name": "gkalpak/angular",
"id": "d6b0b763b743d9116401db6793a8ac8b29f0f9df",
"size": "5744",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__completion_spec.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "250831"
},
{
"name": "Dockerfile",
"bytes": "9419"
},
{
"name": "HTML",
"bytes": "563997"
},
{
"name": "JavaScript",
"bytes": "2420197"
},
{
"name": "Less",
"bytes": "80"
},
{
"name": "NASL",
"bytes": "7222"
},
{
"name": "SCSS",
"bytes": "132731"
},
{
"name": "Shell",
"bytes": "74185"
},
{
"name": "Starlark",
"bytes": "530150"
},
{
"name": "TypeScript",
"bytes": "23119152"
},
{
"name": "jq",
"bytes": "619"
}
],
"symlink_target": ""
} |
package org.loofer.weread.mvp.presenter;
import android.app.Application;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import org.loofer.framework.base.DefaultAdapter;
import org.loofer.framework.di.scope.ActivityScope;
import org.loofer.framework.mvp.BasePresenter;
import org.loofer.framework.utils.DeviceUtils;
import org.loofer.framework.utils.RxUtils;
import org.loofer.framework.utils.UiUtils;
import org.loofer.rxerrorhandler.core.RxErrorHandler;
import org.loofer.weread.mvp.contract.DailyContract;
import org.loofer.weread.mvp.model.entity.HomeItem;
import org.loofer.weread.mvp.ui.activity.AudioDetailActivity;
import org.loofer.weread.mvp.ui.activity.TextDetailActivity;
import org.loofer.weread.mvp.ui.activity.VideoDetailActivity;
import org.loofer.weread.mvp.ui.adapter.DailyAdapter;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;
/**
* ============================================================
* 版权: x x 版权所有(c)2017
*
* 作者:Loofer
* 版本:1.0
* 创建日期 :2017/1/13 10:42.
* 描述:
*
* 注:如果您修改了本类请填写以下内容作为记录,如非本人操作劳烦通知,谢谢!!!
* Modified Date Modify Content:
*
* ==========================================================
*/
@ActivityScope
public class DailyPresenter extends BasePresenter<DailyContract.Model, DailyContract.View> {
private RxErrorHandler mErrorHandler;
private Application mApplication;
private DailyAdapter mAdapter;
private List<HomeItem> mHomeItemList = new ArrayList<>();
private int mPage = 1;
private int model =4;
private String pageId = "0";
private String lastItemCreateTime = "0";
@Inject
public DailyPresenter(DailyContract.Model model, DailyContract.View rootView
, RxErrorHandler handler, Application application) {
super(model, rootView);
this.mErrorHandler = handler;
this.mApplication = application;
mAdapter = new DailyAdapter(mHomeItemList);
mRootView.setAdapter(mAdapter);//设置Adapter
// mAdapter.setOnItemClickListener(mOnRecyclerViewItemClickListener);
}
public void getListByPage(final boolean pullToRefresh) {
if (pullToRefresh) {
mPage = 1;
pageId = "0";
lastItemCreateTime = "0";
} else {
pageId = mAdapter.getLastItemId();
lastItemCreateTime = mAdapter.getLastItemCreateTime();
}
mModel.getListByPage(mPage, model, pageId, DeviceUtils.getDeviceId(mApplication), lastItemCreateTime)
.subscribeOn(Schedulers.io())
.doOnSubscribe(new Action0() {
@Override
public void call() {
if (mPage == 1)
mRootView.showLoading();//显示上拉刷新的进度条
else
mRootView.startLoadMore();
}
})
.subscribeOn(AndroidSchedulers.mainThread())
.observeOn(AndroidSchedulers.mainThread())
.doAfterTerminate(new Action0() {
@Override
public void call() {
if (mPage == 2)
mRootView.hideLoading();//隐藏上拉刷新的进度条
else
mRootView.endLoadMore();
}
})
.compose(RxUtils.<List<HomeItem>>bindToLifecycle(mRootView))//使用RXlifecycle,使subscription和activity一起销毁
.subscribe(new Subscriber<List<HomeItem>>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
mRootView.showOnFailure();
}
@Override
public void onNext(List<HomeItem> homeItemList) {
// int size = homeItemList.size();
// if (size > 0) {
if (mPage == 1)
mHomeItemList.clear();
for (HomeItem item : homeItemList) {
mHomeItemList.add(item);
}
mPage++;
mAdapter.notifyDataSetChanged();
// mRootView.updateListUI(baseJson.getData());
// } else {
// mRootView.showNoMore();
// }
}
}
);
}
DefaultAdapter.OnRecyclerViewItemClickListener mOnRecyclerViewItemClickListener = new DefaultAdapter.OnRecyclerViewItemClickListener() {
@Override
public void onItemClick(View view, Object data, int position) {
HomeItem item = (HomeItem) data;
int model = Integer.valueOf(item.getModel());
Intent intent;
switch (model) {
case 5:
Uri uri = Uri.parse(item.getHtml5());
intent = new Intent(Intent.ACTION_VIEW, uri);
UiUtils.startActivity(intent);
break;
case 3:
intent = new Intent(mApplication, AudioDetailActivity.class);
intent.putExtra("item", item);
UiUtils.startActivity(intent);
break;
case 2:
intent = new Intent(mApplication, VideoDetailActivity.class);
intent.putExtra("item", item);
UiUtils.startActivity(intent);
break;
case 1:
intent = new Intent(mApplication, TextDetailActivity.class);
intent.putExtra("item", item);
UiUtils.startActivity(intent);
break;
default:
intent = new Intent(mApplication, TextDetailActivity.class);
intent.putExtra("item", item);
UiUtils.startActivity(intent);
}
}
};
@Override
public void onDestroy() {
super.onDestroy();
this.mErrorHandler = null;
this.mApplication = null;
}
} | {
"content_hash": "67edf5a0010b65aba3315b3e0a04b236",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 140,
"avg_line_length": 37.01657458563536,
"alnum_prop": 0.5240298507462686,
"repo_name": "Loofer/WeRead",
"id": "d3d771b879fad24d6f795b389ae6df6145ca8ba0",
"size": "6880",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/org/loofer/weread/mvp/presenter/DailyPresenter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "947826"
}
],
"symlink_target": ""
} |
// MIT © 2017 azu
"use strict";
const fs = require("fs");
import {UseCase} from "almin";
import textlintAppRepository from "../../infra/repository/TextlintAppRepository";
export default class OpenNewFileUseCase extends UseCase {
static create() {
return new this({textlintAppRepository});
}
constructor({textlintAppRepository}) {
super();
this.textlintAppRepository = textlintAppRepository;
}
execute(filePath) {
return Promise.resolve().then(() => {
const text = fs.readFileSync(filePath, "utf-8");
/** @type {TextlintApp} */
const app = this.textlintAppRepository.lastUsed();
app.textlintEditor.openNewFile({
text,
filePath
});
this.textlintAppRepository.save(app);
});
}
}
| {
"content_hash": "cdfa5f7616fbfc7b733604efa2b5d5bd",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 81,
"avg_line_length": 29.20689655172414,
"alnum_prop": 0.5962219598583235,
"repo_name": "textlint/textlint-app",
"id": "f6088ddf51a6a935341c2a9fa10a835aacfe8ce0",
"size": "848",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/renderer/use-case/textlint-editor/OpenNewFileUseCase.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3782"
},
{
"name": "HTML",
"bytes": "269"
},
{
"name": "JavaScript",
"bytes": "87761"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.