text stringlengths 2 1.04M | meta dict |
|---|---|
layout: post
title: "Worldwide sales of Prius (Prii..."
---
Worldwide sales of Prius (Prii?) tops 1 million - | {
"content_hash": "f6c52e7ef1c8fa77295e390c372e0a6a",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 49,
"avg_line_length": 27.25,
"alnum_prop": 0.7064220183486238,
"repo_name": "briankirsten/briankirsten.github.com",
"id": "ec78c17f2da5dea9620fe17f5800970226ec17f9",
"size": "113",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2008-05-15-worldwide-sales-of-prius-(prii....html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10174"
},
{
"name": "JavaScript",
"bytes": "18"
}
],
"symlink_target": ""
} |
const { sep, join } = require('path');
const { spawn } = require('child_process');
const pathOffset = __dirname.split(sep).slice(-2).join(sep);
const fixturesPath = join(pathOffset, 'test/fixtures');
const env = {
...process.env,
NODE_ENV: 'customenv',
CONFIG_DIR: fixturesPath,
CONFIG_OVERRIDE_KEY: 'sandboxStuffs',
SANDBOX: 'true',
};
spawn('mocha', [], { env, stdio: 'inherit' });
| {
"content_hash": "c4fd97347f60f11897c031237b1fed65",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 60,
"avg_line_length": 26.466666666666665,
"alnum_prop": 0.6523929471032746,
"repo_name": "good-hood-gmbh/uni-config",
"id": "6c59deb9c3b8f33b98c0e203d3f510c26ff898aa",
"size": "397",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "2384"
}
],
"symlink_target": ""
} |
package com.edd.chat.admin.account;
import com.edd.chat.account.Account;
import com.edd.chat.account.AccountLookup;
import com.edd.chat.account.AccountRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AccountManagementService {
private static final Logger LOGGER = LoggerFactory.getLogger(AccountManagementService.class);
private final AccountRepository accountRepository;
private final AccountLookup accountLookup;
@Autowired
public AccountManagementService(AccountRepository accountRepository,
AccountLookup accountLookup) {
this.accountRepository = accountRepository;
this.accountLookup = accountLookup;
}
/**
* Manage other users account.
*
* @param id account id.
* @param details details to set to the account.
*/
public Account updateAccount(String id,
AccountManagementDetails details) {
Account account = accountLookup.getAccount(id);
account.setEnabled(details.isEnabled());
LOGGER.debug("Setting enabled to: {} of account: {}",
details.isEnabled(), account.getInternalUsername());
return accountRepository.save(account);
}
} | {
"content_hash": "ec53798c7a9f71291cbf88382f12e249",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 97,
"avg_line_length": 31.704545454545453,
"alnum_prop": 0.6996415770609319,
"repo_name": "Edvinas01/chat-rooms",
"id": "563e6370a4a3861fdb79f66a9c695cf0ca16b5d3",
"size": "1395",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/src/main/java/com/edd/chat/admin/account/AccountManagementService.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3814"
},
{
"name": "HTML",
"bytes": "1092"
},
{
"name": "Java",
"bytes": "86617"
},
{
"name": "JavaScript",
"bytes": "56234"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_112-google-v7) on Mon Dec 18 13:35:09 PST 2017 -->
<title>PerfStatsCollector.ThrowingSupplier</title>
<meta name="date" content="2017-12-18">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="PerfStatsCollector.ThrowingSupplier";
}
}
catch(err) {
}
//-->
var methods = {"i0":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/robolectric/util/PerfStatsCollector.ThrowingRunnable.html" title="interface in org.robolectric.util"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../org/robolectric/util/PerfStatsReporter.html" title="interface in org.robolectric.util"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/robolectric/util/PerfStatsCollector.ThrowingSupplier.html" target="_top">Frames</a></li>
<li><a href="PerfStatsCollector.ThrowingSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.robolectric.util</div>
<h2 title="Interface PerfStatsCollector.ThrowingSupplier" class="title">Interface PerfStatsCollector.ThrowingSupplier<T,F extends java.lang.Exception></h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../org/robolectric/util/PerfStatsCollector.html" title="class in org.robolectric.util">PerfStatsCollector</a></dd>
</dl>
<hr>
<br>
<pre>public static interface <span class="typeNameLabel">PerfStatsCollector.ThrowingSupplier<T,F extends java.lang.Exception></span></pre>
<div class="block"><p>Supplier that throws an exception.</p></div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code><a href="../../../org/robolectric/util/PerfStatsCollector.ThrowingSupplier.html" title="type parameter in PerfStatsCollector.ThrowingSupplier">T</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/util/PerfStatsCollector.ThrowingSupplier.html#get--">get</a></span>()</code> </td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="get--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>get</h4>
<pre><a href="../../../org/robolectric/util/PerfStatsCollector.ThrowingSupplier.html" title="type parameter in PerfStatsCollector.ThrowingSupplier">T</a> get()
throws <a href="../../../org/robolectric/util/PerfStatsCollector.ThrowingSupplier.html" title="type parameter in PerfStatsCollector.ThrowingSupplier">F</a> extends java.lang.Exception</pre>
<dl>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="../../../org/robolectric/util/PerfStatsCollector.ThrowingSupplier.html" title="type parameter in PerfStatsCollector.ThrowingSupplier">F</a> extends java.lang.Exception</code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><script type="text/javascript" src="../../../highlight.pack.js"></script>
<script type="text/javascript"><!--
hljs.initHighlightingOnLoad();
//--></script></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/robolectric/util/PerfStatsCollector.ThrowingRunnable.html" title="interface in org.robolectric.util"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../org/robolectric/util/PerfStatsReporter.html" title="interface in org.robolectric.util"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/robolectric/util/PerfStatsCollector.ThrowingSupplier.html" target="_top">Frames</a></li>
<li><a href="PerfStatsCollector.ThrowingSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "b5c19102181bccc7f66543ec0357bfdd",
"timestamp": "",
"source": "github",
"line_count": 233,
"max_line_length": 391,
"avg_line_length": 37.58369098712446,
"alnum_prop": 0.6527349548932283,
"repo_name": "robolectric/robolectric.github.io",
"id": "eeb35683d6687983d4c615fb636b12d808aa65bf",
"size": "8757",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "javadoc/3.6/org/robolectric/util/PerfStatsCollector.ThrowingSupplier.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "132673"
},
{
"name": "HTML",
"bytes": "277730"
},
{
"name": "JavaScript",
"bytes": "24371"
},
{
"name": "Ruby",
"bytes": "1051"
},
{
"name": "SCSS",
"bytes": "64100"
},
{
"name": "Shell",
"bytes": "481"
}
],
"symlink_target": ""
} |
package org.workcraft.serialisation;
import org.w3c.dom.Element;
import org.workcraft.dom.Container;
import org.workcraft.dom.Node;
import org.workcraft.exceptions.SerialisationException;
import org.workcraft.plugins.PluginInfo;
import org.workcraft.plugins.PluginProvider;
import org.workcraft.utils.XmlUtils;
import java.util.ArrayList;
import java.util.HashMap;
public class XMLSerialisationManager implements SerialiserFactory, NodeSerialiser {
private final HashMap<String, XMLSerialiser> serialisers = new HashMap<>();
private final DefaultNodeSerialiser nodeSerialiser = new DefaultNodeSerialiser(this, this);
private XMLSerialiserState state = null;
private void registerSerialiser(XMLSerialiser serialiser) {
serialisers.put(serialiser.getClassName(), serialiser);
}
@Override
public XMLSerialiser getSerialiserFor(Class<?> cls) {
return serialisers.get(cls.getName());
}
public void begin(ReferenceProducer internalReferenceResolver, ReferenceProducer externalReferenceResolver) {
state = new XMLSerialiserState(internalReferenceResolver, externalReferenceResolver);
}
public void end() {
state = null;
}
public void processPlugins(PluginProvider pp) {
for (PluginInfo<? extends XMLSerialiser> info : pp.getPlugins(XMLSerialiser.class)) {
registerSerialiser(info.getInstance());
}
}
@Override
public void serialise(Element element, Object object) throws SerialisationException {
element.setAttribute(XMLCommonAttributes.CLASS_ATTRIBUTE, object.getClass().getName());
nodeSerialiser.serialise(element, object, state.internalReferences, state.externalReferences);
if (object instanceof Container) {
Container container = (Container) object;
ArrayList<Node> children = new ArrayList<>(container.getChildren());
for (Node child : children) {
Element childElement = XmlUtils.createChildElement(XMLCommonAttributes.NODE_ATTRIBUTE, element);
serialise(childElement, child);
}
}
}
}
| {
"content_hash": "00edd0f06a5fae5eff30782e84bfd15b",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 113,
"avg_line_length": 36.23728813559322,
"alnum_prop": 0.724976613657624,
"repo_name": "danilovesky/workcraft",
"id": "966e4a6c2b06ae22626b017ec30e05fa6d49c78f",
"size": "2138",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "workcraft/WorkcraftCore/src/org/workcraft/serialisation/XMLSerialisationManager.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "GAP",
"bytes": "11313"
},
{
"name": "Java",
"bytes": "6366934"
},
{
"name": "JavaScript",
"bytes": "41903"
},
{
"name": "Kotlin",
"bytes": "3511"
},
{
"name": "Shell",
"bytes": "12685"
},
{
"name": "Verilog",
"bytes": "25409"
}
],
"symlink_target": ""
} |
package org.apache.hadoop.yarn.api;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.nio.ByteBuffer;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import org.apache.commons.lang.math.LongRange;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.security.proto.SecurityProtos.*;
import org.apache.hadoop.yarn.api.protocolrecords.*;
import org.apache.hadoop.yarn.api.protocolrecords.impl.pb.*;
import org.apache.hadoop.yarn.api.records.*;
import org.apache.hadoop.yarn.api.records.impl.pb.*;
import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.*;
import org.apache.hadoop.yarn.proto.YarnProtos.*;
import org.apache.hadoop.yarn.proto.YarnServiceProtos.*;
import org.apache.hadoop.yarn.server.api.protocolrecords.impl.pb.*;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
public class TestPBImplRecords {
static final Log LOG = LogFactory.getLog(TestPBImplRecords.class);
private static HashMap<Type, Object> typeValueCache = new HashMap<Type, Object>();
private static Random rand = new Random();
private static byte [] bytes = new byte[] {'1', '2', '3', '4'};
@SuppressWarnings({"rawtypes", "unchecked"})
private static Object genTypeValue(Type type) {
Object ret = typeValueCache.get(type);
if (ret != null) {
return ret;
}
// only use positive primitive values
if (type.equals(boolean.class)) {
return rand.nextBoolean();
} else if (type.equals(byte.class)) {
return bytes[rand.nextInt(4)];
} else if (type.equals(int.class)) {
return rand.nextInt(1000000);
} else if (type.equals(long.class)) {
return Long.valueOf(rand.nextInt(1000000));
} else if (type.equals(float.class)) {
return rand.nextFloat();
} else if (type.equals(double.class)) {
return rand.nextDouble();
} else if (type.equals(String.class)) {
return String.format("%c%c%c",
'a' + rand.nextInt(26),
'a' + rand.nextInt(26),
'a' + rand.nextInt(26));
} else if (type instanceof Class) {
Class clazz = (Class)type;
if (clazz.isArray()) {
Class compClass = clazz.getComponentType();
if (compClass != null) {
ret = Array.newInstance(compClass, 2);
Array.set(ret, 0, genTypeValue(compClass));
Array.set(ret, 1, genTypeValue(compClass));
}
} else if (clazz.isEnum()) {
Object [] values = clazz.getEnumConstants();
ret = values[rand.nextInt(values.length)];
} else if (clazz.equals(ByteBuffer.class)) {
// return new ByteBuffer every time
// to prevent potential side effects
ByteBuffer buff = ByteBuffer.allocate(4);
rand.nextBytes(buff.array());
return buff;
}
} else if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType)type;
Type rawType = pt.getRawType();
Type [] params = pt.getActualTypeArguments();
// only support EnumSet<T>, List<T>, Set<T>, Map<K,V>
if (rawType.equals(EnumSet.class)) {
if (params[0] instanceof Class) {
Class c = (Class)(params[0]);
return EnumSet.allOf(c);
}
} if (rawType.equals(List.class)) {
ret = Lists.newArrayList(genTypeValue(params[0]));
} else if (rawType.equals(Set.class)) {
ret = Sets.newHashSet(genTypeValue(params[0]));
} else if (rawType.equals(Map.class)) {
Map<Object, Object> map = Maps.newHashMap();
map.put(genTypeValue(params[0]), genTypeValue(params[1]));
ret = map;
}
}
if (ret == null) {
throw new IllegalArgumentException("type " + type + " is not supported");
}
typeValueCache.put(type, ret);
return ret;
}
/**
* this method generate record instance by calling newIntance
* using reflection, add register the generated value to typeValueCache
*/
@SuppressWarnings("rawtypes")
private static Object generateByNewInstance(Class clazz) throws Exception {
Object ret = typeValueCache.get(clazz);
if (ret != null) {
return ret;
}
Method newInstance = null;
Type [] paramTypes = new Type[0];
// get newInstance method with most parameters
for (Method m : clazz.getMethods()) {
int mod = m.getModifiers();
if (m.getDeclaringClass().equals(clazz) &&
Modifier.isPublic(mod) &&
Modifier.isStatic(mod) &&
m.getName().equals("newInstance")) {
Type [] pts = m.getGenericParameterTypes();
if (newInstance == null
|| (pts.length > paramTypes.length)) {
newInstance = m;
paramTypes = pts;
}
}
}
if (newInstance == null) {
throw new IllegalArgumentException("type " + clazz.getName() +
" does not have newInstance method");
}
Object [] args = new Object[paramTypes.length];
for (int i=0;i<args.length;i++) {
args[i] = genTypeValue(paramTypes[i]);
}
ret = newInstance.invoke(null, args);
typeValueCache.put(clazz, ret);
return ret;
}
@BeforeClass
public static void setup() throws Exception {
typeValueCache.put(LongRange.class, new LongRange(1000, 2000));
typeValueCache.put(URL.class, URL.newInstance(
"http", "localhost", 8080, "file0"));
typeValueCache.put(SerializedException.class,
SerializedException.newInstance(new IOException("exception for test")));
generateByNewInstance(ApplicationId.class);
generateByNewInstance(ApplicationAttemptId.class);
generateByNewInstance(ContainerId.class);
generateByNewInstance(Resource.class);
generateByNewInstance(ResourceBlacklistRequest.class);
generateByNewInstance(ResourceOption.class);
generateByNewInstance(LocalResource.class);
generateByNewInstance(Priority.class);
generateByNewInstance(NodeId.class);
generateByNewInstance(NodeReport.class);
generateByNewInstance(Token.class);
generateByNewInstance(NMToken.class);
generateByNewInstance(ResourceRequest.class);
generateByNewInstance(ApplicationAttemptReport.class);
generateByNewInstance(ApplicationResourceUsageReport.class);
generateByNewInstance(ApplicationReport.class);
generateByNewInstance(Container.class);
generateByNewInstance(ContainerLaunchContext.class);
generateByNewInstance(ApplicationSubmissionContext.class);
generateByNewInstance(ContainerReport.class);
generateByNewInstance(ContainerResourceDecrease.class);
generateByNewInstance(ContainerResourceIncrease.class);
generateByNewInstance(ContainerResourceIncreaseRequest.class);
generateByNewInstance(ContainerStatus.class);
generateByNewInstance(PreemptionContainer.class);
generateByNewInstance(PreemptionResourceRequest.class);
generateByNewInstance(PreemptionContainer.class);
generateByNewInstance(PreemptionContract.class);
generateByNewInstance(StrictPreemptionContract.class);
generateByNewInstance(PreemptionMessage.class);
generateByNewInstance(StartContainerRequest.class);
// genByNewInstance does not apply to QueueInfo, cause
// it is recursive(has sub queues)
typeValueCache.put(QueueInfo.class, QueueInfo.newInstance(
"root", 1.0f, 1.0f, 0.1f, null, null, QueueState.RUNNING));
generateByNewInstance(QueueUserACLInfo.class);
generateByNewInstance(YarnClusterMetrics.class);
}
private class GetSetPair {
public String propertyName;
public Method getMethod;
public Method setMethod;
public Type type;
public Object testValue;
@Override
public String toString() {
return String.format("{ name=%s, class=%s, value=%s }", propertyName,
type, testValue);
}
}
private <R> Map<String, GetSetPair> getGetSetPairs(Class<R> recordClass)
throws Exception {
Map<String, GetSetPair> ret = new HashMap<String, GetSetPair>();
Method [] methods = recordClass.getDeclaredMethods();
// get all get methods
for (int i = 0; i < methods.length; i++) {
Method m = methods[i];
int mod = m.getModifiers();
if (m.getDeclaringClass().equals(recordClass) &&
Modifier.isPublic(mod) &&
(!Modifier.isStatic(mod))) {
String name = m.getName();
if (name.equals("getProto")) {
continue;
}
if ((name.length() > 3) && name.startsWith("get") &&
(m.getParameterTypes().length == 0)) {
String propertyName = name.substring(3);
Type valueType = m.getGenericReturnType();
GetSetPair p = ret.get(propertyName);
if (p == null) {
p = new GetSetPair();
p.propertyName = propertyName;
p.type = valueType;
p.getMethod = m;
ret.put(propertyName, p);
} else {
Assert.fail("Multiple get method with same name: " + recordClass
+ p.propertyName);
}
}
}
}
// match get methods with set methods
for (int i = 0; i < methods.length; i++) {
Method m = methods[i];
int mod = m.getModifiers();
if (m.getDeclaringClass().equals(recordClass) &&
Modifier.isPublic(mod) &&
(!Modifier.isStatic(mod))) {
String name = m.getName();
if (name.startsWith("set") && (m.getParameterTypes().length == 1)) {
String propertyName = name.substring(3);
Type valueType = m.getGenericParameterTypes()[0];
GetSetPair p = ret.get(propertyName);
if (p != null && p.type.equals(valueType)) {
p.setMethod = m;
}
}
}
}
// exclude incomplete get/set pair, and generate test value
Iterator<Entry<String, GetSetPair>> itr = ret.entrySet().iterator();
while (itr.hasNext()) {
Entry<String, GetSetPair> cur = itr.next();
GetSetPair gsp = cur.getValue();
if ((gsp.getMethod == null) ||
(gsp.setMethod == null)) {
LOG.info(String.format("Exclude protential property: %s\n", gsp.propertyName));
itr.remove();
} else {
LOG.info(String.format("New property: %s type: %s", gsp.toString(), gsp.type));
gsp.testValue = genTypeValue(gsp.type);
LOG.info(String.format(" testValue: %s\n", gsp.testValue));
}
}
return ret;
}
private <R, P> void validatePBImplRecord(Class<R> recordClass,
Class<P> protoClass)
throws Exception {
LOG.info(String.format("Validate %s %s\n", recordClass.getName(),
protoClass.getName()));
Constructor<R> emptyConstructor = recordClass.getConstructor();
Constructor<R> pbConstructor = recordClass.getConstructor(protoClass);
Method getProto = recordClass.getDeclaredMethod("getProto");
Map<String, GetSetPair> getSetPairs = getGetSetPairs(recordClass);
R origRecord = emptyConstructor.newInstance();
for (GetSetPair gsp : getSetPairs.values()) {
gsp.setMethod.invoke(origRecord, gsp.testValue);
}
Object ret = getProto.invoke(origRecord);
Assert.assertNotNull(recordClass.getName() + "#getProto returns null", ret);
if (!(protoClass.isAssignableFrom(ret.getClass()))) {
Assert.fail("Illegal getProto method return type: " + ret.getClass());
}
R deserRecord = pbConstructor.newInstance(ret);
Assert.assertEquals("whole " + recordClass + " records should be equal",
origRecord, deserRecord);
for (GetSetPair gsp : getSetPairs.values()) {
Object origValue = gsp.getMethod.invoke(origRecord);
Object deserValue = gsp.getMethod.invoke(deserRecord);
Assert.assertEquals("property " + recordClass.getName() + "#"
+ gsp.propertyName + " should be equal", origValue, deserValue);
}
}
@Test
public void testAllocateRequestPBImpl() throws Exception {
validatePBImplRecord(AllocateRequestPBImpl.class, AllocateRequestProto.class);
}
@Test
public void testAllocateResponsePBImpl() throws Exception {
validatePBImplRecord(AllocateResponsePBImpl.class, AllocateResponseProto.class);
}
@Test
public void testCancelDelegationTokenRequestPBImpl() throws Exception {
validatePBImplRecord(CancelDelegationTokenRequestPBImpl.class,
CancelDelegationTokenRequestProto.class);
}
@Test
public void testCancelDelegationTokenResponsePBImpl() throws Exception {
validatePBImplRecord(CancelDelegationTokenResponsePBImpl.class,
CancelDelegationTokenResponseProto.class);
}
@Test
public void testFinishApplicationMasterRequestPBImpl() throws Exception {
validatePBImplRecord(FinishApplicationMasterRequestPBImpl.class,
FinishApplicationMasterRequestProto.class);
}
@Test
public void testFinishApplicationMasterResponsePBImpl() throws Exception {
validatePBImplRecord(FinishApplicationMasterResponsePBImpl.class,
FinishApplicationMasterResponseProto.class);
}
@Test
public void testGetApplicationAttemptReportRequestPBImpl() throws Exception {
validatePBImplRecord(GetApplicationAttemptReportRequestPBImpl.class,
GetApplicationAttemptReportRequestProto.class);
}
@Test
public void testGetApplicationAttemptReportResponsePBImpl() throws Exception {
validatePBImplRecord(GetApplicationAttemptReportResponsePBImpl.class,
GetApplicationAttemptReportResponseProto.class);
}
@Test
public void testGetApplicationAttemptsRequestPBImpl() throws Exception {
validatePBImplRecord(GetApplicationAttemptsRequestPBImpl.class,
GetApplicationAttemptsRequestProto.class);
}
@Test
public void testGetApplicationAttemptsResponsePBImpl() throws Exception {
validatePBImplRecord(GetApplicationAttemptsResponsePBImpl.class,
GetApplicationAttemptsResponseProto.class);
}
@Test
public void testGetApplicationReportRequestPBImpl() throws Exception {
validatePBImplRecord(GetApplicationReportRequestPBImpl.class,
GetApplicationReportRequestProto.class);
}
@Test
public void testGetApplicationReportResponsePBImpl() throws Exception {
validatePBImplRecord(GetApplicationReportResponsePBImpl.class,
GetApplicationReportResponseProto.class);
}
@Test
public void testGetApplicationsRequestPBImpl() throws Exception {
validatePBImplRecord(GetApplicationsRequestPBImpl.class,
GetApplicationsRequestProto.class);
}
@Test
public void testGetApplicationsResponsePBImpl() throws Exception {
validatePBImplRecord(GetApplicationsResponsePBImpl.class,
GetApplicationsResponseProto.class);
}
@Test
public void testGetClusterMetricsRequestPBImpl() throws Exception {
validatePBImplRecord(GetClusterMetricsRequestPBImpl.class,
GetClusterMetricsRequestProto.class);
}
@Test
public void testGetClusterMetricsResponsePBImpl() throws Exception {
validatePBImplRecord(GetClusterMetricsResponsePBImpl.class,
GetClusterMetricsResponseProto.class);
}
@Test
public void testGetClusterNodesRequestPBImpl() throws Exception {
validatePBImplRecord(GetClusterNodesRequestPBImpl.class,
GetClusterNodesRequestProto.class);
}
@Test
public void testGetClusterNodesResponsePBImpl() throws Exception {
validatePBImplRecord(GetClusterNodesResponsePBImpl.class,
GetClusterNodesResponseProto.class);
}
@Test
public void testGetContainerReportRequestPBImpl() throws Exception {
validatePBImplRecord(GetContainerReportRequestPBImpl.class,
GetContainerReportRequestProto.class);
}
@Test
public void testGetContainerReportResponsePBImpl() throws Exception {
validatePBImplRecord(GetContainerReportResponsePBImpl.class,
GetContainerReportResponseProto.class);
}
@Test
public void testGetContainersRequestPBImpl() throws Exception {
validatePBImplRecord(GetContainersRequestPBImpl.class,
GetContainersRequestProto.class);
}
@Test
public void testGetContainersResponsePBImpl() throws Exception {
validatePBImplRecord(GetContainersResponsePBImpl.class,
GetContainersResponseProto.class);
}
@Test
public void testGetContainerStatusesRequestPBImpl() throws Exception {
validatePBImplRecord(GetContainerStatusesRequestPBImpl.class,
GetContainerStatusesRequestProto.class);
}
@Test
public void testGetContainerStatusesResponsePBImpl() throws Exception {
validatePBImplRecord(GetContainerStatusesResponsePBImpl.class,
GetContainerStatusesResponseProto.class);
}
@Test
public void testGetDelegationTokenRequestPBImpl() throws Exception {
validatePBImplRecord(GetDelegationTokenRequestPBImpl.class,
GetDelegationTokenRequestProto.class);
}
@Test
public void testGetDelegationTokenResponsePBImpl() throws Exception {
validatePBImplRecord(GetDelegationTokenResponsePBImpl.class,
GetDelegationTokenResponseProto.class);
}
@Test
public void testGetNewApplicationRequestPBImpl() throws Exception {
validatePBImplRecord(GetNewApplicationRequestPBImpl.class,
GetNewApplicationRequestProto.class);
}
@Test
public void testGetNewApplicationResponsePBImpl() throws Exception {
validatePBImplRecord(GetNewApplicationResponsePBImpl.class,
GetNewApplicationResponseProto.class);
}
@Test
public void testGetQueueInfoRequestPBImpl() throws Exception {
validatePBImplRecord(GetQueueInfoRequestPBImpl.class,
GetQueueInfoRequestProto.class);
}
@Test
public void testGetQueueInfoResponsePBImpl() throws Exception {
validatePBImplRecord(GetQueueInfoResponsePBImpl.class,
GetQueueInfoResponseProto.class);
}
@Test
public void testGetQueueUserAclsInfoRequestPBImpl() throws Exception {
validatePBImplRecord(GetQueueUserAclsInfoRequestPBImpl.class,
GetQueueUserAclsInfoRequestProto.class);
}
@Test
public void testGetQueueUserAclsInfoResponsePBImpl() throws Exception {
validatePBImplRecord(GetQueueUserAclsInfoResponsePBImpl.class,
GetQueueUserAclsInfoResponseProto.class);
}
@Test
public void testKillApplicationRequestPBImpl() throws Exception {
validatePBImplRecord(KillApplicationRequestPBImpl.class,
KillApplicationRequestProto.class);
}
@Test
public void testKillApplicationResponsePBImpl() throws Exception {
validatePBImplRecord(KillApplicationResponsePBImpl.class,
KillApplicationResponseProto.class);
}
@Test
public void testMoveApplicationAcrossQueuesRequestPBImpl() throws Exception {
validatePBImplRecord(MoveApplicationAcrossQueuesRequestPBImpl.class,
MoveApplicationAcrossQueuesRequestProto.class);
}
@Test
public void testMoveApplicationAcrossQueuesResponsePBImpl() throws Exception {
validatePBImplRecord(MoveApplicationAcrossQueuesResponsePBImpl.class,
MoveApplicationAcrossQueuesResponseProto.class);
}
@Test
public void testRegisterApplicationMasterRequestPBImpl() throws Exception {
validatePBImplRecord(RegisterApplicationMasterRequestPBImpl.class,
RegisterApplicationMasterRequestProto.class);
}
@Test
public void testRegisterApplicationMasterResponsePBImpl() throws Exception {
validatePBImplRecord(RegisterApplicationMasterResponsePBImpl.class,
RegisterApplicationMasterResponseProto.class);
}
@Test
public void testRenewDelegationTokenRequestPBImpl() throws Exception {
validatePBImplRecord(RenewDelegationTokenRequestPBImpl.class,
RenewDelegationTokenRequestProto.class);
}
@Test
public void testRenewDelegationTokenResponsePBImpl() throws Exception {
validatePBImplRecord(RenewDelegationTokenResponsePBImpl.class,
RenewDelegationTokenResponseProto.class);
}
@Test
public void testStartContainerRequestPBImpl() throws Exception {
validatePBImplRecord(StartContainerRequestPBImpl.class,
StartContainerRequestProto.class);
}
@Test
public void testStartContainersRequestPBImpl() throws Exception {
validatePBImplRecord(StartContainersRequestPBImpl.class,
StartContainersRequestProto.class);
}
@Test
public void testStartContainersResponsePBImpl() throws Exception {
validatePBImplRecord(StartContainersResponsePBImpl.class,
StartContainersResponseProto.class);
}
@Test
public void testStopContainersRequestPBImpl() throws Exception {
validatePBImplRecord(StopContainersRequestPBImpl.class,
StopContainersRequestProto.class);
}
@Test
public void testStopContainersResponsePBImpl() throws Exception {
validatePBImplRecord(StopContainersResponsePBImpl.class,
StopContainersResponseProto.class);
}
@Test
public void testSubmitApplicationRequestPBImpl() throws Exception {
validatePBImplRecord(SubmitApplicationRequestPBImpl.class,
SubmitApplicationRequestProto.class);
}
@Test
public void testSubmitApplicationResponsePBImpl() throws Exception {
validatePBImplRecord(SubmitApplicationResponsePBImpl.class,
SubmitApplicationResponseProto.class);
}
@Test
@Ignore
// ignore cause ApplicationIdPBImpl is immutable
public void testApplicationAttemptIdPBImpl() throws Exception {
validatePBImplRecord(ApplicationAttemptIdPBImpl.class,
ApplicationAttemptIdProto.class);
}
@Test
public void testApplicationAttemptReportPBImpl() throws Exception {
validatePBImplRecord(ApplicationAttemptReportPBImpl.class,
ApplicationAttemptReportProto.class);
}
@Test
@Ignore
// ignore cause ApplicationIdPBImpl is immutable
public void testApplicationIdPBImpl() throws Exception {
validatePBImplRecord(ApplicationIdPBImpl.class, ApplicationIdProto.class);
}
@Test
public void testApplicationReportPBImpl() throws Exception {
validatePBImplRecord(ApplicationReportPBImpl.class,
ApplicationReportProto.class);
}
@Test
public void testApplicationResourceUsageReportPBImpl() throws Exception {
validatePBImplRecord(ApplicationResourceUsageReportPBImpl.class,
ApplicationResourceUsageReportProto.class);
}
@Test
public void testApplicationSubmissionContextPBImpl() throws Exception {
validatePBImplRecord(ApplicationSubmissionContextPBImpl.class,
ApplicationSubmissionContextProto.class);
}
@Test
@Ignore
// ignore cause ApplicationIdPBImpl is immutable
public void testContainerIdPBImpl() throws Exception {
validatePBImplRecord(ContainerIdPBImpl.class, ContainerIdProto.class);
}
@Test
public void testContainerLaunchContextPBImpl() throws Exception {
validatePBImplRecord(ContainerLaunchContextPBImpl.class,
ContainerLaunchContextProto.class);
}
@Test
public void testContainerPBImpl() throws Exception {
validatePBImplRecord(ContainerPBImpl.class, ContainerProto.class);
}
@Test
public void testContainerReportPBImpl() throws Exception {
validatePBImplRecord(ContainerReportPBImpl.class, ContainerReportProto.class);
}
@Test
public void testContainerResourceDecreasePBImpl() throws Exception {
validatePBImplRecord(ContainerResourceDecreasePBImpl.class,
ContainerResourceDecreaseProto.class);
}
@Test
public void testContainerResourceIncreasePBImpl() throws Exception {
validatePBImplRecord(ContainerResourceIncreasePBImpl.class,
ContainerResourceIncreaseProto.class);
}
@Test
public void testContainerResourceIncreaseRequestPBImpl() throws Exception {
validatePBImplRecord(ContainerResourceIncreaseRequestPBImpl.class,
ContainerResourceIncreaseRequestProto.class);
}
@Test
public void testContainerStatusPBImpl() throws Exception {
validatePBImplRecord(ContainerStatusPBImpl.class, ContainerStatusProto.class);
}
@Test
public void testLocalResourcePBImpl() throws Exception {
validatePBImplRecord(LocalResourcePBImpl.class, LocalResourceProto.class);
}
@Test
public void testNMTokenPBImpl() throws Exception {
validatePBImplRecord(NMTokenPBImpl.class, NMTokenProto.class);
}
@Test
@Ignore
// ignore cause ApplicationIdPBImpl is immutable
public void testNodeIdPBImpl() throws Exception {
validatePBImplRecord(NodeIdPBImpl.class, NodeIdProto.class);
}
@Test
public void testNodeReportPBImpl() throws Exception {
validatePBImplRecord(NodeReportPBImpl.class, NodeReportProto.class);
}
@Test
public void testPreemptionContainerPBImpl() throws Exception {
validatePBImplRecord(PreemptionContainerPBImpl.class,
PreemptionContainerProto.class);
}
@Test
public void testPreemptionContractPBImpl() throws Exception {
validatePBImplRecord(PreemptionContractPBImpl.class,
PreemptionContractProto.class);
}
@Test
public void testPreemptionMessagePBImpl() throws Exception {
validatePBImplRecord(PreemptionMessagePBImpl.class,
PreemptionMessageProto.class);
}
@Test
public void testPreemptionResourceRequestPBImpl() throws Exception {
validatePBImplRecord(PreemptionResourceRequestPBImpl.class,
PreemptionResourceRequestProto.class);
}
@Test
public void testPriorityPBImpl() throws Exception {
validatePBImplRecord(PriorityPBImpl.class, PriorityProto.class);
}
@Test
public void testQueueInfoPBImpl() throws Exception {
validatePBImplRecord(QueueInfoPBImpl.class, QueueInfoProto.class);
}
@Test
public void testQueueUserACLInfoPBImpl() throws Exception {
validatePBImplRecord(QueueUserACLInfoPBImpl.class,
QueueUserACLInfoProto.class);
}
@Test
public void testResourceBlacklistRequestPBImpl() throws Exception {
validatePBImplRecord(ResourceBlacklistRequestPBImpl.class,
ResourceBlacklistRequestProto.class);
}
@Test
@Ignore
// ignore as ResourceOptionPBImpl is immutable
public void testResourceOptionPBImpl() throws Exception {
validatePBImplRecord(ResourceOptionPBImpl.class, ResourceOptionProto.class);
}
@Test
public void testResourcePBImpl() throws Exception {
validatePBImplRecord(ResourcePBImpl.class, ResourceProto.class);
}
@Test
public void testResourceRequestPBImpl() throws Exception {
validatePBImplRecord(ResourceRequestPBImpl.class, ResourceRequestProto.class);
}
@Test
public void testSerializedExceptionPBImpl() throws Exception {
validatePBImplRecord(SerializedExceptionPBImpl.class,
SerializedExceptionProto.class);
}
@Test
public void testStrictPreemptionContractPBImpl() throws Exception {
validatePBImplRecord(StrictPreemptionContractPBImpl.class,
StrictPreemptionContractProto.class);
}
@Test
public void testTokenPBImpl() throws Exception {
validatePBImplRecord(TokenPBImpl.class, TokenProto.class);
}
@Test
public void testURLPBImpl() throws Exception {
validatePBImplRecord(URLPBImpl.class, URLProto.class);
}
@Test
public void testYarnClusterMetricsPBImpl() throws Exception {
validatePBImplRecord(YarnClusterMetricsPBImpl.class,
YarnClusterMetricsProto.class);
}
@Test
public void testRefreshAdminAclsRequestPBImpl() throws Exception {
validatePBImplRecord(RefreshAdminAclsRequestPBImpl.class,
RefreshAdminAclsRequestProto.class);
}
@Test
public void testRefreshAdminAclsResponsePBImpl() throws Exception {
validatePBImplRecord(RefreshAdminAclsResponsePBImpl.class,
RefreshAdminAclsResponseProto.class);
}
@Test
public void testRefreshNodesRequestPBImpl() throws Exception {
validatePBImplRecord(RefreshNodesRequestPBImpl.class,
RefreshNodesRequestProto.class);
}
@Test
public void testRefreshNodesResponsePBImpl() throws Exception {
validatePBImplRecord(RefreshNodesResponsePBImpl.class,
RefreshNodesResponseProto.class);
}
@Test
public void testRefreshQueuesRequestPBImpl() throws Exception {
validatePBImplRecord(RefreshQueuesRequestPBImpl.class,
RefreshQueuesRequestProto.class);
}
@Test
public void testRefreshQueuesResponsePBImpl() throws Exception {
validatePBImplRecord(RefreshQueuesResponsePBImpl.class,
RefreshQueuesResponseProto.class);
}
@Test
public void testRefreshServiceAclsRequestPBImpl() throws Exception {
validatePBImplRecord(RefreshServiceAclsRequestPBImpl.class,
RefreshServiceAclsRequestProto.class);
}
@Test
public void testRefreshServiceAclsResponsePBImpl() throws Exception {
validatePBImplRecord(RefreshServiceAclsResponsePBImpl.class,
RefreshServiceAclsResponseProto.class);
}
@Test
public void testRefreshSuperUserGroupsConfigurationRequestPBImpl()
throws Exception {
validatePBImplRecord(RefreshSuperUserGroupsConfigurationRequestPBImpl.class,
RefreshSuperUserGroupsConfigurationRequestProto.class);
}
@Test
public void testRefreshSuperUserGroupsConfigurationResponsePBImpl()
throws Exception {
validatePBImplRecord(RefreshSuperUserGroupsConfigurationResponsePBImpl.class,
RefreshSuperUserGroupsConfigurationResponseProto.class);
}
@Test
public void testRefreshUserToGroupsMappingsRequestPBImpl() throws Exception {
validatePBImplRecord(RefreshUserToGroupsMappingsRequestPBImpl.class,
RefreshUserToGroupsMappingsRequestProto.class);
}
@Test
public void testRefreshUserToGroupsMappingsResponsePBImpl() throws Exception {
validatePBImplRecord(RefreshUserToGroupsMappingsResponsePBImpl.class,
RefreshUserToGroupsMappingsResponseProto.class);
}
@Test
public void testUpdateNodeResourceRequestPBImpl() throws Exception {
validatePBImplRecord(UpdateNodeResourceRequestPBImpl.class,
UpdateNodeResourceRequestProto.class);
}
@Test
public void testUpdateNodeResourceResponsePBImpl() throws Exception {
validatePBImplRecord(UpdateNodeResourceResponsePBImpl.class,
UpdateNodeResourceResponseProto.class);
}
}
| {
"content_hash": "4178dce19f3675bc367ea71a65de4667",
"timestamp": "",
"source": "github",
"line_count": 879,
"max_line_length": 87,
"avg_line_length": 34.49488054607509,
"alnum_prop": 0.7409716038389235,
"repo_name": "jonathangizmo/HadoopDistJ",
"id": "c6572e9f387707b9394421bc48fbf249fca08441",
"size": "31127",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/api/TestPBImplRecords.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AspectJ",
"bytes": "29602"
},
{
"name": "C",
"bytes": "1201880"
},
{
"name": "C++",
"bytes": "87387"
},
{
"name": "CSS",
"bytes": "44021"
},
{
"name": "Erlang",
"bytes": "232"
},
{
"name": "Java",
"bytes": "43792925"
},
{
"name": "JavaScript",
"bytes": "22681"
},
{
"name": "Perl",
"bytes": "19540"
},
{
"name": "Python",
"bytes": "11309"
},
{
"name": "Shell",
"bytes": "273691"
},
{
"name": "TeX",
"bytes": "19322"
},
{
"name": "XSLT",
"bytes": "20949"
}
],
"symlink_target": ""
} |
Copyright (c) 2014 Eric Mountain
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# Originally based on [HTLM5 Boilerplate](http://html5boilerplate.com/)
Copyright (c) HTML5 Boilerplate
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
| {
"content_hash": "685c967fb3a079c7c7153711b1b220db",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 79,
"avg_line_length": 52.095238095238095,
"alnum_prop": 0.8043875685557587,
"repo_name": "EricMountain/TaskSlayer",
"id": "2b266adb30dc304b26c81665f7983425751d334d",
"size": "2203",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LICENSE.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "24139"
},
{
"name": "CSS",
"bytes": "13761"
},
{
"name": "HTML",
"bytes": "9210"
},
{
"name": "JavaScript",
"bytes": "49377"
}
],
"symlink_target": ""
} |
namespace Protocol
{
static int MessageResourcesQueryACKHandler( MessageResourcesQueryACK msg )
{
// UserDefineHandler Begin
// Your Codes here!
return 0;
// UserDefineHandler End
}
} // End of namespace Protocol
#endif // !Message_Resources_Query_ACK_HANDLER_HPP_
| {
"content_hash": "3b1d6d79661a8febce7813d8b140b53c",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 78,
"avg_line_length": 25.916666666666668,
"alnum_prop": 0.6655948553054662,
"repo_name": "Yhgenomics/maraton-cli",
"id": "24e30a9b1058fe138eea2ecccc87312275790845",
"size": "451",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/msghandler/MessageResourcesQueryACKHandler.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "726508"
},
{
"name": "C++",
"bytes": "401512"
},
{
"name": "Shell",
"bytes": "467"
}
],
"symlink_target": ""
} |
package com.microsoft.azure.management.network.v2019_02_01;
import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.arm.resources.models.Resource;
import com.microsoft.azure.arm.resources.models.GroupableResourceCore;
import com.microsoft.azure.arm.resources.models.HasResourceGroup;
import com.microsoft.azure.arm.model.Refreshable;
import com.microsoft.azure.arm.model.Updatable;
import com.microsoft.azure.arm.model.Appliable;
import com.microsoft.azure.arm.model.Creatable;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.network.v2019_02_01.implementation.NetworkManager;
import java.util.List;
import com.microsoft.azure.SubResource;
import com.microsoft.azure.management.network.v2019_02_01.implementation.SubnetInner;
import com.microsoft.azure.management.network.v2019_02_01.implementation.VirtualNetworkPeeringInner;
import com.microsoft.azure.management.network.v2019_02_01.implementation.VirtualNetworkInner;
/**
* Type representing VirtualNetwork.
*/
public interface VirtualNetwork extends HasInner<VirtualNetworkInner>, Resource, GroupableResourceCore<NetworkManager, VirtualNetworkInner>, HasResourceGroup, Refreshable<VirtualNetwork>, Updatable<VirtualNetwork.Update>, HasManager<NetworkManager> {
/**
* @return the addressSpace value.
*/
AddressSpace addressSpace();
/**
* @return the ddosProtectionPlan value.
*/
SubResource ddosProtectionPlan();
/**
* @return the dhcpOptions value.
*/
DhcpOptions dhcpOptions();
/**
* @return the enableDdosProtection value.
*/
Boolean enableDdosProtection();
/**
* @return the enableVmProtection value.
*/
Boolean enableVmProtection();
/**
* @return the etag value.
*/
String etag();
/**
* @return the provisioningState value.
*/
String provisioningState();
/**
* @return the resourceGuid value.
*/
String resourceGuid();
/**
* @return the subnets value.
*/
List<Subnet> subnets();
/**
* @return the virtualNetworkPeerings value.
*/
List<VirtualNetworkPeering> virtualNetworkPeerings();
/**
* The entirety of the VirtualNetwork definition.
*/
interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithCreate {
}
/**
* Grouping of VirtualNetwork definition stages.
*/
interface DefinitionStages {
/**
* The first stage of a VirtualNetwork definition.
*/
interface Blank extends GroupableResourceCore.DefinitionWithRegion<WithGroup> {
}
/**
* The stage of the VirtualNetwork definition allowing to specify the resource group.
*/
interface WithGroup extends GroupableResourceCore.DefinitionStages.WithGroup<WithCreate> {
}
/**
* The stage of the virtualnetwork definition allowing to specify AddressSpace.
*/
interface WithAddressSpace {
/**
* Specifies addressSpace.
* @param addressSpace The AddressSpace that contains an array of IP address ranges that can be used by subnets
* @return the next definition stage
*/
WithCreate withAddressSpace(AddressSpace addressSpace);
}
/**
* The stage of the virtualnetwork definition allowing to specify DdosProtectionPlan.
*/
interface WithDdosProtectionPlan {
/**
* Specifies ddosProtectionPlan.
* @param ddosProtectionPlan The DDoS protection plan associated with the virtual network
* @return the next definition stage
*/
WithCreate withDdosProtectionPlan(SubResource ddosProtectionPlan);
}
/**
* The stage of the virtualnetwork definition allowing to specify DhcpOptions.
*/
interface WithDhcpOptions {
/**
* Specifies dhcpOptions.
* @param dhcpOptions The dhcpOptions that contains an array of DNS servers available to VMs deployed in the virtual network
* @return the next definition stage
*/
WithCreate withDhcpOptions(DhcpOptions dhcpOptions);
}
/**
* The stage of the virtualnetwork definition allowing to specify EnableDdosProtection.
*/
interface WithEnableDdosProtection {
/**
* Specifies enableDdosProtection.
* @param enableDdosProtection Indicates if DDoS protection is enabled for all the protected resources in the virtual network. It requires a DDoS protection plan associated with the resource
* @return the next definition stage
*/
WithCreate withEnableDdosProtection(Boolean enableDdosProtection);
}
/**
* The stage of the virtualnetwork definition allowing to specify EnableVmProtection.
*/
interface WithEnableVmProtection {
/**
* Specifies enableVmProtection.
* @param enableVmProtection Indicates if VM protection is enabled for all the subnets in the virtual network
* @return the next definition stage
*/
WithCreate withEnableVmProtection(Boolean enableVmProtection);
}
/**
* The stage of the virtualnetwork definition allowing to specify Etag.
*/
interface WithEtag {
/**
* Specifies etag.
* @param etag Gets a unique read-only string that changes whenever the resource is updated
* @return the next definition stage
*/
WithCreate withEtag(String etag);
}
/**
* The stage of the virtualnetwork definition allowing to specify ProvisioningState.
*/
interface WithProvisioningState {
/**
* Specifies provisioningState.
* @param provisioningState The provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'
* @return the next definition stage
*/
WithCreate withProvisioningState(String provisioningState);
}
/**
* The stage of the virtualnetwork definition allowing to specify ResourceGuid.
*/
interface WithResourceGuid {
/**
* Specifies resourceGuid.
* @param resourceGuid The resourceGuid property of the Virtual Network resource
* @return the next definition stage
*/
WithCreate withResourceGuid(String resourceGuid);
}
/**
* The stage of the virtualnetwork definition allowing to specify Subnets.
*/
interface WithSubnets {
/**
* Specifies subnets.
* @param subnets A list of subnets in a Virtual Network
* @return the next definition stage
*/
WithCreate withSubnets(List<SubnetInner> subnets);
}
/**
* The stage of the virtualnetwork definition allowing to specify VirtualNetworkPeerings.
*/
interface WithVirtualNetworkPeerings {
/**
* Specifies virtualNetworkPeerings.
* @param virtualNetworkPeerings A list of peerings in a Virtual Network
* @return the next definition stage
*/
WithCreate withVirtualNetworkPeerings(List<VirtualNetworkPeeringInner> virtualNetworkPeerings);
}
/**
* The stage of the definition which contains all the minimum required inputs for
* the resource to be created (via {@link WithCreate#create()}), but also allows
* for any other optional settings to be specified.
*/
interface WithCreate extends Creatable<VirtualNetwork>, Resource.DefinitionWithTags<WithCreate>, DefinitionStages.WithAddressSpace, DefinitionStages.WithDdosProtectionPlan, DefinitionStages.WithDhcpOptions, DefinitionStages.WithEnableDdosProtection, DefinitionStages.WithEnableVmProtection, DefinitionStages.WithEtag, DefinitionStages.WithProvisioningState, DefinitionStages.WithResourceGuid, DefinitionStages.WithSubnets, DefinitionStages.WithVirtualNetworkPeerings {
}
}
/**
* The template for a VirtualNetwork update operation, containing all the settings that can be modified.
*/
interface Update extends Appliable<VirtualNetwork>, Resource.UpdateWithTags<Update>, UpdateStages.WithAddressSpace, UpdateStages.WithDdosProtectionPlan, UpdateStages.WithDhcpOptions, UpdateStages.WithEnableDdosProtection, UpdateStages.WithEnableVmProtection, UpdateStages.WithEtag, UpdateStages.WithProvisioningState, UpdateStages.WithResourceGuid, UpdateStages.WithSubnets, UpdateStages.WithVirtualNetworkPeerings {
}
/**
* Grouping of VirtualNetwork update stages.
*/
interface UpdateStages {
/**
* The stage of the virtualnetwork update allowing to specify AddressSpace.
*/
interface WithAddressSpace {
/**
* Specifies addressSpace.
* @param addressSpace The AddressSpace that contains an array of IP address ranges that can be used by subnets
* @return the next update stage
*/
Update withAddressSpace(AddressSpace addressSpace);
}
/**
* The stage of the virtualnetwork update allowing to specify DdosProtectionPlan.
*/
interface WithDdosProtectionPlan {
/**
* Specifies ddosProtectionPlan.
* @param ddosProtectionPlan The DDoS protection plan associated with the virtual network
* @return the next update stage
*/
Update withDdosProtectionPlan(SubResource ddosProtectionPlan);
}
/**
* The stage of the virtualnetwork update allowing to specify DhcpOptions.
*/
interface WithDhcpOptions {
/**
* Specifies dhcpOptions.
* @param dhcpOptions The dhcpOptions that contains an array of DNS servers available to VMs deployed in the virtual network
* @return the next update stage
*/
Update withDhcpOptions(DhcpOptions dhcpOptions);
}
/**
* The stage of the virtualnetwork update allowing to specify EnableDdosProtection.
*/
interface WithEnableDdosProtection {
/**
* Specifies enableDdosProtection.
* @param enableDdosProtection Indicates if DDoS protection is enabled for all the protected resources in the virtual network. It requires a DDoS protection plan associated with the resource
* @return the next update stage
*/
Update withEnableDdosProtection(Boolean enableDdosProtection);
}
/**
* The stage of the virtualnetwork update allowing to specify EnableVmProtection.
*/
interface WithEnableVmProtection {
/**
* Specifies enableVmProtection.
* @param enableVmProtection Indicates if VM protection is enabled for all the subnets in the virtual network
* @return the next update stage
*/
Update withEnableVmProtection(Boolean enableVmProtection);
}
/**
* The stage of the virtualnetwork update allowing to specify Etag.
*/
interface WithEtag {
/**
* Specifies etag.
* @param etag Gets a unique read-only string that changes whenever the resource is updated
* @return the next update stage
*/
Update withEtag(String etag);
}
/**
* The stage of the virtualnetwork update allowing to specify ProvisioningState.
*/
interface WithProvisioningState {
/**
* Specifies provisioningState.
* @param provisioningState The provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'
* @return the next update stage
*/
Update withProvisioningState(String provisioningState);
}
/**
* The stage of the virtualnetwork update allowing to specify ResourceGuid.
*/
interface WithResourceGuid {
/**
* Specifies resourceGuid.
* @param resourceGuid The resourceGuid property of the Virtual Network resource
* @return the next update stage
*/
Update withResourceGuid(String resourceGuid);
}
/**
* The stage of the virtualnetwork update allowing to specify Subnets.
*/
interface WithSubnets {
/**
* Specifies subnets.
* @param subnets A list of subnets in a Virtual Network
* @return the next update stage
*/
Update withSubnets(List<SubnetInner> subnets);
}
/**
* The stage of the virtualnetwork update allowing to specify VirtualNetworkPeerings.
*/
interface WithVirtualNetworkPeerings {
/**
* Specifies virtualNetworkPeerings.
* @param virtualNetworkPeerings A list of peerings in a Virtual Network
* @return the next update stage
*/
Update withVirtualNetworkPeerings(List<VirtualNetworkPeeringInner> virtualNetworkPeerings);
}
}
}
| {
"content_hash": "e27bb4e606c8cdf4e64c5aad3e89f6ff",
"timestamp": "",
"source": "github",
"line_count": 356,
"max_line_length": 476,
"avg_line_length": 38.575842696629216,
"alnum_prop": 0.6396999927182698,
"repo_name": "navalev/azure-sdk-for-java",
"id": "6110265bc838b1060591efdecb5ad8dd8a5c2440",
"size": "13963",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "sdk/network/mgmt-v2019_02_01/src/main/java/com/microsoft/azure/management/network/v2019_02_01/VirtualNetwork.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "7230"
},
{
"name": "CSS",
"bytes": "5411"
},
{
"name": "Groovy",
"bytes": "1570436"
},
{
"name": "HTML",
"bytes": "29221"
},
{
"name": "Java",
"bytes": "250218562"
},
{
"name": "JavaScript",
"bytes": "15605"
},
{
"name": "PowerShell",
"bytes": "30924"
},
{
"name": "Python",
"bytes": "42119"
},
{
"name": "Shell",
"bytes": "1408"
}
],
"symlink_target": ""
} |
.class Lcom/android/systemui/servicebox/KeyguardServiceBoxContainer$2;
.super Lcom/android/systemui/KnoxStateMonitorCallback;
.source "KeyguardServiceBoxContainer.java"
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Lcom/android/systemui/servicebox/KeyguardServiceBoxContainer;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x0
name = null
.end annotation
# instance fields
.field final synthetic this$0:Lcom/android/systemui/servicebox/KeyguardServiceBoxContainer;
# direct methods
.method constructor <init>(Lcom/android/systemui/servicebox/KeyguardServiceBoxContainer;)V
.locals 0
iput-object p1, p0, Lcom/android/systemui/servicebox/KeyguardServiceBoxContainer$2;->this$0:Lcom/android/systemui/servicebox/KeyguardServiceBoxContainer;
invoke-direct {p0}, Lcom/android/systemui/KnoxStateMonitorCallback;-><init>()V
return-void
.end method
# virtual methods
.method public onUpdateLockscreenHiddenItems()V
.locals 1
iget-object v0, p0, Lcom/android/systemui/servicebox/KeyguardServiceBoxContainer$2;->this$0:Lcom/android/systemui/servicebox/KeyguardServiceBoxContainer;
invoke-static {v0}, Lcom/android/systemui/servicebox/KeyguardServiceBoxContainer;->-get7(Lcom/android/systemui/servicebox/KeyguardServiceBoxContainer;)Lcom/android/systemui/servicebox/pages/clock/KeyguardOwnerInfoView;
move-result-object v0
invoke-virtual {v0}, Lcom/android/systemui/servicebox/pages/clock/KeyguardOwnerInfoView;->updateOwnerInfo()V
iget-object v0, p0, Lcom/android/systemui/servicebox/KeyguardServiceBoxContainer$2;->this$0:Lcom/android/systemui/servicebox/KeyguardServiceBoxContainer;
invoke-static {v0}, Lcom/android/systemui/servicebox/KeyguardServiceBoxContainer;->-get10(Lcom/android/systemui/servicebox/KeyguardServiceBoxContainer;)Lcom/android/systemui/servicebox/pages/KeyguardServiceBoxPageAdapter;
move-result-object v0
invoke-virtual {v0}, Lcom/android/systemui/servicebox/pages/KeyguardServiceBoxPageAdapter;->onUpdateLockscreenHiddenItems()V
iget-object v0, p0, Lcom/android/systemui/servicebox/KeyguardServiceBoxContainer$2;->this$0:Lcom/android/systemui/servicebox/KeyguardServiceBoxContainer;
invoke-static {v0}, Lcom/android/systemui/servicebox/KeyguardServiceBoxContainer;->-wrap6(Lcom/android/systemui/servicebox/KeyguardServiceBoxContainer;)V
return-void
.end method
| {
"content_hash": "ef6dae9402ddef6318e6f9f37395ea60",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 225,
"avg_line_length": 42.03448275862069,
"alnum_prop": 0.8166529942575882,
"repo_name": "BatMan-Rom/ModdedFiles",
"id": "f1c7d5e8fa5453f83b021e5d049e3a725c80f7c3",
"size": "2438",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SystemUI/smali/com/android/systemui/servicebox/KeyguardServiceBoxContainer$2.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "15069"
},
{
"name": "HTML",
"bytes": "139176"
},
{
"name": "Smali",
"bytes": "541934400"
}
],
"symlink_target": ""
} |
<?php
namespace Swarming\SubscribePro\Test\Unit\Gateway\Request;
use Magento\Payment\Gateway\Data\PaymentDataObjectInterface;
use Magento\Sales\Model\Order\Payment;
use Magento\Vault\Model\Ui\VaultConfigProvider;
use Swarming\SubscribePro\Gateway\Helper\SubjectReader;
use Swarming\SubscribePro\Gateway\Request\PaymentDataBuilder;
class PaymentDataBuilderTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Swarming\SubscribePro\Gateway\Helper\SubjectReader
*/
protected $subjectReaderMock;
/**
* @var \Swarming\SubscribePro\Gateway\Request\PaymentDataBuilder
*/
protected $paymentDataBuilder;
protected function setUp(): void
{
$this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class)
->disableOriginalConstructor()->getMock();
$this->paymentDataBuilder = new PaymentDataBuilder($this->subjectReaderMock);
}
public function testBuild()
{
$subject = ['subject'];
$result = [
PaymentDataBuilder::PAYMENT_METHOD_TOKEN => ['info'],
VaultConfigProvider::IS_ACTIVE_CODE => 'active'
];
$paymentInfoMock = $this->getMockBuilder(Payment::class)
->disableOriginalConstructor()
->getMock();
$paymentInfoMock->expects($this->at(0))
->method('getAdditionalInformation')
->with(PaymentDataBuilder::PAYMENT_METHOD_TOKEN)
->willReturn(['info']);
$paymentInfoMock->expects($this->at(1))
->method('getAdditionalInformation')
->with(VaultConfigProvider::IS_ACTIVE_CODE)
->willReturn('active');
$paymentDOMock = $this->getMockBuilder(PaymentDataObjectInterface::class)->getMock();
$paymentDOMock->expects($this->once())->method('getPayment')->willReturn($paymentInfoMock);
$this->subjectReaderMock->expects($this->once())
->method('readPayment')
->with($subject)
->willReturn($paymentDOMock);
$this->assertEquals($result, $this->paymentDataBuilder->build($subject));
}
}
| {
"content_hash": "3a011ce63bc4f3b1e7703a997bc8e4fc",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 104,
"avg_line_length": 35.16393442622951,
"alnum_prop": 0.661072261072261,
"repo_name": "subscribepro/subscribepro-magento2-ext",
"id": "d98751b3a2f1885977081a3bcd10556f75c52c54",
"size": "2145",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "Test/Unit/Gateway/Request/PaymentDataBuilderTest.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "77813"
},
{
"name": "JavaScript",
"bytes": "122664"
},
{
"name": "Less",
"bytes": "11377"
},
{
"name": "PHP",
"bytes": "1602312"
},
{
"name": "Shell",
"bytes": "41"
}
],
"symlink_target": ""
} |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
module CpuSpec where
import Control.Monad.State
import Data.Char (toUpper)
import Data.Proxy
import GHC.TypeLits
import GHC.Word
import Numeric (showHex)
import Cpu
import Cpu.Instruction
import Executor
import Test.Tasty.Hspec
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck as QC
spec :: Spec
spec = do
readWithModeSpec
writeWithModeSpec
-- Initialize the Cpu setting the register
initCpuForX x = initCpu { _x = (X x) }
initCpuForY y = initCpu { _y = (Y y) }
genProg :: Ram
genProg = initRamZero //
[ (0x0000, 0xA9), (0x0001,0xDE) -- LDA ZeroPage
, (0x0002, 0xEA), (0x00DE,0xF2),(0x00DF,0xA1)
, (0x0050, 0xAD), (0x0051, 0xF2), (0x0052, 0x33), (0x33F2, 0x00)
]
------------------------------------------------------------------------------------------
-- Read
------------------------------------------------------------------------------------------
readWithModeSpec = do
describe "readWithMode" $ do
describe "Immediate" $
it "should return byte at PC + 1" $
let ((byte,_), _) = runState (readWithMode Immediate) (genProg,initCpu)
in byte `shouldBe` 0xDE
describe "ZeroPage" $
it "should return the value at the address pointed to by PC + 1" $
let ((byte,_), _) = runState (readWithMode ZeroPage) (genProg, initCpu)
in byte `shouldBe` 0xF2
describe "ZeroPageX" $ do
let run x = runState (readWithMode ZeroPageX) (genProg, initCpuForX x)
it "should return the value at the address built with the value at the address PC + 1, added to the X register" $
let x = 0x01
((byte,_), _) = run x
in byte `shouldBe` 0xA1
-- With ZeroPageX the address of the value is calculated by:
-- 1. Getting the 8-bit zero page address from the instruction (mem[pc + 1]).
-- 2. Adding the value of the x register to it.
it "should wrap around if (mem[pc + 1] + X > 0xFF)" $
let x = 0x23
((byte,_), _) = run x
in byte `shouldBe` 0xDE
describe "ZeroPageY" $ do
let run y = runState (readWithMode ZeroPageY) (genProg, initCpuForY y)
it "should return the value at the address built with the value at the address PC + 1, added to the Y register" $
let y = 0x01
((byte,_), _) = run y
in byte `shouldBe` 0xA1
it "should wrap around if (mem[pc + 1] + Y > 0xFF)" $
let y = 0x23
((byte,_), _) = run y
in byte `shouldBe` 0xDE
------------------------------------------------------------------------------------------
-- Write
------------------------------------------------------------------------------------------
writeWithModeSpec = do
describe "writeWithMode" $ do
let byte = 0x05
describe "ZeroPage" $
it "should write to the address given by the value at pc + 1" $
let (_, (ram, _)) = runState (writeWithMode ZeroPage byte) (genProg, initCpu)
in (ram ! 0xDE) `shouldBe` byte
describe "ZeroPageX" $ do
let run x = runState (writeWithMode ZeroPageX byte) (genProg, initCpuForX x)
it "should write to the address given by ZeroPageX addressing" $
let x = 0x01
(_, (ram, _)) = run x
in (ram ! 0xDF) `shouldBe` byte
it "should wrap around if (mem[pc + 1] + X > 0xFF)" $
let x = 0x23
(_, (ram, _)) = run x
in (ram ! 0x01) `shouldBe` byte
describe "ZeroPageY" $ do
let run y = runState (writeWithMode ZeroPageY byte) (genProg, initCpuForY y)
it "should write to the address given by ZeroPageY addressing" $
let y = 0x01
(_, (ram, _)) = run y
in (ram ! 0x0DF) `shouldBe` byte
it "should wrap around if (mem[pc + 1] + X > 0xFF)" $
let y = 0x23
(_, (ram,_)) = run y
in (ram ! 0x01) `shouldBe` byte
describe "Absolute" $
it "should read address high and low bytes in correct order" $
let (_, (ram, _)) = runState (writeWithMode Absolute byte) (genProg, initCpu { _pc = (PC 0x50) })
in (ram ! 0x33F2) `shouldBe` byte
| {
"content_hash": "a8c7d4d7c8768e5156d8eba38c8fc5b7",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 119,
"avg_line_length": 33.41129032258065,
"alnum_prop": 0.5498431088583152,
"repo_name": "wayofthepie/emu-mos-6502",
"id": "ed20b45ccd3c3c56c04a16341612a6064ef62c19",
"size": "4143",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/CpuSpec.hs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Haskell",
"bytes": "26435"
},
{
"name": "Nix",
"bytes": "754"
}
],
"symlink_target": ""
} |
const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const UglifyJSPlugin = require("uglifyjs-webpack-plugin");
const productionPath = "new";
const publicPath = process.env.NODE_ENV === "development" ? "/" : `/${productionPath}/`;
process.noDeprecation = true;
var config = {
entry: path.resolve(__dirname, "./src/js/app.jsx"),
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js",
publicPath,
},
resolve: {
extensions: [ ".js", ".jsx", ".json" ]
},
devtool: "source-map",
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: "babel-loader",
query: {
"presets": [ "es2015", "react", "stage-1" ],
"plugins": [ "transform-decorators-legacy" ]
},
},
{
test: /\.scss$/,
exclude: /node_modules/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader" },
]
},
{
test: /\.css$/,
exclude: /node_modules/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
]
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
exclude: /node_modules/,
use: [
{
loader: "file-loader",
options: {
hash: "sha512",
digest: "hex",
name: "[hash].[ext]"
}
},
{
loader: "image-webpack-loader",
options: {
bypassOnDebug: true,
optipng: {
optimizationLevel: true
},
gifsicle: {
interlaced: true
}
}
},
]
},
]
},
externals: {
"cheerio": "window",
"react/addons": true,
"react/lib/ExecutionEnvironment": true,
"react/lib/ReactContext": true
},
plugins: [
new HtmlWebpackPlugin({
title: "Half Man Half Machine",
template: "./src/html/index.html"
}),
new webpack.LoaderOptionsPlugin({
debug: true
}),
new webpack.DefinePlugin({
"process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV || "development"),
"global.productionPath": JSON.stringify(productionPath),
"global.publicPath": JSON.stringify(publicPath)
})
],
devServer: {
contentBase: path.resolve(__dirname),
port: 3000,
https: false
}
};
// if (process.env.NODE_ENV === "production") {
// config.plugins.push(
// new UglifyJSPlugin()
// );
// }
if (process.env.DEVTOOLS_ENABLED) {
config.plugins.push(
new webpack.DefinePlugin({
"process.env": {
DEVTOOLS_ENABLED: true
}
})
);
}
module.exports = config;
| {
"content_hash": "288bb504f64cdbdbb7d445722e821527",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 90,
"avg_line_length": 29.77310924369748,
"alnum_prop": 0.4036127575500988,
"repo_name": "wesleysmyth/hmhm",
"id": "afc00c1ae0813449217135604fcf420d777f7860",
"size": "3543",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "webpack.config.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10585"
},
{
"name": "HTML",
"bytes": "525"
},
{
"name": "JavaScript",
"bytes": "50836"
}
],
"symlink_target": ""
} |
<?php
namespace Chamilo\Core\Repository\Integration\Chamilo\Core\Menu\Renderer\Item\Bar\Item;
use Chamilo\Core\Menu\Renderer\Item\Bar\Item\CategoryItem;
use Chamilo\Core\Menu\Renderer\Item\Renderer;
use Chamilo\Core\Menu\Storage\DataClass\Item;
use Chamilo\Core\Repository\Instance\Storage\DataClass\Instance;
use Chamilo\Core\User\Storage\DataClass\User;
use Chamilo\Libraries\Format\Theme;
use Chamilo\Libraries\Translation\Translation;
use Chamilo\Libraries\Storage\Parameters\DataClassRetrievesParameters;
/**
*
* @package Chamilo\Core\User\Integration\Chamilo\Core\Menu\Renderer\Item\Bar\Item
* @author Hans De Bisschop <hans.de.bisschop@ehb.be>
* @author Magali Gillard <magali.gillard@ehb.be>
* @author Eduard Vossen <eduard.vossen@ehb.be>
*/
class RepositoryImplementationCategoryItem extends CategoryItem
{
public function isItemSelected()
{
// TODO;
return false;
}
public function render()
{
if (! $this->canViewMenuItem($this->getMenuRenderer()->get_user()))
{
return '';
}
$html = array();
$sub_html = array();
$instances = \Chamilo\Core\Repository\Instance\Storage\DataManager::retrieves(
Instance::class_name(),
new DataClassRetrievesParameters());
if ($instances->size())
{
$sub_html[] = '<ul class="dropdown-menu">';
while ($instance = $instances->next_result())
{
if (! $instance->is_enabled())
{
continue;
}
$sysImagePath = Theme::getInstance()->getImagePath(
$instance->get_implementation(),
'Menu',
'png',
false);
$display = file_exists($sysImagePath) ? Item::DISPLAY_ICON : Item::DISPLAY_TEXT;
$display = Item::DISPLAY_TEXT;
$instanceItem = new \Chamilo\Core\Repository\Integration\Chamilo\Core\Menu\Storage\DataClass\RepositoryImplementationItem();
$instanceItem->set_implementation($instance->get_implementation());
$instanceItem->set_instance_id($instance->get_id());
$instanceItem->set_name($instance->get_title());
$instanceItem->set_parent($this->getItem()->get_id());
$instanceItem->set_display($display);
$sub_html[] = Renderer::toHtml($this->getMenuRenderer(), $instanceItem, $this);
}
$sub_html[] = '</ul>';
}
$selected = $this->isItemSelected();
$html[] = '<li class="dropdown' . ($selected ? ' active' : '') . '">';
$html[] = '<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">';
$title = Translation::get('Instance', null, 'Chamilo\Core\Repository\Integration\Chamilo\Core\Menu');
if ($this->getItem()->show_icon())
{
$integrationNamespace = 'Chamilo\Core\Repository\Integration\Chamilo\Core\Menu';
$imagePath = Theme::getInstance()->getImagePath(
$integrationNamespace,
'RepositoryImplementationCategory' . ($selected ? 'Selected' : ''));
$html[] = '<img class="chamilo-menu-item-icon' .
($this->getItem()->show_title() ? ' chamilo-menu-item-image-with-label' : '') . '" src="' . $imagePath .
'" title="' . $title . '" alt="' . $title . '" />';
}
if ($this->getItem()->show_title())
{
$html[] = '<div class="chamilo-menu-item-label' .
($this->getItem()->show_icon() ? ' chamilo-menu-item-label-with-image' : '') . '">' . $title . '</div>';
}
$html[] = '<div class="clearfix"></div>';
$html[] = '</a>';
$html[] = implode(PHP_EOL, $sub_html);
$html[] = '</li>';
return implode(PHP_EOL, $html);
}
/**
* Returns whether or not the given user can view this menu item
*
* @param User $user
*
* @return bool
*/
public function canViewMenuItem(User $user)
{
$authorizationChecker = $this->getAuthorizationChecker();
return $authorizationChecker->isAuthorized($this->getMenuRenderer()->get_user(), 'Chamilo\Core\Repository');
}
}
| {
"content_hash": "03b956af333ce4256f82e170f96697d8",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 140,
"avg_line_length": 37.975,
"alnum_prop": 0.5494843098529735,
"repo_name": "forelo/cosnics",
"id": "b501ece0d273a3ac36976471105bcca332d9c6cc",
"size": "4557",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Chamilo/Core/Repository/Integration/Chamilo/Core/Menu/Renderer/Item/Bar/Item/RepositoryImplementationCategoryItem.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "262730"
},
{
"name": "C",
"bytes": "12354"
},
{
"name": "CSS",
"bytes": "1334431"
},
{
"name": "CoffeeScript",
"bytes": "41023"
},
{
"name": "Gherkin",
"bytes": "24033"
},
{
"name": "HTML",
"bytes": "1016812"
},
{
"name": "Hack",
"bytes": "424"
},
{
"name": "JavaScript",
"bytes": "10768095"
},
{
"name": "Less",
"bytes": "331253"
},
{
"name": "Makefile",
"bytes": "3221"
},
{
"name": "PHP",
"bytes": "23623996"
},
{
"name": "Python",
"bytes": "2408"
},
{
"name": "Ruby",
"bytes": "618"
},
{
"name": "SCSS",
"bytes": "163532"
},
{
"name": "Shell",
"bytes": "7965"
},
{
"name": "Smarty",
"bytes": "15750"
},
{
"name": "Twig",
"bytes": "388197"
},
{
"name": "TypeScript",
"bytes": "123212"
},
{
"name": "Vue",
"bytes": "454138"
},
{
"name": "XSLT",
"bytes": "43009"
}
],
"symlink_target": ""
} |
S3_BUCKET_NAME="[STAGING S3 BUCKET NAME HERE (ie. my-staging-bucket)]"
PKG="aws-ebs-snapshot-cleanup.zip"
echo "Building deployment package..."
npm run assemble
echo "Deploying to S3 bucket $S3_BUCKET_NAME..."
aws s3 cp dist/$PKG s3://$S3_BUCKET_NAME/$PKG
| {
"content_hash": "0b52abdb176d30c53cea7affbf4cb4c6",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 70,
"avg_line_length": 32.25,
"alnum_prop": 0.7286821705426356,
"repo_name": "CraigPhillips/aws-ebs-snapshot-cleanup",
"id": "118ce736d5f20643a8f31cc5248f1be44516e3a0",
"size": "258",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "deploy/dev/stage.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "19386"
},
{
"name": "Shell",
"bytes": "1944"
}
],
"symlink_target": ""
} |
package net.outman.hipda.bean;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
public class ThreadListBean {
public int count;
public List<ThreadBean> threads = new ArrayList<ThreadBean>();
private boolean mAddStickThreads = false;
public ThreadListBean(Context ctx) {
count = 0;
mAddStickThreads = HiSettingsHelper.getInstance().isShowStickThreads();
}
public void add(ThreadBean thread) {
if (!mAddStickThreads && thread.getIsStick()) {
return;
} else {
threads.add(thread);
count++;
}
}
}
| {
"content_hash": "30b2b0fc3664c9449ee22aa5fbbe65ca",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 79,
"avg_line_length": 22.785714285714285,
"alnum_prop": 0.6379310344827587,
"repo_name": "outman-zhou/android-hipda-client",
"id": "649aed96a53ff4ab2db0dc70b614a1a45c84bc32",
"size": "638",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hipda/src/main/java/net/outman/hipda/bean/ThreadListBean.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1387"
},
{
"name": "Java",
"bytes": "377810"
}
],
"symlink_target": ""
} |
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2005, 2006
// University of Rochester
// Department of Computer Science
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the University of Rochester nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifndef __BENCH_PRIV_LIST_H__
#define __BENCH_PRIV_LIST_H__
#include "stm_api.h"
#include <iostream>
namespace bench
{
// LLNode is a single node in a sorted linked list
class PrivNode : public stm::Object<PrivNode>
{
GENERATE_FIELD(int, val);
GENERATE_FIELD(stm::sh_ptr<PrivNode>, next);
public:
PrivNode(int val = -1) : m_val(val), m_next() { }
PrivNode(int val, const stm::sh_ptr<PrivNode>& next)
: m_val(val), m_next(next) { }
// clone method for use in RSTM
virtual PrivNode* clone() const
{
int val = m_val;
stm::sh_ptr<PrivNode> next = m_next;
return new PrivNode(val, next);
}
#ifdef NEED_REDO_METHOD
virtual void redo(SharedBase* l_sh)
{
PrivNode* l = static_cast<PrivNode*>(l_sh);
m_val = l->m_val;
m_next = l->m_next;
}
#endif
};
// Set of PrivNodes represented as a linked list in sorted order
class PrivList : public Benchmark
{
stm::sh_ptr<PrivNode> sentinel;
int m_max;
public:
// constructor just makes a sentinel for the data structure
PrivList(int _max) : sentinel(new PrivNode()), m_max(_max) { }
virtual void random_transaction(thread_args_t* args,
unsigned int* seed,
unsigned int val,
unsigned int chance)
{
if (insertNextOrClearAll())
++args->count[TXN_INSERT];
else
++args->count[TXN_REMOVE];
}
// make sure the list is in sorted order
virtual bool sanity_check() const;
// no data structure verification is implemented for the PrivList yet
virtual bool verify(VerifyLevel_t v) { return true; }
/**
* There is only one operation on the PrivList: insertNextOrClearAll.
* This operation attempts to add the next integer between 0 and m_max
* to the sorted list. If it finds that m_max has already been
* inserted, the operation privatizes the whole list and deletes all
* elements.
*/
bool insertNextOrClearAll();
};
} // namespace bench
// simple sanity check: make sure all elements of the list are in sorted order
bool bench::PrivList::sanity_check(void) const
{
bool sane = false;
BEGIN_TRANSACTION;
sane = true;
stm::rd_ptr<PrivNode> prev(sentinel);
stm::rd_ptr<PrivNode> curr(prev->get_next(prev.v()));
while (curr != NULL) {
if (prev->get_val(prev.v()) >= curr->get_val(curr.v())) {
sane = false;
break;
}
prev = curr;
curr = curr->get_next(curr.v());
}
END_TRANSACTION;
return sane;
}
/**
* If the max element is < m_max, insert the next integer into the end of the
* list. Otherwise, clear the whole list via privatization.
*/
bool bench::PrivList::insertNextOrClearAll()
{
// if we privatize the list, it will go into here
stm::sh_ptr<PrivNode> priv(NULL);
BEGIN_TRANSACTION;
// reset locals
priv = stm::sh_ptr<PrivNode>(NULL);
// step one: traverse the list to find the max, and store the last node as
// prev
int max = -1;
stm::rd_ptr<PrivNode> prev(sentinel);
stm::rd_ptr<PrivNode> curr(prev->get_next(prev.v()));
while (curr != NULL) {
max = curr->get_val(curr.v());
prev = curr;
curr = prev->get_next(prev.v());
}
// step two: either insert a new element or excise the whole list
if (max < m_max) {
// insert a new node
stm::wr_ptr<PrivNode> insert_pt(prev);
insert_pt->set_next(stm::sh_ptr<PrivNode>(new PrivNode(max + 1, curr)));
}
else {
// excise
// first go back to the start of the tree
prev = sentinel;
// now 'leak' the first non-sentinel node into priv
priv = prev->get_next(prev.v());
// now write a NULL in sentinel->next
stm::wr_ptr<PrivNode> excise_pt(prev);
excise_pt->set_next(stm::sh_ptr<PrivNode>(NULL));
}
END_TRANSACTION;
// if we've got a priv, then we need to use it:
if (priv != NULL) {
// explicit fence is needed, but it might just be an FAI()...
stm::fence();
// now start using un_ptrs:
stm::un_ptr<PrivNode> prev(priv);
stm::un_ptr<PrivNode> curr(prev->get_next(prev.v()));
while (curr != NULL) {
stm::tx_delete(prev);
prev = curr;
curr = curr->get_next(curr.v());
}
stm::tx_delete(prev);
// return false: we were a privatizing tx
return false;
}
// return true: we were an inserting tx
return true;
}
#endif // __BENCH_PRIV_LIST_H__
| {
"content_hash": "6749d1e6334d6acd4891c593a9d3bfc8",
"timestamp": "",
"source": "github",
"line_count": 210,
"max_line_length": 80,
"avg_line_length": 31.652380952380952,
"alnum_prop": 0.5992176921919663,
"repo_name": "rafgitdz/bimodal-scheduler-rstm",
"id": "fa446e6d89c416c3902289f901624bdcaf7f29e4",
"size": "6647",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bench/PrivList.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "14132"
},
{
"name": "C++",
"bytes": "662914"
},
{
"name": "Makefile",
"bytes": "17080"
},
{
"name": "Perl",
"bytes": "2275"
},
{
"name": "Shell",
"bytes": "1695"
}
],
"symlink_target": ""
} |
package com.cloudant.client.api.views;
import com.cloudant.client.api.model.Document;
import java.util.List;
import java.util.Map;
/**
* Encapsulates a response from an _all_docs request.
* <P>
* Provides methods to facilitate processing of the response.
* </P>
*
* @since 2.0.0
*/
public interface AllDocsResponse {
/**
* <P>
* Get the document information from an _all_docs request.
* </P>
* <P>
* Note that if requesting docs using {@link AllDocsRequestBuilder#keys(Object[])} the list of
* documents may include <b>deleted</b> documents that have one of the specified ids.
* </P>
* <P>
* Note if {@link AllDocsRequestBuilder#includeDocs(boolean)} is false then attachment metadata
* will not be present.
* </P>
* @return a list of Document objects from the _all_docs request
* @since 2.0.0
*/
List<Document> getDocs();
/**
* <P>
* Gets a map of the document id and revision for each result in the _all_docs request.
* </P>
* <P>
* Note that if requesting docs using {@link AllDocsRequestBuilder#keys(Object[])} the ids and
* revs may include <b>deleted</b> documents that have one of the specified ids.
* </P>
*
* @return a map with an entry for each document, key of _id and value of _rev
* @since 2.0.0
*/
Map<String, String> getIdsAndRevs();
/**
* <P>
* Deserializes the included full content of result documents to a list of the specified type.
* </P>
* <P>
* Note that if requesting docs using {@link AllDocsRequestBuilder#keys(Object[])} the list of
* documents may include <b>deleted</b> documents that have one of the specified ids. You may
* want to ensure that your document type can support checking of the deleted flag.
* </P>
*
* @param docType the class type to deserialize the JSON document to
* @param <D> the type of the document
* @return the deserialized document
* @throws IllegalStateException if include_docs was {@code false}
* @since 2.0.0
*/
<D> List<D> getDocsAs(Class<D> docType);
/**
* @return a list of the document ids
*/
List<String> getDocIds();
/**
* Gets a map of the document id and error message if an error exists for any result
* in the _all_docs request.
* For example, if a doc id does not exist the error message will show "not_found".
*
* @return a map with an entry for key of the doc id and value of error
* @since 2.10.0
*/
Map<String, String> getErrors();
/**
* @return the total number of rows in the _all_docs view, before any filtering has taken place
* @since 2.19.0
*/
Long getTotalRowCount();
}
| {
"content_hash": "feb124fce24e190d5201b7632f6a7f85",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 99,
"avg_line_length": 31.247191011235955,
"alnum_prop": 0.6314275440489032,
"repo_name": "cloudant/java-cloudant",
"id": "50b3f12927b59119201990fac3036f41433f1261",
"size": "3393",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cloudant-client/src/main/java/com/cloudant/client/api/views/AllDocsResponse.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "32359"
},
{
"name": "Java",
"bytes": "1355328"
},
{
"name": "JavaScript",
"bytes": "7442"
}
],
"symlink_target": ""
} |
{% extends 'core/wide.html' %}
{% load staticfiles %}
{% load i18n %}
{% load compress %}
{% load vendor_tags %}
{% block bodyargs %}ng-app="users" ng-controller="UsersController"{% endblock %}
{% block headextra %}
{% vendor 'angular' %}
{% vendor 'ng-infinite-scroll' %}
{% compress css %}
<link rel="stylesheet" type="text/x-scss" href="{% static 'core/css/list.scss' %}" />
<link rel="stylesheet" type="text/x-scss" href="{% static 'auth/css/users.scss' %}" />
{% endcompress css %}
{% compress js %}
<script type="text/javascript" src="{% static 'core/js/core.js' %}" ></script>
<script type="text/javascript" src="{% static 'core/js/list.js' %}" ></script>
<script type="text/javascript" src="{% static 'core/js/filter.js' %}" ></script>
<script type="text/javascript" src="{% static 'core/js/multiCheckbox.js' %}" ></script>
<script type="text/javascript" src="{% static 'core/js/byNumber.js' %}" ></script>
<script type="text/javascript" src="{% static 'core/js/formgroup.js' %}" ></script>
<script type="text/javascript" src="{% static 'auth/js/users.js' %}" ></script>
{% endcompress js %}
{% endblock %}
{% block wide %}
<div ng-cloak ng-show="service.list.ready">
<h1>User management</h1>
<div class="daiquiri-list">
<div class="row daiquiri-list-header">
<form class="col-sm-6" ng-submit="service.list.search()">
<div class="input-group">
<input class="form-control"
id="table-pager-search-input"
placeholder="{% trans 'Search entries' %}"
type="text" ng-model="service.list.search_string">
<a href="" class="input-group-addon" ng-click="service.list.search()">
<span class="fa fa-search"></span>
</a>
</div>
</form>
<div class="col-sm-6">
<p class="count">
{$ service.list.count $} {% trans 'users found' %}
</p>
<ul class="pagination pull-right">
<li>
<a href="" ng-click="service.list.reset()">{% trans 'Reset' %}</a>
</li>
</ul>
</div>
</div>
<div class="table-responsive">
<table class="table daiquiri-list-table" infinite-scroll="service.list.fetch()" infinite-scroll-distance="0.2">
<thead>
<th style="width: 25%;">{% trans 'Name (Username)' %}</th>
<th style="width: 25%;">{% trans 'Email' %}</th>
<th style="width: 20%;">{% trans 'Status' %}</th>
<th style="width: 10%;">{% trans 'Groups' %}</th>
<th style="width: 20%;"></th>
</thead>
<tbody>
<tr ng-repeat="row in service.list.rows">
<td>
<a href="" ng-click="service.modal('show-user-modal', $index)">
{$ row.full_name $}
</a>
<em>({$ row.user.username $})</em>
</td>
<td>
<div ng-repeat="email in row.emails">
<a href="mailto:{$ row.user.first_name $} {$ row.user.last_name $} <{$ email.email $}>">
{$ email.email $}
</a>
<span ng-show="!email.verified">({% trans 'not verified' %})</span>
</div>
</td>
<td ng-class="{
'text-success': row.user.is_active && !row.is_pending && !row.is_confirmed,
'text-danger': !row.user.is_active,
'text-info': row.is_pending || row.is_confirmed
}">
<span ng-show="row.user.is_superuser">
{% trans 'superuser' %}
</span>
<span ng-show="row.user.is_staff && !row.user.is_superuser">
{% trans 'staff' %}
</span>
<span ng-show="row.user.is_active && !row.is_pending && !row.is_confirmed">
{% trans 'active' %}
</span>
<span ng-hide="row.user.is_active">
{% trans 'disabled' %}
</span>
<span ng-show="row.is_pending">
{% trans 'pending' %}
</span>
<span ng-show="row.is_confirmed">
{% trans 'confirmed' %}
</span>
</td>
<td>
<span ng-repeat="group in service.groups|filterAgainstList:{'id': row.user.groups}">
{$ group.name $}{$ $last ? '' : ', ' $}
</span>
</td>
<td class="text-right options">
{% include 'auth/users_options.html' %}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
{% include 'auth/users_modal_show_user.html' %}
{% include 'auth/users_modal_update_user.html' %}
{% include 'auth/users_modal_disable_user.html' %}
{% include 'auth/users_modal_enable_user.html' %}
{% include 'auth/users_modal_confirm_user.html' %}
{% include 'auth/users_modal_reject_user.html' %}
{% include 'auth/users_modal_activate_user.html' %}
{% endblock %}
| {
"content_hash": "9e73cfe5d5d8a4c2d6d57772741a18fa",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 127,
"avg_line_length": 48.29545454545455,
"alnum_prop": 0.3978039215686274,
"repo_name": "aipescience/django-daiquiri",
"id": "70f8398a6328a0426de8cb3c3017a00d92fec7b3",
"size": "6375",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "daiquiri/auth/templates/auth/users.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "28598"
},
{
"name": "HTML",
"bytes": "236579"
},
{
"name": "JavaScript",
"bytes": "97087"
},
{
"name": "Python",
"bytes": "602159"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Append to Evernote Note</string>
<string name="open_drawer">Open drawer</string>
<string name="close_drawer">Close drawer</string>
<string name="notes">Notes</string>
<string name="notebooks">Notebooks</string>
<string name="label_logout">Sign out</string>
<string name="user_info">User Info</string>
<string name="label_login">Login</string>
<string name="empty">Empty %s</string>
<string name="evernote_not_installed">Evernote is not installed.</string>
<string name="share_public_link">Share public link</string>
<string name="delete">Delete</string>
<string name="raw_content">Raw content</string>
<string name="open_in_evernote_client">Open with Evernote app</string>
<string name="note_title">Note Title</string>
<string name="notebook_title">Notebook Title</string>
<string name="note_content">Note Content</string>
<string name="create_new_note">Create new note</string>
<string name="create_new_notebook">Create new notebook</string>
<string name="create">Create</string>
<string name="personal">Personal</string>
<string name="linked">Linked</string>
<string name="attach_image">Attach image</string>
<string name="mega_bytes">%.1f MB</string>
<string name="kilo_bytes">%.1f KB</string>
<string name="upload_limit">Upload limit</string>
<string name="email">Email</string>
<string name="search">Search</string>
<string name="query">Query</string>
</resources>
| {
"content_hash": "beff14f33f6f6fd1176da1b0e72d3c86",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 77,
"avg_line_length": 48.78125,
"alnum_prop": 0.6880204996796925,
"repo_name": "fivef/add_to_evernote_note",
"id": "fc237a767e0e28136960e5f1a09ac0e6022e733d",
"size": "1561",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "add_to_evernote_note/src/main/res/values/strings.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "363988"
}
],
"symlink_target": ""
} |
require "redis"
module RedisHelpers
def redis
@redis ||= ::Redis.new
end
def remove_keys(template)
keys = redis.keys(template)
redis.del(*keys) if keys.any?
end
end
| {
"content_hash": "b8059109fa804fe8e612512886964298",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 33,
"avg_line_length": 15.583333333333334,
"alnum_prop": 0.6577540106951871,
"repo_name": "nicoolas25/tennis-redis",
"id": "0add78b32585673f7392006159d986f2b6b9e2af",
"size": "187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/support/redis_helpers.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "7803"
}
],
"symlink_target": ""
} |
package malow.gladiatus.common;
import malow.gladiatus.common.models.responses.CharacterInfoResponse;
public class Armor
{
public final static float BASE_ARMOR = 10.0f;
public final static float DEXTERITY_MODIFIER = 0.2f;
public static float GetArmor(float dexterity)
{
return BASE_ARMOR + dexterity * DEXTERITY_MODIFIER;
}
public static float GetArmor(CharacterInfoResponse character)
{
return GetArmor(Float.valueOf(character.dexterity));
}
}
| {
"content_hash": "842af47ec0a55d677115d2d4bffa7c97",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 69,
"avg_line_length": 24.9,
"alnum_prop": 0.7248995983935743,
"repo_name": "Malow/Gladiatus",
"id": "7621a93f13b026dfb690f6b7e3cd1be06ab80bef",
"size": "498",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gladiatus/src/main/java/malow/gladiatus/common/Armor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "3300"
},
{
"name": "Java",
"bytes": "5412861"
},
{
"name": "XSLT",
"bytes": "5266"
}
],
"symlink_target": ""
} |
自定义actionsheet,用来设置自己想要样式的actionSheet原型
| {
"content_hash": "7d4975087ec922a4956a6ea50e73fbc1",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 39,
"avg_line_length": 40,
"alnum_prop": 0.95,
"repo_name": "cxGoGoing/customActionSheet",
"id": "bdf9cb5c35eae6c3d71b3ac1ca5cc9652b75ded2",
"size": "92",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "141562"
}
],
"symlink_target": ""
} |
'use strict';
var Customer = require('../models/customer');
exports.getCustomers = function(args, res, next) {
/**
* Find customers
* Returns all customers
*
* returns inline_response_200_2
**/
Customer.find({}, function(err, customers) {
if(err){
res.status(500).json(err).end();
return;
}
res.json({
customers: customers
}).end();
});
}
| {
"content_hash": "3034a727c37e9261e3abbf5305f11b1b",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 50,
"avg_line_length": 18.681818181818183,
"alnum_prop": 0.5571776155717761,
"repo_name": "s-piovesan/FacturationManager",
"id": "cc2866636c3c182816e4e97b8192ad1398345a8f",
"size": "411",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "FactureManagerAPI/controllers/CustomersService.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1245"
},
{
"name": "HTML",
"bytes": "11018"
},
{
"name": "JavaScript",
"bytes": "33809"
},
{
"name": "TypeScript",
"bytes": "34302"
}
],
"symlink_target": ""
} |
package org.onosproject.p4runtime.ctl.codec;
/**
* Utility class that provides access to P4Runtime codec instances.
*/
public final class Codecs {
public static final Codecs CODECS = new Codecs();
private final ActionCodec action;
private final ActionProfileGroupCodec actionProfileGroup;
private final ActionProfileMemberCodec actionProfileMember;
private final CounterEntryCodec counterEntry;
private final DirectCounterEntryCodec directCounterEntry;
private final DirectMeterEntryCodec directMeterEntry;
private final EntityCodec entity;
private final FieldMatchCodec fieldMatch;
private final HandleCodec handle;
private final MeterEntryCodec meterEntry;
private final MulticastGroupEntryCodec multicastGroupEntry;
private final CloneSessionEntryCodec cloneSessionEntry;
private final PreReplicaCodec preReplica;
private final PacketInCodec packetIn;
private final PacketMetadataCodec packetMetadata;
private final PacketOutCodec packetOut;
private final TableEntryCodec tableEntry;
private final ActionSetCodec actionSet;
private Codecs() {
this.action = new ActionCodec();
this.actionProfileGroup = new ActionProfileGroupCodec();
this.actionProfileMember = new ActionProfileMemberCodec();
this.counterEntry = new CounterEntryCodec();
this.directCounterEntry = new DirectCounterEntryCodec();
this.directMeterEntry = new DirectMeterEntryCodec();
this.entity = new EntityCodec();
this.fieldMatch = new FieldMatchCodec();
this.handle = new HandleCodec();
this.meterEntry = new MeterEntryCodec();
this.multicastGroupEntry = new MulticastGroupEntryCodec();
this.cloneSessionEntry = new CloneSessionEntryCodec();
this.preReplica = new PreReplicaCodec();
this.packetIn = new PacketInCodec();
this.packetMetadata = new PacketMetadataCodec();
this.packetOut = new PacketOutCodec();
this.tableEntry = new TableEntryCodec();
this.actionSet = new ActionSetCodec();
}
public EntityCodec entity() {
return entity;
}
public HandleCodec handle() {
return handle;
}
public PacketOutCodec packetOut() {
return packetOut;
}
public PacketInCodec packetIn() {
return packetIn;
}
TableEntryCodec tableEntry() {
return tableEntry;
}
FieldMatchCodec fieldMatch() {
return fieldMatch;
}
ActionCodec action() {
return action;
}
ActionProfileMemberCodec actionProfileMember() {
return actionProfileMember;
}
ActionProfileGroupCodec actionProfileGroup() {
return actionProfileGroup;
}
PacketMetadataCodec packetMetadata() {
return packetMetadata;
}
MulticastGroupEntryCodec multicastGroupEntry() {
return multicastGroupEntry;
}
CloneSessionEntryCodec cloneSessionEntry() {
return cloneSessionEntry;
}
PreReplicaCodec preReplica() {
return preReplica;
}
DirectMeterEntryCodec directMeterEntry() {
return directMeterEntry;
}
MeterEntryCodec meterEntry() {
return meterEntry;
}
CounterEntryCodec counterEntry() {
return counterEntry;
}
DirectCounterEntryCodec directCounterEntry() {
return directCounterEntry;
}
ActionSetCodec actionSet() {
return actionSet;
}
}
| {
"content_hash": "1aed0aac03cbb9fd5c0c99fa9b2aa151",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 67,
"avg_line_length": 28.284552845528456,
"alnum_prop": 0.6981891348088531,
"repo_name": "opennetworkinglab/onos",
"id": "06a2d182192075e01fd3f5333e6ed22776320784",
"size": "4096",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "protocols/p4runtime/utils/src/main/java/org/onosproject/p4runtime/ctl/codec/Codecs.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "367433"
},
{
"name": "Dockerfile",
"bytes": "3187"
},
{
"name": "HTML",
"bytes": "332756"
},
{
"name": "Java",
"bytes": "38791946"
},
{
"name": "JavaScript",
"bytes": "3999775"
},
{
"name": "Jinja",
"bytes": "2272195"
},
{
"name": "Makefile",
"bytes": "1852"
},
{
"name": "P4",
"bytes": "197536"
},
{
"name": "Python",
"bytes": "489477"
},
{
"name": "SCSS",
"bytes": "3578"
},
{
"name": "Shell",
"bytes": "342726"
},
{
"name": "Starlark",
"bytes": "495306"
},
{
"name": "TypeScript",
"bytes": "959357"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "9dcdc2c4a362c06557599256401091f5",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "2cdc64241f2f651d05169f0f92f755f2dae23ab5",
"size": "185",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Alismatales/Araceae/Monstera/Monstera siltepecana/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using namespace android;
enum
{
NOTIFY_CALLBACK,
};
class BpOOBWakeonVoiceClient: public BpInterface<IOOBWakeonVoiceClient>
{
public:
BpOOBWakeonVoiceClient( const sp<IBinder> &impl )
:BpInterface<IOOBWakeonVoiceClient>( impl )
{
}
void notifyCallback( int32_t msgType, int32_t ext1, int32_t ext2 )
{
LOGV( "notifyCallback" );
Parcel data, reply;
data.writeInterfaceToken( IOOBWakeonVoiceClient::getInterfaceDescriptor() );
data.writeInt32( msgType );
data.writeInt32( ext1 );
data.writeInt32( ext2 );
remote()->transact( NOTIFY_CALLBACK, data, &reply, IBinder::FLAG_ONEWAY );
}
};
IMPLEMENT_META_INTERFACE( OOBWakeonVoiceClient, "IOOBWakeonVoiceClient" );
// -------------------------------------------------------------------------
status_t BnOOBWakeonVoiceClient::onTransact( uint32_t code, const Parcel &data,
Parcel *reply, uint32_t flags )
{
LOGI( "onTransact code: %d", code );
switch ( code )
{
case NOTIFY_CALLBACK:
{
CHECK_INTERFACE( IOOBWakeonVoiceClient, data, reply );
int32_t msgType = data.readInt32();
int32_t ext1 = data.readInt32();
int32_t ext2 = data.readInt32();
this->notifyCallback( msgType, ext1, ext2 );
return NO_ERROR;
}
break;
default:
break;
}
return NO_ERROR;
}
| {
"content_hash": "ed8f9495c8f2f10ce158f40d8a5e1dd3",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 79,
"avg_line_length": 22.482758620689655,
"alnum_prop": 0.6449386503067485,
"repo_name": "yao-matrix/mProto",
"id": "b5f4a7d5096837bb1d9f42e18e1226f965c7d230",
"size": "1390",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "auditory/example/src/android/oobwov/OOBWakeOnVoiceService/IOOBWakeonVoiceClient.cpp",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "5382886"
},
{
"name": "C++",
"bytes": "830849"
},
{
"name": "Java",
"bytes": "122070"
},
{
"name": "Jupyter Notebook",
"bytes": "3046095"
},
{
"name": "Makefile",
"bytes": "31655"
},
{
"name": "Python",
"bytes": "90682"
},
{
"name": "Roff",
"bytes": "11982"
},
{
"name": "Shell",
"bytes": "17619"
}
],
"symlink_target": ""
} |
import { createSelector } from "reselect"
const settingsSelector = (state) => state.present.settings
export const gridStepSelector = createSelector(
settingsSelector,
(settings) => settings.gridSnap ? settings.gridSize : 1
)
| {
"content_hash": "9db0ea69c5fb70e164c0488d3ac4180c",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 58,
"avg_line_length": 28.875,
"alnum_prop": 0.7619047619047619,
"repo_name": "anthonydugois/polynom",
"id": "59ea04270e5ee482ac6c674aec82ea8f25d6ad1d",
"size": "231",
"binary": false,
"copies": "2",
"ref": "refs/heads/gh-pages",
"path": "src/selectors/gridStep.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "19465"
},
{
"name": "HTML",
"bytes": "1122"
},
{
"name": "JavaScript",
"bytes": "128641"
}
],
"symlink_target": ""
} |
<?php
namespace AssetsBundleTest\Controller;
class JsCustomControllerTest extends \Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase
{
/**
* @var array
*/
private $configuration = array(
'assets_bundle' => array(
'production' => true,
'assets' => array(
'css' => array(
'css/test.css',
'css/css.php'
),
'less' => array('less/test.less'),
'js' => array('js/test.js'),
'index' => array(
'test-media' => array(
'css' => array('css/test-media.css'),
'less' => array('less/test-media.less'),
'media' => array(
'@zfRootPath/AssetsBundleTest/_files/fonts',
'@zfRootPath/AssetsBundleTest/_files/images'
)
),
'test-mixins' => array(
'less' => array(
'less/test-mixins.less',
'less/test-mixins-use.less'
),
),
),
),
),
);
/**
* @see PHPUnit_Framework_TestCase::setUp()
*/
public function setUp()
{
$this->setApplicationConfig(\AssetsBundleTest\Bootstrap::getConfig());
parent::setUp();
$oServiceLocator = $this->getApplicationServiceLocator();
$aConfiguration = $oServiceLocator->get('Config');
unset($aConfiguration['assets_bundle']['assets']);
$this->configuration = \Zend\Stdlib\ArrayUtils::merge($aConfiguration, $this->configuration);
$bAllowOverride = $oServiceLocator->getAllowOverride();
if (!$bAllowOverride) {
$oServiceLocator->setAllowOverride(true);
}
$oServiceLocator->setService('Config', $this->configuration)->setAllowOverride($bAllowOverride);
// Empty cache and processed directories
$oServiceLocator->get('AssetsBundleToolsService')->emptyCache(false);
}
public function testTestActionInProduction()
{
$this->dispatch('/test');
$this->assertResponseStatusCode(200,$this->getResponse()->getContent());
$this->assertModuleName('AssetsBundleTest');
$this->assertControllerName('AssetsBundleTest\Controller\Test');
$this->assertControllerClass('TestController');
$this->assertMatchedRouteName('test');
$this->assertEquals('/jscustom/AssetsBundleTest%5CController%5CTest/test', $this->getResponse()->getContent());
}
public function testTestActionInDevelopment()
{
$oServiceLocator = $this->getApplicationServiceLocator();
$aConfiguration = $oServiceLocator->get('Config');
unset($aConfiguration['assets_bundle']['assets']);
$this->configuration = \Zend\Stdlib\ArrayUtils::merge($aConfiguration, $this->configuration);
$this->configuration['assets_bundle']['production'] = false;
$bAllowOverride = $oServiceLocator->getAllowOverride();
if (!$bAllowOverride) {
$oServiceLocator->setAllowOverride(true);
}
$oServiceLocator->setService('Config', $this->configuration)->setAllowOverride($bAllowOverride);
//Retrieve assets bundle service
$oAssetsBundleService = $this->getApplicationServiceLocator()->get('AssetsBundleService');
$oAssetsBundleService->getOptions()->setProduction(false);
$this->assertFalse($oAssetsBundleService->getOptions()->isProduction());
$this->dispatch('/test');
$this->assertResponseStatusCode(200, $this->getResponse()->getContent());
$this->assertModuleName('AssetsBundleTest');
$this->assertControllerName('AssetsBundleTest\Controller\Test');
$this->assertControllerClass('TestController');
$this->assertMatchedRouteName('test');
$this->assertEquals(print_r(array(
'/cache/_files/assets/js/jscustom.js',
'/cache/_files/assets/js/jscustom.php'
), true), preg_replace('/\?[0-9]*/', '', $this->getResponse()->getContent()));
$this->assertFileExists($oAssetsBundleService->getOptions()->getCachePath() . DIRECTORY_SEPARATOR . '_files/assets/js/jscustom.js');
$this->assertFileExists($oAssetsBundleService->getOptions()->getCachePath() . DIRECTORY_SEPARATOR . '_files/assets/js/jscustom.php');
}
public function testFileErrorActionInDevelopment()
{
$oServiceLocator = $this->getApplicationServiceLocator();
$aConfiguration = $oServiceLocator->get('Config');
unset($aConfiguration['assets_bundle']['assets']);
$this->configuration = \Zend\Stdlib\ArrayUtils::merge($aConfiguration, $this->configuration);
$this->configuration['assets_bundle']['production'] = false;
$bAllowOverride = $oServiceLocator->getAllowOverride();
if (!$bAllowOverride) {
$oServiceLocator->setAllowOverride(true);
}
$oServiceLocator->setService('Config', $this->configuration)->setAllowOverride($bAllowOverride);
$this->dispatch('/file-error');
$this->assertResponseStatusCode(200);
$this->assertModuleName('AssetsBundleTest');
$this->assertControllerName('AssetsBundleTest\Controller\Test');
$this->assertControllerClass('TestController');
$this->assertMatchedRouteName('fileError');
}
public function testEmptyActionInDevelopment()
{
$oServiceLocator = $this->getApplicationServiceLocator();
$aConfiguration = $oServiceLocator->get('Config');
unset($aConfiguration['assets_bundle']['assets']);
$this->configuration = \Zend\Stdlib\ArrayUtils::merge($aConfiguration, $this->configuration);
$this->configuration['assets_bundle']['production'] = false;
$bAllowOverride = $oServiceLocator->getAllowOverride();
if (!$bAllowOverride) {
$oServiceLocator->setAllowOverride(true);
}
$oServiceLocator->setService('Config', $this->configuration)->setAllowOverride($bAllowOverride);
$this->dispatch('/empty');
$this->assertResponseStatusCode(200);
$this->assertModuleName('AssetsBundleTest');
$this->assertControllerName('AssetsBundleTest\Controller\Test');
$this->assertControllerClass('TestController');
$this->assertMatchedRouteName('empty');
}
public function testJsCustomAction()
{
$this->dispatch('/jscustom/AssetsBundleTest%5CController%5CTest/test');
$this->assertResponseStatusCode(200);
$this->assertModuleName('AssetsBundleTest');
$this->assertControllerName('AssetsBundleTest\Controller\Test');
$this->assertControllerClass('TestController');
$this->assertMatchedRouteName('jscustom/definition');
$this->assertResponseHeaderContains('content-type', 'text/javascript');
$sCacheExpectedPath = dirname(__DIR__) . '/../_files/expected/cache/prod';
$this->assertStringEqualsFile($sCacheExpectedPath . '/jscustom.js', $this->getResponse()->getContent());
}
public function tearDown()
{
// Empty cache and processed directories
\AssetsBundleTest\Bootstrap::getServiceManager()->get('AssetsBundleToolsService')->emptyCache(false);
parent::tearDown();
}
}
| {
"content_hash": "500bb5454979dff93e44e254a78cc2ce",
"timestamp": "",
"source": "github",
"line_count": 182,
"max_line_length": 141,
"avg_line_length": 41.142857142857146,
"alnum_prop": 0.6164529914529915,
"repo_name": "neilime/zf2-assets-bundle",
"id": "794f5c80adbe2511c1acd6862fd8f89d30d0f623",
"size": "7488",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/AssetsBundleTest/Controller/JsCustomControllerTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3143"
},
{
"name": "HTML",
"bytes": "1331"
},
{
"name": "JavaScript",
"bytes": "160558"
},
{
"name": "PHP",
"bytes": "215201"
}
],
"symlink_target": ""
} |
package org.apache.kafka.clients;
import org.apache.kafka.common.config.AbstractConfig;
import org.apache.kafka.common.config.ConfigDef;
import org.junit.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static org.apache.kafka.common.config.ConfigDef.Range.atLeast;
import static org.junit.Assert.assertEquals;
public class CommonClientConfigsTest {
private static class TestConfig extends AbstractConfig {
private static final ConfigDef CONFIG;
static {
CONFIG = new ConfigDef()
.define(CommonClientConfigs.RECONNECT_BACKOFF_MS_CONFIG,
ConfigDef.Type.LONG,
50L,
atLeast(0L),
ConfigDef.Importance.LOW,
"")
.define(CommonClientConfigs.RECONNECT_BACKOFF_MAX_MS_CONFIG,
ConfigDef.Type.LONG,
1000L,
atLeast(0L),
ConfigDef.Importance.LOW,
"");
}
@Override
protected Map<String, Object> postProcessParsedConfig(final Map<String, Object> parsedValues) {
return CommonClientConfigs.postProcessReconnectBackoffConfigs(this, parsedValues);
}
public TestConfig(Map<?, ?> props) {
super(CONFIG, props);
}
}
@Test
public void testExponentialBackoffDefaults() {
TestConfig defaultConf = new TestConfig(Collections.emptyMap());
assertEquals(Long.valueOf(50L),
defaultConf.getLong(CommonClientConfigs.RECONNECT_BACKOFF_MS_CONFIG));
assertEquals(Long.valueOf(1000L),
defaultConf.getLong(CommonClientConfigs.RECONNECT_BACKOFF_MAX_MS_CONFIG));
TestConfig bothSetConfig = new TestConfig(new HashMap<String, Object>() {{
put(CommonClientConfigs.RECONNECT_BACKOFF_MS_CONFIG, "123");
put(CommonClientConfigs.RECONNECT_BACKOFF_MAX_MS_CONFIG, "12345");
}});
assertEquals(Long.valueOf(123L),
bothSetConfig.getLong(CommonClientConfigs.RECONNECT_BACKOFF_MS_CONFIG));
assertEquals(Long.valueOf(12345L),
bothSetConfig.getLong(CommonClientConfigs.RECONNECT_BACKOFF_MAX_MS_CONFIG));
TestConfig reconnectBackoffSetConf = new TestConfig(new HashMap<String, Object>() {{
put(CommonClientConfigs.RECONNECT_BACKOFF_MS_CONFIG, "123");
}});
assertEquals(Long.valueOf(123L),
reconnectBackoffSetConf.getLong(CommonClientConfigs.RECONNECT_BACKOFF_MS_CONFIG));
assertEquals(Long.valueOf(123L),
reconnectBackoffSetConf.getLong(CommonClientConfigs.RECONNECT_BACKOFF_MAX_MS_CONFIG));
}
}
| {
"content_hash": "430ee2e888af72d2256ac72192bc20f1",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 103,
"avg_line_length": 39.81428571428572,
"alnum_prop": 0.6393972012917115,
"repo_name": "KevinLiLu/kafka",
"id": "d65e6d1cbdc50b4436d52e2c1b2d32d88f4d8d3e",
"size": "3585",
"binary": false,
"copies": "3",
"ref": "refs/heads/trunk",
"path": "clients/src/test/java/org/apache/kafka/clients/CommonClientConfigsTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "29277"
},
{
"name": "Dockerfile",
"bytes": "6044"
},
{
"name": "HTML",
"bytes": "3739"
},
{
"name": "Java",
"bytes": "17318873"
},
{
"name": "Python",
"bytes": "851864"
},
{
"name": "Scala",
"bytes": "6380036"
},
{
"name": "Shell",
"bytes": "91444"
},
{
"name": "XSLT",
"bytes": "7116"
}
],
"symlink_target": ""
} |
FROM balenalib/jetson-tx2-ubuntu:xenial-run
# A few reasons for installing distribution-provided OpenJDK:
#
# 1. Oracle. Licensing prevents us from redistributing the official JDK.
#
# 2. Compiling OpenJDK also requires the JDK to be installed, and it gets
# really hairy.
#
# For some sample build times, see Debian's buildd logs:
# https://buildd.debian.org/status/logs.php?pkg=openjdk-7
# Default to UTF-8 file.encoding
ENV LANG C.UTF-8
# add a simple script that can auto-detect the appropriate JAVA_HOME value
# based on whether the JDK or only the JRE is installed
RUN { \
echo '#!/bin/sh'; \
echo 'set -e'; \
echo; \
echo 'dirname "$(dirname "$(readlink -f "$(which javac || which java)")")"'; \
} > /usr/local/bin/docker-java-home \
&& chmod +x /usr/local/bin/docker-java-home
# do some fancy footwork to create a JAVA_HOME that's cross-architecture-safe
RUN ln -svT "/usr/lib/jvm/java-11-openjdk-$(dpkg --print-architecture)" /docker-java-home
ENV JAVA_HOME /docker-java-home
RUN set -ex; \
\
# deal with slim variants not having man page directories (which causes "update-alternatives" to fail)
if [ ! -d /usr/share/man/man1 ]; then \
mkdir -p /usr/share/man/man1; \
fi; \
\
apt-get update; \
apt-get install -y --no-install-recommends \
software-properties-common \
; \
add-apt-repository ppa:openjdk-r/ppa; \
apt-get update; \
apt-get install -y --no-install-recommends \
openjdk-11-jre \
; \
rm -rf /var/lib/apt/lists/*; \
\
# verify that "docker-java-home" returns what we expect
[ "$(readlink -f "$JAVA_HOME")" = "$(docker-java-home)" ]; \
\
# update-alternatives so that future installs of other OpenJDK versions don't change /usr/bin/java
update-alternatives --get-selections | awk -v home="$(readlink -f "$JAVA_HOME")" 'index($3, home) == 1 { $2 = "manual"; print | "update-alternatives --set-selections" }'; \
# ... and verify that it actually worked for one of the alternatives we care about
update-alternatives --query java | grep -q 'Status: manual'
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Ubuntu xenial \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nOpenJDK v11-jre \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {
"content_hash": "47775699fdba45964a5c1395aff2a5e6",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 677,
"avg_line_length": 48.87301587301587,
"alnum_prop": 0.7021760311789542,
"repo_name": "nghiant2710/base-images",
"id": "632247f2f326e7b5880b93ec327821648a606862",
"size": "3100",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "balena-base-images/openjdk/jetson-tx2/ubuntu/xenial/11-jre/run/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "144558581"
},
{
"name": "JavaScript",
"bytes": "16316"
},
{
"name": "Shell",
"bytes": "368690"
}
],
"symlink_target": ""
} |
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using VerifyInsurance.Models;
namespace VerifyInsurance.Services
{
public class InsuranceService
{
private const string baseUrlFormat = "http://asfromania.ro/em/cedam/search.php?c={0}&v={1}&zi={2}&luna={3}&an={4}";
private const string chassisNumberFormat = "serie_caroserie";
private const string plateNumberFormat = "nr_inmatriculare";
public async Task<Result> VerifyByPlateNumber(string plateNumber, int day, int month, int year)
{
var date = GetDate(day, month, year);
return await MakeRequest(plateNumber, RequestType.ByPlateNumber, date);
}
public async Task<Result> VerifyByChassisNumber(string chassisNumber, int day, int month, int year)
{
var date = GetDate(day, month, year);
return await MakeRequest(chassisNumber, RequestType.ByChassisNumber, date);
}
private async Task<Result> MakeRequest(string input, RequestType type, DateTime date)
{
var webClient = new WebClient();
webClient.Encoding = System.Text.Encoding.UTF8;
var url = GetUrl(input, type, date);
try
{
var html = await webClient.DownloadStringTaskAsync(url);
var result = ParseHtml(html);
result.Input = input;
result.RequestType = type;
return result;
}
catch (Exception ex)
{
return GetResultWithError(input, type, ex);
}
}
private Result ParseHtml(string html)
{
var doc = new HtmlDocument();
doc.LoadHtml(html);
var result = new Result();
return result;
}
private string GetUrl(string input, RequestType type, DateTime date)
{
switch (type)
{
case RequestType.ByChassisNumber:
return GetUrlForChassisNumber(input, date);
case RequestType.ByPlateNumber:
default:
return GetUrlForPlateNumber(input, date);
}
}
private string GetUrlForChassisNumber(string number, DateTime date)
{
return string.Format(baseUrlFormat, chassisNumberFormat, number, date.Day, date.Month, date.Year);
}
private string GetUrlForPlateNumber(string number, DateTime date)
{
return string.Format(baseUrlFormat, plateNumberFormat, number, date.Day, date.Month, date.Year);
}
private DateTime GetDate(int day, int month, int year)
{
DateTime date;
try
{
date = new DateTime(year, month, day);
}
catch
{
date = DateTime.Now;
}
return date;
}
private Result GetResultWithError(string input, RequestType type, Exception ex)
{
return new Result
{
Input = input,
RequestType = type,
HasError = true,
Error = ex.Message
};
}
}
} | {
"content_hash": "beb0887f0b0a53038854204409c2317f",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 123,
"avg_line_length": 31.78301886792453,
"alnum_prop": 0.5598100326506382,
"repo_name": "radu-ungureanu/VerifyInsurance",
"id": "372a555c28e89e31a43bbc8b47067f0f1d63ecc3",
"size": "3371",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "VerifyInsurance/Services/InsuranceService.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "109"
},
{
"name": "C#",
"bytes": "144776"
},
{
"name": "CSS",
"bytes": "2626"
},
{
"name": "JavaScript",
"bytes": "146747"
}
],
"symlink_target": ""
} |
package com.google.errorprone.predicates.type;
import com.google.errorprone.VisitorState;
import com.google.errorprone.predicates.TypePredicate;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.util.ASTHelpers;
import com.sun.tools.javac.code.Type;
/** Matches types that exactly match the given type. */
public class Exact implements TypePredicate {
public final Supplier<Type> supplier;
public Exact(Supplier<Type> type) {
this.supplier = type;
}
@Override
public boolean apply(Type type, VisitorState state) {
Type expected = supplier.get(state);
if (expected == null || type == null) {
return false;
}
return ASTHelpers.isSameType(expected, type, state);
}
}
| {
"content_hash": "34a90dfd9e5e8958677cc3f524ddd6f0",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 56,
"avg_line_length": 26.321428571428573,
"alnum_prop": 0.7381275440976933,
"repo_name": "google/error-prone",
"id": "28dc78f149445033aa2e1353b9570f4ddd021796",
"size": "1344",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "check_api/src/main/java/com/google/errorprone/predicates/type/Exact.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "9329704"
},
{
"name": "Mustache",
"bytes": "1939"
},
{
"name": "Shell",
"bytes": "1915"
},
{
"name": "Starlark",
"bytes": "959"
}
],
"symlink_target": ""
} |
using EFSM.Designer.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
namespace EFSM.Designer.Extensions
{
public static class INamedEntityExtensions
{
public static string CreateUniqueName(this IEnumerable<string> existingNames, string format, StringComparison stringComparison = StringComparison.OrdinalIgnoreCase)
{
int index = 1;
string currentName = string.Format(format, index);
string[] materialized = existingNames.ToArray();
while (materialized.Any(n => string.Compare(n, currentName, stringComparison) == 0))
{
index++;
currentName = string.Format(format, index);
}
return currentName;
}
public static string CreateUniqueName<T>(this IEnumerable<T> namedItems, string format, StringComparison stringComparison = StringComparison.OrdinalIgnoreCase)
where T : INamedItem
{
var existingNames = namedItems.Select(n => n.Name);
return CreateUniqueName(existingNames, format, stringComparison);
}
}
}
| {
"content_hash": "586e78f84194c47aa366a726ed58bca9",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 172,
"avg_line_length": 32.083333333333336,
"alnum_prop": 0.651082251082251,
"repo_name": "CaptiveAire/EmbeddedFiniteStateMachine",
"id": "e7d4d0d18c56f8cb147a34a9eb9756d7ec580415",
"size": "1157",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "EFSM.Designer/Extensions/INamedEntityExtensions.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "39"
},
{
"name": "C",
"bytes": "332271"
},
{
"name": "C#",
"bytes": "365622"
},
{
"name": "HTML",
"bytes": "8997"
}
],
"symlink_target": ""
} |
package sbe.web1.mvc.validator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.ObjectUtils;
public class IdenticalFieldValidator implements ConstraintValidator<IdenticalField, Object> {
private String src;
private String dest;
private String message;
@Override
public void initialize(IdenticalField constraintAnnotation) {
this.src = constraintAnnotation.src();
this.dest = constraintAnnotation.dest();
this.message = constraintAnnotation.message();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
BeanWrapper beanWrapper = new BeanWrapperImpl(value);
Object srcVal = beanWrapper.getPropertyValue(src);
Object destVal = beanWrapper.getPropertyValue(dest);
boolean matched = ObjectUtils.nullSafeEquals(srcVal, destVal);
if (matched) {
return true;
}
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(message).addPropertyNode(src).addConstraintViolation();
context.buildConstraintViolationWithTemplate(message).addPropertyNode(dest).addConstraintViolation();
return false;
}
}
| {
"content_hash": "fe28089405a66eea82ed0784e04aa7cb",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 109,
"avg_line_length": 38.567567567567565,
"alnum_prop": 0.728801681850035,
"repo_name": "SecureSkyTechnology/springboot-exercise-web1",
"id": "63cca82b57e54ea9932a7ad9ed9e8478d7d8c582",
"size": "1427",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/sbe/web1/mvc/validator/IdenticalFieldValidator.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "5006"
},
{
"name": "CSS",
"bytes": "151"
},
{
"name": "HTML",
"bytes": "83164"
},
{
"name": "Java",
"bytes": "153041"
},
{
"name": "PLSQL",
"bytes": "1843"
},
{
"name": "Shell",
"bytes": "7058"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_45) on Mon Jun 24 22:25:09 UTC 2013 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.apache.hadoop.hbase.rest.RowResource (HBase 0.94.9 API)
</TITLE>
<META NAME="date" CONTENT="2013-06-24">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.hbase.rest.RowResource (HBase 0.94.9 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/hbase/rest/RowResource.html" title="class in org.apache.hadoop.hbase.rest"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/hadoop/hbase/rest//class-useRowResource.html" target="_top"><B>FRAMES</B></A>
<A HREF="RowResource.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.hadoop.hbase.rest.RowResource</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../org/apache/hadoop/hbase/rest/RowResource.html" title="class in org.apache.hadoop.hbase.rest">RowResource</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.hadoop.hbase.rest"><B>org.apache.hadoop.hbase.rest</B></A></TD>
<TD>HBase REST </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.hadoop.hbase.rest"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../org/apache/hadoop/hbase/rest/RowResource.html" title="class in org.apache.hadoop.hbase.rest">RowResource</A> in <A HREF="../../../../../../org/apache/hadoop/hbase/rest/package-summary.html">org.apache.hadoop.hbase.rest</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/apache/hadoop/hbase/rest/package-summary.html">org.apache.hadoop.hbase.rest</A> that return <A HREF="../../../../../../org/apache/hadoop/hbase/rest/RowResource.html" title="class in org.apache.hadoop.hbase.rest">RowResource</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/apache/hadoop/hbase/rest/RowResource.html" title="class in org.apache.hadoop.hbase.rest">RowResource</A></CODE></FONT></TD>
<TD><CODE><B>TableResource.</B><B><A HREF="../../../../../../org/apache/hadoop/hbase/rest/TableResource.html#getRowResource(java.lang.String, java.lang.String, java.lang.String)">getRowResource</A></B>(<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> rowspec,
<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> versions,
<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> check)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/hbase/rest/RowResource.html" title="class in org.apache.hadoop.hbase.rest"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/hadoop/hbase/rest//class-useRowResource.html" target="_top"><B>FRAMES</B></A>
<A HREF="RowResource.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2013 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All Rights Reserved.
</BODY>
</HTML>
| {
"content_hash": "1587c391e01cc654c64ae2de37e34315",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 353,
"avg_line_length": 47.49726775956284,
"alnum_prop": 0.6281638288080994,
"repo_name": "zqxjjj/NobidaBase",
"id": "b9d0288677556eb533d33a4c847d7127fbb7094d",
"size": "8692",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/apidocs/org/apache/hadoop/hbase/rest/class-use/RowResource.html",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "19836"
},
{
"name": "CSS",
"bytes": "42877"
},
{
"name": "Erlang",
"bytes": "324"
},
{
"name": "Java",
"bytes": "29972006"
},
{
"name": "PHP",
"bytes": "37634"
},
{
"name": "Perl",
"bytes": "20962"
},
{
"name": "Python",
"bytes": "29070"
},
{
"name": "Ruby",
"bytes": "779544"
},
{
"name": "Shell",
"bytes": "169607"
},
{
"name": "XSLT",
"bytes": "8758"
}
],
"symlink_target": ""
} |
{% extends 'base.html' %}
{% load static %}
{% block metatitle %}
<title>Model My Watershed - Micro Site Storm Model</title>
{% endblock metatitle %}
{% block header %}
<header class="water-balance">
<nav id="app-header" class="navbar-watershed">
<div class="brand"><a href="/">Model My Watershed</a><a href="#"> - Micro Site Storm Model</a></div>
<div class="navigation">
<ul class="main">
<li class="header-link">
<a target="_blank" rel="noopener noreferrer"
href="http://www.wikiwatershed.org">WikiWatershed</a>
</li>
<li class="header-link">
<div class="dropdown" data-toggle="tooltip" data-placement="bottom" title="Information">
<a class="main dropdown-toggle" type="button" data-toggle="dropdown" aria-expanded="true">
<i class="fa fa-info-circle"></i>
</a>
<div id="info" class="dropdown-menu menu-right" role="menu" aria-labelledby="select-area">
<h2>Water Balance Model</h2>
<p>Welcome to the Model My Watershed - Micro Site Storm Model simulator. See how changes in the amount of rainfall, the surfaces on which the rain falls and the texture of the soil change where the water goes. To begin, decide how much rain will fall by using the slide bar on the upper right. Then select the land-cover type where the rain will fall. Finally, pick a soil type. The coarsest soils (sandy soils) are on the left and the finest soils (clay loam) are on the right. As the simulation runs, follow where the water flows. Also, look at the column in the center that shows how much water goes in each direction.</p>
</div>
</div>
</li>
</ul>
</div>
</nav>
</header>
{% endblock header %}
{% block map %}
<div id="water-balance" class="container-fluid"> <!-- Container -->
<div class="canvas"> <!-- Canvas -->
<div class="model-container"> <!-- Model Container -->
<!-- OUTPUT WELLS -->
<div id="well-precip" class="well-custom text-center"> <!-- Precip Well -->
<h1 class="precip">0.0 cm</h1>
<label>Precipitation</label>
</div> <!-- End Precip Well -->
<div id="well-evapo" class="well-custom text-center"> <!-- Evapotranspiration Well -->
<h1 class="evapo">0.0 cm</h1>
<label>Evapotranspiration</label>
</div> <!-- End Evapotranspiration Well -->
<div id="well-runoff" class="well-custom text-center"> <!-- Runoff Well -->
<h1 class="runoff">0.0 cm</h1>
<label>Runoff</label>
</div> <!-- End Runoff Well -->
<div id="well-infil" class="well-custom text-center"> <!-- Infiltration Well -->
<h1 class="infil">0.0 cm</h1>
<label>Infiltration</label>
</div> <!-- End Infiltration Well -->
<!-- LANDCOVER -->
<div class="tab-content land-container text-center"> <!-- Land Cover Type -->
<!-- Effects -->
<div id="effect-precip" class="animated fadeInDown">
<img src="{% static 'images/water_balance/art_precip.png' %}" alt="precipitation">
</div>
<div id="effect-evapo" class="animated fadeInUp">
<svg style="width: 100%; height: 100%">
<image xlink:href="{% static 'images/water_balance/art_evapo.svg' %}" src="{% static 'images/water_balance/art_evapo.png' %}" width="100%" height="100%"></image>
</svg>
</div>
<!-- Land Cover -->
<div id="land-open_water" role="tabpanel" class="tab-pane land">
<img src="{% static 'images/water_balance/art_land_openwater.png' %}" alt="Open Water">
</div>
<div id="land-woody_wetlands" role="tabpanel" class="tab-pane land">
<img src="{% static 'images/water_balance/art_land_wetlands.png' %}" alt="Wetlands">
</div>
<div id="land-developed_low" role="tabpanel" class="tab-pane active land">
<img src="{% static 'images/water_balance/art_land_lir.png' %}" alt="Developed, Low Intensity">
</div>
<div id="land-developed_med" role="tabpanel" class="tab-pane land">
<img src="{% static 'images/water_balance/art_land_hir.png' %}" alt="Developed, Medium Intensity">
</div>
<div id="land-developed_high" role="tabpanel" class="tab-pane land">
<img src="{% static 'images/water_balance/art_land_commercial.png' %}" alt="Developed, High Intensity">
</div>
<div id="land-grassland" role="tabpanel" class="tab-pane land">
<img src="{% static 'images/water_balance/art_land_grassland.png' %}" alt="Grassland/Herbaceous">
</div>
<div id="land-deciduous_forest" role="tabpanel" class="tab-pane land">
<img src="{% static 'images/water_balance/art_land_forest.png' %}" alt="Deciduous Forest">
</div>
<div id="land-developed_open" role="tabpanel" class="tab-pane land">
<img src="{% static 'images/water_balance/art_land_turfGrass.png' %}" alt="Developed, Open Space">
</div>
<div id="land-pasture" role="tabpanel" class="tab-pane land">
<img src="{% static 'images/water_balance/art_land_pasture.png' %}" alt="Pasture/Hay">
</div>
<div id="land-cultivated_crops" role="tabpanel" class="tab-pane land">
<img src="{% static 'images/water_balance/art_land_rowCrops.png' %}" alt="Cultivated Crops">
</div>
<div id="land-shrub" role="tabpanel" class="tab-pane land">
<img src="{% static 'images/water_balance/art_land_chaparral.png' %}" alt="Shrub/Scrub">
</div>
<div id="land-barren_land" role="tabpanel" class="tab-pane land">
<img src="{% static 'images/water_balance/art_land_desert.png' %}" alt="Barren Land (Rock/Sand/Clay)">
</div>
</div> <!-- End Land Cover Type -->
<!-- SOIL -->
<div class="tab-content soil-container text-center"> <!-- Soil Type -->
<!-- Effects -->
<div id="effect-runoff" class="animated fadeInRight">
<svg style="width: 100%; height: 100%">
<image xlink:href="{% static 'images/water_balance/art_runoff.svg' %}" src="{% static 'images/water_balance/art_runoff.png' %}" width="100%" height="100%"></image>
</svg>
</div>
<div id="effect-infiltration" class="animated fadeInDown">
<svg style="width: 100%; height: 100%">
<image xlink:href="{% static 'images/water_balance/art_infiltration.svg' %}" src="{% static 'images/water_balance/art_infiltration.png' %}" width="100%" height="100%"></image>
</svg>
</div>
<!-- Land Cover -->
<div id="soil-sand" role="tabpanel" class="tab-pane soil active">
<img src="{% static 'images/water_balance/art_soil_sand.png' %}" alt="sand">
</div>
<div id="soil-loam" role="tabpanel" class="tab-pane soil">
<img src="{% static 'images/water_balance/art_soil_loam.png' %}" alt="loam">
</div>
<div id="soil-sandyClay" role="tabpanel" class="tab-pane soil">
<img src="{% static 'images/water_balance/art_soil_sandyClay.png' %}" alt="sandyClay">
</div>
<div id="soil-clayLoam" role="tabpanel" class="tab-pane soil">
<img src="{% static 'images/water_balance/art_soil_clayLoam.png' %}" alt="clayLoam">
</div>
</div> <!-- End Soil Type -->
</div> <!-- End Model Container -->
<div id="water-column-container" class="well-custom"> <!-- Water Column -->
<div id="alert">
<svg class="ic_approach" width="40" height="40">
<image xlink:href="{% static 'images/water_balance/art_alert.svg' %}" src="{% static 'images/water_balance/art_alert.svg' %}" width="40" height="40"></image>
</svg>
</div>
<div id="column-overlay"></div>
<div id="column-et" class="column" data-toggle="tooltip" data-placement="left" title="Evapotranspiration"><label>ET</label></div>
<div id="column-r" class="column" data-toggle="tooltip" data-placement="left" title="Runoff"><label>R</label></div>
<div id="column-i" class="column" data-toggle="tooltip" data-placement="left" title="Infiltration"><label>I</label></div>
<label>Water Column</label>
</div> <!-- End Water Column -->
</div> <!-- End Canvas -->
<!-- SIDEBAR -->
<div class="sidebar">
<div class="row pad-sm bdr-bottom"> <!-- Precipitation Slider -->
<div><p>Precipitation for 24-hour storm event</p></div>
<div class="well-precip row">
<label class="col-xs-2">
<img src="{% static 'images/water_balance/slider_min.png' %}" alt="slider min">
</label>
<div class="slider-wrapper col-xs-8">
<input id="precip-slider" class="slider" type="range" min="0" max="4" value="2">
</div>
<label class="col-xs-2">
<img src="{% static 'images/water_balance/slider_max.png' %}" alt="slider max">
</label>
</div>
</div> <!-- End Precipitation Slider -->
<div class="row pad-sm bdr-bottom"> <!-- Land Cover -->
<div class="pull-left"><p>Land Cover</p></div>
<ul id="thumbs-land" class="nav" role="tablist"> <!-- Landcover Thumbs -->
<li id="thumb-open_water">
<a href="#land-open_water" aria-controls="filter-tab" role="tab" data-toggle="tab" class="nlcd-11">
<img src="{% static 'images/water_balance/thumb_openwater.png' %}" alt="Open Water" data-name="open_water" data-container="body" data-toggle="popover" data-placement="left" data-category="nlcd-11">
</a>
<label>Water</label>
</li>
<li id="thumb-developed_open">
<a href="#land-developed_open" aria-controls="filter-tab" role="tab" data-toggle="tab" class="nlcd-21">
<img src="{% static 'images/water_balance/thumb_turfGrass.png' %}" alt="Developed, Open Space" data-name="developed_open" data-container="body" data-toggle="popover" data-placement="left" data-category="nlcd-21" >
</a>
<label>Developed-Open</label>
</li>
<li id="thumb-developed_low" class="active">
<a href="#land-developed_low" aria-controls="filter-tab" role="tab" data-toggle="tab" class="nlcd-22">
<img src="{% static 'images/water_balance/thumb_lir.png' %}" alt="Developed, Low Intensity" data-name="developed_low" data-container="body" data-toggle="popover" data-placement="left" data-category="nlcd-22" >
</a>
<label>Developed-Low</label>
</li>
<li id="thumb-developed_med">
<a href="#land-developed_med" aria-controls="filter-tab" role="tab" data-toggle="tab" class="nlcd-23">
<img src="{% static 'images/water_balance/thumb_hir.png' %}" alt="Developed, Medium Intensity" data-name="developed_med" data-container="body" data-toggle="popover" data-placement="left" data-category="nlcd-23" >
</a>
<label>Developed-Med</label>
</li>
<li id="thumb-developed_high">
<a href="#land-developed_high" aria-controls="filter-tab" role="tab" data-toggle="tab" class="nlcd-24">
<img src="{% static 'images/water_balance/thumb_commercial.png' %}" alt="Developed High Intensity" data-name="developed_high" data-container="body" data-toggle="popover" data-placement="left" data-category="nlcd-24" >
</a>
<label>Developed-High</label>
</li>
<li id="thumb-barren_land">
<a href="#land-barren_land" aria-controls="filter-tab" role="tab" data-toggle="tab" class="nlcd-31">
<img src="{% static 'images/water_balance/thumb_desert.png' %}" alt="Barren Land (Rock/Sand/Clay)" data-name="barren_land" data-container="body" data-toggle="popover" data-placement="left" data-category="nlcd-31" >
</a>
<label>Barren Land</label>
</li>
<li id="thumb-deciduous_forest">
<a href="#land-deciduous_forest" aria-controls="filter-tab" role="tab" data-toggle="tab" class="nlcd-41">
<img src="{% static 'images/water_balance/thumb_forest.png' %}" alt="Forest" data-container="body" data-name="deciduous_forest" data-toggle="popover" data-placement="left" data-category="nlcd-41" >
</a>
<label>Forest</label>
</li>
<li id="thumb-shrub">
<a href="#land-shrub" aria-controls="filter-tab" role="tab" data-toggle="tab" class="nlcd-52">
<img src="{% static 'images/water_balance/thumb_chaparral.png' %}" alt="Shrub/Scrub" data-name="shrub" data-container="body" data-toggle="popover" data-placement="left" data-category="nlcd-52" >
</a>
<label>Shrub/Scrub</label>
</li>
<li id="thumb-grassland">
<a href="#land-grassland" aria-controls="filter-tab" role="tab" data-toggle="tab" class="nlcd-71">
<img src="{% static 'images/water_balance/thumb_grassland.png' %}" alt="Grassland/Herbaceous" data-name="grassland" data-container="body" data-toggle="popover" data-placement="left" data-category="nlcd-71" >
</a>
<label>Grassland</label>
</li>
<li id="thumb-pasture">
<a href="#land-pasture" aria-controls="filter-tab" role="tab" data-toggle="tab" class="nlcd-81">
<img src="{% static 'images/water_balance/thumb_pasture.png' %}" alt="Pasture/Hay" data-name="pasture" data-container="body" data-toggle="popover" data-placement="left" data-category="nlcd-81" >
</a>
<label>Pasture/Hay</label>
</li>
<li id="thumb-cultivated_crops">
<a href="#land-cultivated_crops" aria-controls="filter-tab" role="tab" data-toggle="tab" class="nlcd-82">
<img src="{% static 'images/water_balance/thumb_rowCrops.png' %}" alt="Cultivated Crops" data-name="cultivated_crops" data-container="body" data-toggle="popover" data-placement="left" data-category="nlcd-82" >
</a>
<label>Crops</label>
</li>
<li id="thumb-woody_wetlands">
<a href="#land-woody_wetlands" aria-controls="filter-tab" role="tab" data-toggle="tab" class="nlcd-90">
<img src="{% static 'images/water_balance/thumb_wetlands.png' %}" alt="Wetlands" data-name="woody_wetlands" data-container="body" data-toggle="popover" data-placement="left" data-category="nlcd-90" >
</a>
<label>Wetlands</label>
</li>
</ul> <!-- End Landcover Thumbs-->
</div> <!-- End Land Cover -->
<div class="row pad-sm"> <!-- SoilS -->
<div class="pull-left"><p>Hydrologic Soil Group</p></div>
<ul id="thumbs-soil" class="nav" role="tablist"> <!-- Soil Thumbs -->
<li id="thumb-sand" class="active"> <!-- Sand Thumb -->
<a href="#soil-sand" aria-controls="filter-tab" role="tab" data-toggle="tab" class="soil-a">
<img src="{% static 'images/water_balance/thumb_sand.png' %}" alt="Sand" data-name="soil_a" data-container="body" data-toggle="popover" data-placement="left" data-category="soil-a">
</a>
<label>A - High Infiltration</label>
</li>
<li id="thumb-loam"> <!-- Loam Thumb -->
<a href="#soil-loam" aria-controls="filter-tab" role="tab" data-toggle="tab" class="soil-b">
<img src="{% static 'images/water_balance/thumb_loam.png' %}" alt="loam" data-name="soil_b" data-container="body" data-toggle="popover" data-placement="left" data-category="soil-b">
</a>
<label>B - Moderate Infiltration</label>
</li>
<li id="thumb-sandyClay"> <!-- Sandy Clay Thumb -->
<a href="#soil-sandyClay" aria-controls="filter-tab" role="tab" data-toggle="tab" class="soil-c">
<img src="{% static 'images/water_balance/thumb_sandyClay.png' %}" alt="Sandy Clay" data-name="soil_c" data-container="body" data-toggle="popover" data-placement="left" data-category="soil-c">
</a>
<label>C - Slow Infiltration</label>
</li>
<li id="thumb-clayLoam"> <!-- Clay Loam Thumb -->
<a href="#soil-clayLoam" aria-controls="filter-tab" role="tab" data-toggle="tab" class="soil-d">
<img src="{% static 'images/water_balance/thumb_clayLoam.png' %}" alt="Clay Loam" data-name="soil_d" data-container="body" data-toggle="popover" data-placement="left" data-category="soil-d">
</a>
<label>D - Very Slow Infiltration</label>
</li>
</ul> <!-- End Soil Thumbs-->
</div> <!-- End Soils -->
<div class="row pad-sm">
<p class="info text-muted">Apply our <a href="http://modelmywatershed.org" target="_blank" rel="noopener noreferrer">Site Storm Model</a> to your watershed. Info and help at <a target="_blank" href="http://wikiwatershed.org/model/">http://wikiwatershed.org/model/</a>.</p>
</div>
</div>
</div> <!-- End Container -->
{% endblock map %}
{% block javascript %}
<script type="text/javascript" src="{% static 'js/vendor_water_balance.js' %}"></script>
<script type="text/javascript" src="{% static 'js/main_water_balance.js' %}"></script>
{% endblock javascript %}
| {
"content_hash": "22f0fd4225e6b8398cfe585f40dab30d",
"timestamp": "",
"source": "github",
"line_count": 350,
"max_line_length": 660,
"avg_line_length": 58.19428571428571,
"alnum_prop": 0.5045659858601729,
"repo_name": "WikiWatershed/model-my-watershed",
"id": "efb13fd440266dae091a98049f7a266a87c63b50",
"size": "20368",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/mmw/apps/water_balance/templates/home_page/index.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CartoCSS",
"bytes": "11602"
},
{
"name": "HTML",
"bytes": "1312164"
},
{
"name": "JavaScript",
"bytes": "2286872"
},
{
"name": "Jinja",
"bytes": "8016"
},
{
"name": "Python",
"bytes": "859002"
},
{
"name": "Ruby",
"bytes": "1248"
},
{
"name": "SCSS",
"bytes": "411655"
},
{
"name": "Shell",
"bytes": "20014"
}
],
"symlink_target": ""
} |
package org.elasticsearch.ingest.common;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.ingest.Processor;
import org.elasticsearch.ingest.ProcessorsRegistry;
import org.elasticsearch.ingest.TestProcessor;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.test.ESTestCase;
import org.hamcrest.Matchers;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static org.mockito.Mockito.mock;
public class ForEachProcessorFactoryTests extends ESTestCase {
public void testCreate() throws Exception {
ProcessorsRegistry.Builder builder = new ProcessorsRegistry.Builder();
Processor processor = new TestProcessor(ingestDocument -> {});
builder.registerProcessor("_name", (registry) -> config -> processor);
ProcessorsRegistry registry = builder.build(mock(ScriptService.class), mock(ClusterService.class));
ForEachProcessor.Factory forEachFactory = new ForEachProcessor.Factory(registry);
Map<String, Object> config = new HashMap<>();
config.put("field", "_field");
config.put("processors", Collections.singletonList(Collections.singletonMap("_name", Collections.emptyMap())));
ForEachProcessor forEachProcessor = forEachFactory.create(config);
assertThat(forEachProcessor, Matchers.notNullValue());
assertThat(forEachProcessor.getField(), Matchers.equalTo("_field"));
assertThat(forEachProcessor.getProcessors().size(), Matchers.equalTo(1));
assertThat(forEachProcessor.getProcessors().get(0), Matchers.sameInstance(processor));
config = new HashMap<>();
config.put("processors", Collections.singletonList(Collections.singletonMap("_name", Collections.emptyMap())));
try {
forEachFactory.create(config);
fail("exception expected");
} catch (Exception e) {
assertThat(e.getMessage(), Matchers.equalTo("[field] required property is missing"));
}
config = new HashMap<>();
config.put("field", "_field");
try {
forEachFactory.create(config);
fail("exception expected");
} catch (Exception e) {
assertThat(e.getMessage(), Matchers.equalTo("[processors] required property is missing"));
}
}
}
| {
"content_hash": "9de1294894dea0097900142386e1c137",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 119,
"avg_line_length": 41.875,
"alnum_prop": 0.7019189765458422,
"repo_name": "palecur/elasticsearch",
"id": "d45e98ab06ac5845f99a268114dc58d753d025af",
"size": "3133",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/ForEachProcessorFactoryTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "12298"
},
{
"name": "Batchfile",
"bytes": "16353"
},
{
"name": "Emacs Lisp",
"bytes": "3341"
},
{
"name": "FreeMarker",
"bytes": "45"
},
{
"name": "Groovy",
"bytes": "251756"
},
{
"name": "HTML",
"bytes": "5348"
},
{
"name": "Java",
"bytes": "36569179"
},
{
"name": "Perl",
"bytes": "7116"
},
{
"name": "Python",
"bytes": "76119"
},
{
"name": "Shell",
"bytes": "102339"
}
],
"symlink_target": ""
} |
using System;
using System.Diagnostics.CodeAnalysis;
namespace Octokit.Reactive
{
/// <summary>
/// A client for GitHub's Pull Requests API.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/activity/notifications/">Pull Requests API documentation</a> for more information.
/// </remarks>
public interface IObservablePullRequestsClient
{
/// <summary>
/// Client for managing reviews.
/// </summary>
IObservablePullRequestReviewsClient Review { get; }
/// <summary>
/// Client for managing review comments.
/// </summary>
IObservablePullRequestReviewCommentsClient ReviewComment { get; }
/// <summary>
/// Client for managing review requests.
/// </summary>
IObservablePullRequestReviewRequestsClient ReviewRequest { get; }
/// <summary>
/// Client for locking/unlocking a conversation on a pull request
/// </summary>
IObservableLockUnlockClient LockUnlock { get; }
/// <summary>
/// Gets a single Pull Request by number.
/// </summary>
/// <remarks>
/// http://developer.github.com/v3/pulls/#get-a-single-pull-request
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="number">The number of the pull request</param>
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get",
Justification = "Method makes a network request")]
IObservable<PullRequest> Get(string owner, string name, int number);
/// <summary>
/// Gets a single Pull Request by number.
/// </summary>
/// <remarks>
/// http://developer.github.com/v3/pulls/#get-a-single-pull-request
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="number">The number of the pull request</param>
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get",
Justification = "Method makes a network request")]
IObservable<PullRequest> Get(long repositoryId, int number);
/// <summary>
/// Gets all open pull requests for the repository.
/// </summary>
/// <remarks>
/// http://developer.github.com/v3/pulls/#list-pull-requests
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
IObservable<PullRequest> GetAllForRepository(string owner, string name);
/// <summary>
/// Gets all open pull requests for the repository.
/// </summary>
/// <remarks>
/// http://developer.github.com/v3/pulls/#list-pull-requests
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
IObservable<PullRequest> GetAllForRepository(long repositoryId);
/// <summary>
/// Gets all open pull requests for the repository.
/// </summary>
/// <remarks>
/// http://developer.github.com/v3/pulls/#list-pull-requests
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="options">Options for changing the API response</param>
IObservable<PullRequest> GetAllForRepository(string owner, string name, ApiOptions options);
/// <summary>
/// Gets all open pull requests for the repository.
/// </summary>
/// <remarks>
/// http://developer.github.com/v3/pulls/#list-pull-requests
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="options">Options for changing the API response</param>
IObservable<PullRequest> GetAllForRepository(long repositoryId, ApiOptions options);
/// <summary>
/// Query pull requests for the repository based on criteria
/// </summary>
/// <remarks>
/// http://developer.github.com/v3/pulls/#list-pull-requests
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="request">Used to filter and sort the list of pull requests returned</param>
IObservable<PullRequest> GetAllForRepository(string owner, string name, PullRequestRequest request);
/// <summary>
/// Query pull requests for the repository based on criteria
/// </summary>
/// <remarks>
/// http://developer.github.com/v3/pulls/#list-pull-requests
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="request">Used to filter and sort the list of pull requests returned</param>
IObservable<PullRequest> GetAllForRepository(long repositoryId, PullRequestRequest request);
/// <summary>
/// Query pull requests for the repository based on criteria
/// </summary>
/// <remarks>
/// http://developer.github.com/v3/pulls/#list-pull-requests
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="request">Used to filter and sort the list of pull requests returned</param>
/// <param name="options">Options for changing the API response</param>
IObservable<PullRequest> GetAllForRepository(string owner, string name, PullRequestRequest request, ApiOptions options);
/// <summary>
/// Query pull requests for the repository based on criteria
/// </summary>
/// <remarks>
/// http://developer.github.com/v3/pulls/#list-pull-requests
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="request">Used to filter and sort the list of pull requests returned</param>
/// <param name="options">Options for changing the API response</param>
IObservable<PullRequest> GetAllForRepository(long repositoryId, PullRequestRequest request, ApiOptions options);
/// <summary>
/// Creates a pull request for the specified repository.
/// </summary>
/// <remarks>http://developer.github.com/v3/pulls/#create-a-pull-request</remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="newPullRequest">A <see cref="NewPullRequest"/> instance describing the new PullRequest to create</param>
IObservable<PullRequest> Create(string owner, string name, NewPullRequest newPullRequest);
/// <summary>
/// Creates a pull request for the specified repository.
/// </summary>
/// <remarks>http://developer.github.com/v3/pulls/#create-a-pull-request</remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="newPullRequest">A <see cref="NewPullRequest"/> instance describing the new PullRequest to create</param>
IObservable<PullRequest> Create(long repositoryId, NewPullRequest newPullRequest);
/// <summary>
/// Update a pull request for the specified repository.
/// </summary>
/// <remarks>http://developer.github.com/v3/pulls/#update-a-pull-request</remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="number">The PullRequest number</param>
/// <param name="pullRequestUpdate">An <see cref="PullRequestUpdate"/> instance describing the changes to make to the PullRequest
/// </param>
IObservable<PullRequest> Update(string owner, string name, int number, PullRequestUpdate pullRequestUpdate);
/// <summary>
/// Update a pull request for the specified repository.
/// </summary>
/// <remarks>http://developer.github.com/v3/pulls/#update-a-pull-request</remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="number">The PullRequest number</param>
/// <param name="pullRequestUpdate">An <see cref="PullRequestUpdate"/> instance describing the changes to make to the PullRequest
/// </param>
IObservable<PullRequest> Update(long repositoryId, int number, PullRequestUpdate pullRequestUpdate);
/// <summary>
/// Merge a pull request.
/// </summary>
/// <remarks>http://developer.github.com/v3/pulls/#merge-a-pull-request-merge-buttontrade</remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="number">The pull request number</param>
/// <param name="mergePullRequest">A <see cref="MergePullRequest"/> instance describing a pull request merge</param>
IObservable<PullRequestMerge> Merge(string owner, string name, int number, MergePullRequest mergePullRequest);
/// <summary>
/// Merge a pull request.
/// </summary>
/// <remarks>http://developer.github.com/v3/pulls/#merge-a-pull-request-merge-buttontrade</remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="number">The pull request number</param>
/// <param name="mergePullRequest">A <see cref="MergePullRequest"/> instance describing a pull request merge</param>
IObservable<PullRequestMerge> Merge(long repositoryId, int number, MergePullRequest mergePullRequest);
/// <summary>
/// Gets the pull request merge status.
/// </summary>
/// <remarks>http://developer.github.com/v3/pulls/#get-if-a-pull-request-has-been-merged</remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="number">The pull request number</param>
IObservable<bool> Merged(string owner, string name, int number);
/// <summary>
/// Gets the pull request merge status.
/// </summary>
/// <remarks>http://developer.github.com/v3/pulls/#get-if-a-pull-request-has-been-merged</remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="number">The pull request number</param>
IObservable<bool> Merged(long repositoryId, int number);
/// <summary>
/// Gets the list of commits on a pull request.
/// </summary>
/// <remarks>http://developer.github.com/v3/pulls/#list-commits-on-a-pull-request</remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="number">The pull request number</param>
IObservable<PullRequestCommit> Commits(string owner, string name, int number);
/// <summary>
/// Gets the list of commits on a pull request.
/// </summary>
/// <remarks>http://developer.github.com/v3/pulls/#list-commits-on-a-pull-request</remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="number">The pull request number</param>
IObservable<PullRequestCommit> Commits(long repositoryId, int number);
/// <summary>
/// Get the list of files on a pull request.
/// </summary>
/// <remarks>https://developer.github.com/v3/pulls/#list-pull-requests-files</remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="number">The pull request number</param>
/// <param name="options">Options for changing the API response</param>
IObservable<PullRequestFile> Files(string owner, string name, int number, ApiOptions options);
/// <summary>
/// Get the list of files on a pull request.
/// </summary>
/// <remarks>https://developer.github.com/v3/pulls/#list-pull-requests-files</remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="number">The pull request number</param>
IObservable<PullRequestFile> Files(string owner, string name, int number);
/// <summary>
/// Get the list of files on a pull request.
/// </summary>
/// <remarks>https://developer.github.com/v3/pulls/#list-pull-requests-files</remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="number">The pull request number</param>
/// <param name="options">Options for changing the API response</param>
IObservable<PullRequestFile> Files(long repositoryId, int number, ApiOptions options);
/// <summary>
/// Get the list of files on a pull request.
/// </summary>
/// <remarks>https://developer.github.com/v3/pulls/#list-pull-requests-files</remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="number">The pull request number</param>
IObservable<PullRequestFile> Files(long repositoryId, int number);
}
}
| {
"content_hash": "a0b1900f652fbd01a6b8f066558fb4ba",
"timestamp": "",
"source": "github",
"line_count": 270,
"max_line_length": 138,
"avg_line_length": 51.01851851851852,
"alnum_prop": 0.6299818511796733,
"repo_name": "octokit/octokit.net",
"id": "510769f8da48b8140db48ddd7ab06e5b7127c8da",
"size": "13777",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "Octokit.Reactive/Clients/IObservablePullRequestsClient.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "9254544"
},
{
"name": "Dockerfile",
"bytes": "889"
},
{
"name": "PowerShell",
"bytes": "8425"
},
{
"name": "Shell",
"bytes": "442"
}
],
"symlink_target": ""
} |
import numpy as np
import modred as mr
# Create random data
num_vecs = 100
nx = 100
vecs = np.random.random((nx, num_vecs))
# Define non-uniform grid and corresponding inner product weights
x_grid = 1. - np.cos(np.linspace(0, np.pi, nx))
x_diff = np.diff(x_grid)
weights = 0.5 * np.append(np.append(
x_diff[0], x_diff[:-1] + x_diff[1:]), x_diff[-1])
# Compute POD
num_modes = 10
POD_res = mr.compute_POD_arrays_direct_method(
vecs, list(mr.range(num_modes)), inner_product_weights=weights)
modes = POD_res.modes
eigvals = POD_res.eigvals
| {
"content_hash": "80ef0e21fbcfc7d6e87d6b2941fb1a56",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 67,
"avg_line_length": 25.045454545454547,
"alnum_prop": 0.6860254083484574,
"repo_name": "belson17/modred",
"id": "1ec310f67d6dc1e4d68d2029aab218035faf3cff",
"size": "551",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modred/examples/tutorial_ex2.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "MATLAB",
"bytes": "5666"
},
{
"name": "Python",
"bytes": "525224"
}
],
"symlink_target": ""
} |
package org.apache.accumulo.server.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.HashSet;
import java.util.Map.Entry;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.BatchWriterConfig;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.client.mock.MockInstance;
import org.apache.accumulo.core.client.security.tokens.PasswordToken;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.data.impl.KeyExtent;
import org.apache.accumulo.core.metadata.MetadataTable;
import org.apache.accumulo.core.metadata.schema.DataFileValue;
import org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection;
import org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection.DataFileColumnFamily;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.hadoop.io.Text;
import org.junit.Test;
public class CloneTest {
@Test
public void testNoFiles() throws Exception {
MockInstance mi = new MockInstance();
Connector conn = mi.getConnector("", new PasswordToken(""));
KeyExtent ke = new KeyExtent(new Text("0"), null, null);
Mutation mut = ke.getPrevRowUpdateMutation();
TabletsSection.ServerColumnFamily.TIME_COLUMN.put(mut, new Value("M0".getBytes()));
TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(mut, new Value("/default_tablet".getBytes()));
BatchWriter bw1 = conn.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig());
bw1.addMutation(mut);
bw1.close();
BatchWriter bw2 = conn.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig());
MetadataTableUtil.initializeClone("0", "1", conn, bw2);
int rc = MetadataTableUtil.checkClone("0", "1", conn, bw2);
assertEquals(0, rc);
// scan tables metadata entries and confirm the same
}
@Test
public void testFilesChange() throws Exception {
MockInstance mi = new MockInstance();
Connector conn = mi.getConnector("", new PasswordToken(""));
KeyExtent ke = new KeyExtent(new Text("0"), null, null);
Mutation mut = ke.getPrevRowUpdateMutation();
TabletsSection.ServerColumnFamily.TIME_COLUMN.put(mut, new Value("M0".getBytes()));
TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(mut, new Value("/default_tablet".getBytes()));
mut.put(DataFileColumnFamily.NAME.toString(), "/default_tablet/0_0.rf", new DataFileValue(1, 200).encodeAsString());
BatchWriter bw1 = conn.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig());
bw1.addMutation(mut);
bw1.flush();
BatchWriter bw2 = conn.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig());
MetadataTableUtil.initializeClone("0", "1", conn, bw2);
Mutation mut2 = new Mutation(ke.getMetadataEntry());
mut2.putDelete(DataFileColumnFamily.NAME.toString(), "/default_tablet/0_0.rf");
mut2.put(DataFileColumnFamily.NAME.toString(), "/default_tablet/1_0.rf", new DataFileValue(2, 300).encodeAsString());
bw1.addMutation(mut2);
bw1.flush();
int rc = MetadataTableUtil.checkClone("0", "1", conn, bw2);
assertEquals(1, rc);
rc = MetadataTableUtil.checkClone("0", "1", conn, bw2);
assertEquals(0, rc);
Scanner scanner = conn.createScanner(MetadataTable.NAME, Authorizations.EMPTY);
scanner.setRange(new KeyExtent(new Text("1"), null, null).toMetadataRange());
HashSet<String> files = new HashSet<>();
for (Entry<Key,Value> entry : scanner) {
if (entry.getKey().getColumnFamily().equals(DataFileColumnFamily.NAME))
files.add(entry.getKey().getColumnQualifier().toString());
}
assertEquals(1, files.size());
assertTrue(files.contains("../0/default_tablet/1_0.rf"));
}
// test split where files of children are the same
@Test
public void testSplit1() throws Exception {
MockInstance mi = new MockInstance();
Connector conn = mi.getConnector("", new PasswordToken(""));
BatchWriter bw1 = conn.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig());
bw1.addMutation(createTablet("0", null, null, "/default_tablet", "/default_tablet/0_0.rf"));
bw1.flush();
BatchWriter bw2 = conn.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig());
MetadataTableUtil.initializeClone("0", "1", conn, bw2);
bw1.addMutation(createTablet("0", "m", null, "/default_tablet", "/default_tablet/0_0.rf"));
bw1.addMutation(createTablet("0", null, "m", "/t-1", "/default_tablet/0_0.rf"));
bw1.flush();
int rc = MetadataTableUtil.checkClone("0", "1", conn, bw2);
assertEquals(0, rc);
Scanner scanner = conn.createScanner(MetadataTable.NAME, Authorizations.EMPTY);
scanner.setRange(new KeyExtent(new Text("1"), null, null).toMetadataRange());
HashSet<String> files = new HashSet<>();
int count = 0;
for (Entry<Key,Value> entry : scanner) {
if (entry.getKey().getColumnFamily().equals(DataFileColumnFamily.NAME)) {
files.add(entry.getKey().getColumnQualifier().toString());
count++;
}
}
assertEquals(1, count);
assertEquals(1, files.size());
assertTrue(files.contains("../0/default_tablet/0_0.rf"));
}
// test split where files of children differ... like majc and split occurred
@Test
public void testSplit2() throws Exception {
MockInstance mi = new MockInstance();
Connector conn = mi.getConnector("", new PasswordToken(""));
BatchWriter bw1 = conn.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig());
bw1.addMutation(createTablet("0", null, null, "/default_tablet", "/default_tablet/0_0.rf"));
bw1.flush();
BatchWriter bw2 = conn.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig());
MetadataTableUtil.initializeClone("0", "1", conn, bw2);
bw1.addMutation(createTablet("0", "m", null, "/default_tablet", "/default_tablet/1_0.rf"));
Mutation mut3 = createTablet("0", null, "m", "/t-1", "/default_tablet/1_0.rf");
mut3.putDelete(DataFileColumnFamily.NAME.toString(), "/default_tablet/0_0.rf");
bw1.addMutation(mut3);
bw1.flush();
int rc = MetadataTableUtil.checkClone("0", "1", conn, bw2);
assertEquals(1, rc);
rc = MetadataTableUtil.checkClone("0", "1", conn, bw2);
assertEquals(0, rc);
Scanner scanner = conn.createScanner(MetadataTable.NAME, Authorizations.EMPTY);
scanner.setRange(new KeyExtent(new Text("1"), null, null).toMetadataRange());
HashSet<String> files = new HashSet<>();
int count = 0;
for (Entry<Key,Value> entry : scanner) {
if (entry.getKey().getColumnFamily().equals(DataFileColumnFamily.NAME)) {
files.add(entry.getKey().getColumnQualifier().toString());
count++;
}
}
assertEquals(1, files.size());
assertEquals(2, count);
assertTrue(files.contains("../0/default_tablet/1_0.rf"));
}
private static Mutation deleteTablet(String tid, String endRow, String prevRow, String dir, String file) throws Exception {
KeyExtent ke = new KeyExtent(new Text(tid), endRow == null ? null : new Text(endRow), prevRow == null ? null : new Text(prevRow));
Mutation mut = new Mutation(ke.getMetadataEntry());
TabletsSection.TabletColumnFamily.PREV_ROW_COLUMN.putDelete(mut);
TabletsSection.ServerColumnFamily.TIME_COLUMN.putDelete(mut);
TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.putDelete(mut);
mut.putDelete(DataFileColumnFamily.NAME.toString(), file);
return mut;
}
private static Mutation createTablet(String tid, String endRow, String prevRow, String dir, String file) throws Exception {
KeyExtent ke = new KeyExtent(new Text(tid), endRow == null ? null : new Text(endRow), prevRow == null ? null : new Text(prevRow));
Mutation mut = ke.getPrevRowUpdateMutation();
TabletsSection.ServerColumnFamily.TIME_COLUMN.put(mut, new Value("M0".getBytes()));
TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN.put(mut, new Value(dir.getBytes()));
mut.put(DataFileColumnFamily.NAME.toString(), file, new DataFileValue(10, 200).encodeAsString());
return mut;
}
// test two tablets splitting into four
@Test
public void testSplit3() throws Exception {
MockInstance mi = new MockInstance();
Connector conn = mi.getConnector("", new PasswordToken(""));
BatchWriter bw1 = conn.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig());
bw1.addMutation(createTablet("0", "m", null, "/d1", "/d1/file1"));
bw1.addMutation(createTablet("0", null, "m", "/d2", "/d2/file2"));
bw1.flush();
BatchWriter bw2 = conn.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig());
MetadataTableUtil.initializeClone("0", "1", conn, bw2);
bw1.addMutation(createTablet("0", "f", null, "/d1", "/d1/file3"));
bw1.addMutation(createTablet("0", "m", "f", "/d3", "/d1/file1"));
bw1.addMutation(createTablet("0", "s", "m", "/d2", "/d2/file2"));
bw1.addMutation(createTablet("0", null, "s", "/d4", "/d2/file2"));
bw1.flush();
int rc = MetadataTableUtil.checkClone("0", "1", conn, bw2);
assertEquals(0, rc);
Scanner scanner = conn.createScanner(MetadataTable.NAME, Authorizations.EMPTY);
scanner.setRange(new KeyExtent(new Text("1"), null, null).toMetadataRange());
HashSet<String> files = new HashSet<>();
int count = 0;
for (Entry<Key,Value> entry : scanner) {
if (entry.getKey().getColumnFamily().equals(DataFileColumnFamily.NAME)) {
files.add(entry.getKey().getColumnQualifier().toString());
count++;
}
}
assertEquals(2, count);
assertEquals(2, files.size());
assertTrue(files.contains("../0/d1/file1"));
assertTrue(files.contains("../0/d2/file2"));
}
// test cloned marker
@Test
public void testClonedMarker() throws Exception {
MockInstance mi = new MockInstance();
Connector conn = mi.getConnector("", new PasswordToken(""));
BatchWriter bw1 = conn.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig());
bw1.addMutation(createTablet("0", "m", null, "/d1", "/d1/file1"));
bw1.addMutation(createTablet("0", null, "m", "/d2", "/d2/file2"));
bw1.flush();
BatchWriter bw2 = conn.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig());
MetadataTableUtil.initializeClone("0", "1", conn, bw2);
bw1.addMutation(deleteTablet("0", "m", null, "/d1", "/d1/file1"));
bw1.addMutation(deleteTablet("0", null, "m", "/d2", "/d2/file2"));
bw1.flush();
bw1.addMutation(createTablet("0", "f", null, "/d1", "/d1/file3"));
bw1.addMutation(createTablet("0", "m", "f", "/d3", "/d1/file1"));
bw1.addMutation(createTablet("0", "s", "m", "/d2", "/d2/file3"));
bw1.addMutation(createTablet("0", null, "s", "/d4", "/d4/file3"));
bw1.flush();
int rc = MetadataTableUtil.checkClone("0", "1", conn, bw2);
assertEquals(1, rc);
bw1.addMutation(deleteTablet("0", "m", "f", "/d3", "/d1/file1"));
bw1.flush();
bw1.addMutation(createTablet("0", "m", "f", "/d3", "/d1/file3"));
bw1.flush();
rc = MetadataTableUtil.checkClone("0", "1", conn, bw2);
assertEquals(0, rc);
Scanner scanner = conn.createScanner(MetadataTable.NAME, Authorizations.EMPTY);
scanner.setRange(new KeyExtent(new Text("1"), null, null).toMetadataRange());
HashSet<String> files = new HashSet<>();
int count = 0;
for (Entry<Key,Value> entry : scanner) {
if (entry.getKey().getColumnFamily().equals(DataFileColumnFamily.NAME)) {
files.add(entry.getKey().getColumnQualifier().toString());
count++;
}
}
assertEquals(3, count);
assertEquals(3, files.size());
assertTrue(files.contains("../0/d1/file1"));
assertTrue(files.contains("../0/d2/file3"));
assertTrue(files.contains("../0/d4/file3"));
}
// test two tablets splitting into four
@Test
public void testMerge() throws Exception {
MockInstance mi = new MockInstance();
Connector conn = mi.getConnector("", new PasswordToken(""));
BatchWriter bw1 = conn.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig());
bw1.addMutation(createTablet("0", "m", null, "/d1", "/d1/file1"));
bw1.addMutation(createTablet("0", null, "m", "/d2", "/d2/file2"));
bw1.flush();
BatchWriter bw2 = conn.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig());
MetadataTableUtil.initializeClone("0", "1", conn, bw2);
bw1.addMutation(deleteTablet("0", "m", null, "/d1", "/d1/file1"));
Mutation mut = createTablet("0", null, null, "/d2", "/d2/file2");
mut.put(DataFileColumnFamily.NAME.toString(), "/d1/file1", new DataFileValue(10, 200).encodeAsString());
bw1.addMutation(mut);
bw1.flush();
try {
MetadataTableUtil.checkClone("0", "1", conn, bw2);
assertTrue(false);
} catch (TabletIterator.TabletDeletedException tde) {}
}
}
| {
"content_hash": "2adb58d5bbbbc4fe92bc3ebf37eaa4c4",
"timestamp": "",
"source": "github",
"line_count": 370,
"max_line_length": 134,
"avg_line_length": 35.34324324324324,
"alnum_prop": 0.6839489179475415,
"repo_name": "adamjshook/accumulo",
"id": "58e6410c0beef5fe9fa7375d3fef94f79190a7af",
"size": "13878",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/base/src/test/java/org/apache/accumulo/server/util/CloneTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2423"
},
{
"name": "C++",
"bytes": "1414083"
},
{
"name": "CSS",
"bytes": "5933"
},
{
"name": "Groovy",
"bytes": "1385"
},
{
"name": "HTML",
"bytes": "11698"
},
{
"name": "Java",
"bytes": "20215877"
},
{
"name": "JavaScript",
"bytes": "249594"
},
{
"name": "Makefile",
"bytes": "2865"
},
{
"name": "Perl",
"bytes": "28190"
},
{
"name": "Protocol Buffer",
"bytes": "1325"
},
{
"name": "Python",
"bytes": "729147"
},
{
"name": "Ruby",
"bytes": "211593"
},
{
"name": "Shell",
"bytes": "194340"
},
{
"name": "Thrift",
"bytes": "55653"
}
],
"symlink_target": ""
} |
#ifndef WELS_DECODER_CORE_H__
#define WELS_DECODER_CORE_H__
#include "typedefs.h"
#include "wels_common_basis.h"
#include "decoder_context.h"
#include "codec_def.h"
namespace WelsDec {
/*
* InitBsBuffer
* Memory allocation for Bitstream Buffer
* return:
* 0 - success; otherwise returned error_no defined in error_no.h.
*/
int32_t InitBsBuffer (PWelsDecoderContext pCtx);
/*
* ExpandBsBuffer
* Expand current BS buffer and copy its content
* new buffer size will consider input size as a reference
* return:
* 0 - success; otherwise returned error_no defined in error_no.h.
*/
int32_t ExpandBsBuffer (PWelsDecoderContext pCtx, const int32_t kiSrcLen);
/*
* ExpandBsLenBuffer
* Expand current BS length buffer to double size or maximum, due to max slice number exceeding
* Parameter:
* kiCurrLen: current value of total nal number (including non-VCL nal)
* return:
* 0 - success; otherwise returned error_no defined in error_no.h.
*/
int32_t ExpandBsLenBuffer (PWelsDecoderContext pCtx, const int32_t kiCurrLen);
/*
* CheckBsBuffer
* Check if current buffer size is enough
*/
int32_t CheckBsBuffer (PWelsDecoderContext pCtx, const int32_t kiSrcLen);
/*
* WelsInitStaticMemory
* Memory request for introduced data at decoder start
* Especially for:
* rbsp_au_buffer, cur_dq_layer_ptr and ref_dq_layer_ptr in MB info cache.
* return:
* 0 - success; otherwise returned error_no defined in error_no.h.
*/
int32_t WelsInitStaticMemory (PWelsDecoderContext pCtx);
/*
* WelsFreeStaticMemory
* Free memory introduced in WelsInitStaticMemory at destruction of decoder.
*
*/
void WelsFreeStaticMemory (PWelsDecoderContext pCtx);
/*!
* \brief request memory when maximal picture width and height are available
*/
int32_t InitialDqLayersContext (PWelsDecoderContext pCtx, const int32_t kiMaxWidth, const int32_t kiMaxHeight);
/*!
* \brief free dq layer context memory related
*/
void UninitialDqLayersContext (PWelsDecoderContext pCtx);
/*
* DecodeNalHeaderExt
* Trigger condition: NAL_UNIT_TYPE = NAL_UNIT_PREFIX or NAL_UNIT_CODED_SLICE_EXT
* Parameter:
* pNal: target NALUnit ptr
* pSrc: NAL Unit bitstream
*/
void DecodeNalHeaderExt (PNalUnit pNal, uint8_t* pSrc);
/*
* ParseSliceHeaderSyntaxs
* Parse slice header of bitstream
*/
int32_t ParseSliceHeaderSyntaxs (PWelsDecoderContext pCtx, PBitStringAux pBs, const bool kbExtensionFlag);
/*
* Copy relative syntax elements of NALUnitHeaderExt, sRefPicBaseMarking and bStoreRefBasePicFlag in prefix nal unit.
* pSrc: mark as decoded prefix NAL
* pDst: succeeded VCL NAL based AVC (I/P Slice)
*/
bool PrefetchNalHeaderExtSyntax (PWelsDecoderContext pCtx, PNalUnit const kpDst, PNalUnit const kpSrc);
/*
* ConstructAccessUnit
* construct an access unit for given input bitstream, maybe partial NAL Unit, one or more Units are involved to
* joint a collective access unit.
* parameter\
* buf: bitstream data buffer
* bit_len: size in bit length of data
* buf_len: size in byte length of data
* coded_au: mark an Access Unit decoding finished
* return:
* 0 - success; otherwise returned error_no defined in error_no.h
*/
int32_t ConstructAccessUnit (PWelsDecoderContext pCtx, uint8_t** ppDst, SBufferInfo* pDstInfo);
/*
* DecodeCurrentAccessUnit
* Decode current access unit when current AU is completed.
*/
int32_t DecodeCurrentAccessUnit (PWelsDecoderContext pCtx, uint8_t** ppDst, SBufferInfo* pDstInfo);
/*
* Check if frame is completed and EC is required
*/
bool CheckAndFinishLastPic (PWelsDecoderContext pCtx, uint8_t** pDst, SBufferInfo* pDstInfo);
/*
* Prepare current dq layer context initialization.
*/
void WelsDqLayerDecodeStart (PWelsDecoderContext pCtx, PNalUnit pCurNal, PSps pSps, PPps pPps);
int32_t WelsDecodeAccessUnitStart (PWelsDecoderContext pCtx);
void WelsDecodeAccessUnitEnd (PWelsDecoderContext pCtx);
void DecodeFinishUpdate (PWelsDecoderContext pCtx);
void ForceResetCurrentAccessUnit (PAccessUnit pAu);
void ForceClearCurrentNal (PAccessUnit pAu);
bool CheckRefPicturesComplete (PWelsDecoderContext pCtx); // Check whether all ref pictures are complete
void ForceResetParaSetStatusAndAUList (PWelsDecoderContext pCtx);
} // namespace WelsDec
#endif//WELS_DECODER_CORE_H__
| {
"content_hash": "656ffd2ff7f4b2c95213319cf48237a2",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 118,
"avg_line_length": 30.769784172661872,
"alnum_prop": 0.7594108019639935,
"repo_name": "shihuade/openh264",
"id": "41cd1d6a98a3dca7247109151303c9e4443ddd8d",
"size": "5984",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "codec/decoder/core/inc/decoder_core.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "1404817"
},
{
"name": "Batchfile",
"bytes": "16595"
},
{
"name": "C",
"bytes": "676057"
},
{
"name": "C#",
"bytes": "26488"
},
{
"name": "C++",
"bytes": "4141276"
},
{
"name": "Dockerfile",
"bytes": "1660"
},
{
"name": "Java",
"bytes": "11303"
},
{
"name": "JavaScript",
"bytes": "603"
},
{
"name": "Makefile",
"bytes": "50916"
},
{
"name": "Meson",
"bytes": "13070"
},
{
"name": "Objective-C",
"bytes": "42368"
},
{
"name": "Python",
"bytes": "13031"
},
{
"name": "Shell",
"bytes": "97964"
}
],
"symlink_target": ""
} |
/* eslint-disable no-console */
/**
This module exports a "handler" function,
that wraps a customer function.
We bundle this module and its dependencies to "dist".
To bundle: `npm run build`
*/
import type { Headers, LambdaEvent } from '../types'
import type { APITypes } from '@oneblink/types'
type APIGatewayResult = {
statusCode: number
headers: Headers
body?: string
}
import path from 'path'
import querystring from 'querystring'
import handlers from '../handlers'
import wrapper from '../wrapper'
// return only the pertinent data from a API Gateway + Lambda event
function normaliseLambdaRequest<T>(
event: LambdaEvent,
): APITypes.OneBlinkAPIHostingRequest<T> {
const headers = wrapper.keysToLowerCase(event.headers)
let body = event.body
try {
body = JSON.parse(body)
} catch (e) {
// Do nothing...
}
const host = headers['x-forwarded-host'] || headers.host
return {
body,
headers,
method: wrapper.normaliseMethod(event.httpMethod),
route: event.path,
url: {
host,
hostname: host,
params: {},
pathname: event.path,
protocol: wrapper.protocolFromHeaders(headers),
query: event.queryStringParameters || {},
},
}
}
async function handler(
event: LambdaEvent,
context: any,
): Promise<APIGatewayResult> {
const startTime = Date.now()
context.callbackWaitsForEmptyEventLoop = false
const request = normaliseLambdaRequest<undefined>(event)
const internalHeaders: Headers = {
'Content-Type': 'application/json',
}
// eslint-disable-next-line @typescript-eslint/no-var-requires
const config = require(path.join(__dirname, 'bm-server.json'))
const finish = (
statusCode: number,
body: unknown | undefined,
customHeaders: Headers | void,
): APIGatewayResult => {
const headers = wrapper.keysToLowerCase(
Object.assign(internalHeaders, customHeaders),
)
const endTime = Date.now()
const requestTime = endTime - startTime
let path = request.url.pathname
const search = querystring.stringify(request.url.query)
if (search) {
path += `?${search}`
}
let referer = request.headers.referer
if (typeof referer !== 'string' || !referer) {
referer = '-'
}
let userAgent = request.headers['user-agent']
if (typeof userAgent !== 'string' || !userAgent) {
userAgent = '-'
}
console.log(
`${request.method.toUpperCase()} ${path}${querystring.stringify(
request.url.query,
)} ${statusCode} "${requestTime} ms" "${referer}" "${userAgent}"`,
)
const result: APIGatewayResult = {
headers: headers,
statusCode: statusCode,
}
if (body !== undefined) {
result.body = typeof body === 'string' ? body : JSON.stringify(body)
}
return result
}
try {
// Get handler module based on route
let routeConfig
try {
routeConfig = handlers.findRouteConfig(event.path, config.routes)
request.url.params = routeConfig.params || {}
request.route = routeConfig.route
} catch (error) {
return finish(404, {
error: 'Not Found',
message: error.message,
statusCode: 404,
})
}
// Check for browser requests and apply CORS if required
if (request.headers.origin) {
if (!config.cors) {
// No cors, we will return 405 result and let browser handler error
return finish(405, {
error: 'Method Not Allowed',
message: 'OPTIONS method has not been implemented',
statusCode: 405,
})
}
if (
!config.cors.origins.some(
(origin: any) => origin === '*' || origin === request.headers.origin,
)
) {
// Invalid origin, we will return 200 result and let browser handler error
return finish(200, undefined, undefined)
}
// Headers for all cross origin requests
internalHeaders['Access-Control-Allow-Origin'] = request.headers.origin
internalHeaders[
'Access-Control-Expose-Headers'
] = config.cors.exposedHeaders.join(',')
// Headers for OPTIONS cross origin requests
if (
request.method === 'options' &&
request.headers['access-control-request-method']
) {
internalHeaders[
'Access-Control-Allow-Headers'
] = config.cors.headers.join(',')
internalHeaders['Access-Control-Allow-Methods'] =
request.headers['access-control-request-method']
internalHeaders['Access-Control-Max-Age'] = config.cors.maxAge
}
// Only set credentials header if truthy
if (config.cors.credentials) {
internalHeaders['Access-Control-Allow-Credentials'] = true
}
}
if (request.method === 'options') {
// For OPTIONS requests, we can just finish
// as we have created our own implementation of CORS
return finish(200, undefined, undefined)
}
// Change current working directory to the project
// to accommodate for packages using process.cwd()
const projectPath = path.join(__dirname, 'project')
if (process.cwd() !== projectPath) {
try {
process.chdir(projectPath)
} catch (err) {
throw new Error(
`Could not change current working directory to '${projectPath}': ${err}`,
)
}
}
const handler = await handlers.getHandler(
path.join(__dirname, routeConfig.module),
request.method,
)
if (typeof handler !== 'function') {
return finish(405, {
error: 'Method Not Allowed',
message: `${request.method.toUpperCase()} method has not been implemented`,
statusCode: 405,
})
}
const response = await handlers.executeHandler(handler, request)
return finish(response.statusCode, response.payload, response.headers)
} catch (error) {
if (
error &&
error.isBoom &&
error.output &&
error.output.payload &&
error.output.statusCode
) {
if (error.data) {
console.error(error, JSON.stringify(error.data))
} else {
console.error(error)
}
return finish(
error.output.statusCode,
error.output.payload,
error.output.headers,
)
}
console.error(error)
return finish(500, {
error: 'Internal Server Error',
message: 'An internal server error occurred',
statusCode: 500,
})
}
}
export { handler, normaliseLambdaRequest }
/* eslint-enable no-console */
| {
"content_hash": "00323db839c6ac8fea95de08ae45daaa",
"timestamp": "",
"source": "github",
"line_count": 226,
"max_line_length": 83,
"avg_line_length": 28.81858407079646,
"alnum_prop": 0.6275142023645017,
"repo_name": "blinkmobile/cli",
"id": "e5d7d391879ab9f7f3abc4caf4ba4c0e9cb66b4c",
"size": "6513",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/api/scripts/api-handler.ts",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "198745"
}
],
"symlink_target": ""
} |
package com.reason.lang.ocaml;
import com.intellij.psi.*;
import java.util.*;
public class ExpressionsParsingTest extends OclParsingTestCase {
public void testA() {
PsiFile file = parseCode("module Hooks = struct let a = fun (_, info as ei) -> x end\nlet b = 1");
Collection<PsiNamedElement> expressions = expressions(file);
assertEquals(2, expressions.size());
}
public void testB() {
PsiFile file = parseCode("let x = function | _ -> false\nlet y = 1");
Collection<PsiNamedElement> expressions = expressions(file);
assertEquals(2, expressions.size());
}
}
| {
"content_hash": "8ef76cc6b0312dfec4e8d8edc7911229",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 106,
"avg_line_length": 29.904761904761905,
"alnum_prop": 0.6528662420382165,
"repo_name": "giraud/reasonml-idea-plugin",
"id": "39a03872254900e2a1407929dc851621cc865fd9",
"size": "628",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/com/reason/lang/ocaml/ExpressionsParsingTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "155"
},
{
"name": "Java",
"bytes": "1939272"
},
{
"name": "JavaScript",
"bytes": "17286"
},
{
"name": "Lex",
"bytes": "38490"
},
{
"name": "OCaml",
"bytes": "29443"
},
{
"name": "ReScript",
"bytes": "960"
},
{
"name": "Reason",
"bytes": "1592"
},
{
"name": "SCSS",
"bytes": "4798"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.cognitosync.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.cognitosync.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* RecordMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class RecordMarshaller {
private static final MarshallingInfo<String> KEY_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Key").build();
private static final MarshallingInfo<String> VALUE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Value").build();
private static final MarshallingInfo<Long> SYNCCOUNT_BINDING = MarshallingInfo.builder(MarshallingType.LONG).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("SyncCount").build();
private static final MarshallingInfo<java.util.Date> LASTMODIFIEDDATE_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("LastModifiedDate").timestampFormat("unixTimestamp").build();
private static final MarshallingInfo<String> LASTMODIFIEDBY_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("LastModifiedBy").build();
private static final MarshallingInfo<java.util.Date> DEVICELASTMODIFIEDDATE_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DeviceLastModifiedDate").timestampFormat("unixTimestamp").build();
private static final RecordMarshaller instance = new RecordMarshaller();
public static RecordMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(Record record, ProtocolMarshaller protocolMarshaller) {
if (record == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(record.getKey(), KEY_BINDING);
protocolMarshaller.marshall(record.getValue(), VALUE_BINDING);
protocolMarshaller.marshall(record.getSyncCount(), SYNCCOUNT_BINDING);
protocolMarshaller.marshall(record.getLastModifiedDate(), LASTMODIFIEDDATE_BINDING);
protocolMarshaller.marshall(record.getLastModifiedBy(), LASTMODIFIEDBY_BINDING);
protocolMarshaller.marshall(record.getDeviceLastModifiedDate(), DEVICELASTMODIFIEDDATE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| {
"content_hash": "10e4f22f97e1ec44822d652abd72f93d",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 155,
"avg_line_length": 49.69491525423729,
"alnum_prop": 0.7503410641200545,
"repo_name": "aws/aws-sdk-java",
"id": "a6ed98929d01f82d86a0d1714cb0140eabfa5718",
"size": "3512",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-cognitosync/src/main/java/com/amazonaws/services/cognitosync/model/transform/RecordMarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#include <TActionView>
#include <TWebApplication>
#include <TActionController>
#include <THttpUtility>
#include <THtmlAttribute>
#include <TReactComponent>
#include <QDir>
#include <QMutex>
#include <QMutexLocker>
#include "tsystemglobal.h"
/*!
\class TActionView
\brief The TActionView class is the abstract base class of views,
providing functionality common to view.
*/
/*!
Constructor.
*/
TActionView::TActionView()
: QObject(), TViewHelper(), TPrototypeAjaxHelper(), actionController(0), subView(0)
{ }
/*!
Returns a content processed by a action.
*/
QString TActionView::yield() const
{
return (subView) ? subView->toString() : QString();
}
/*!
Render the partial template given by \a templateName without layout.
*/
QString TActionView::renderPartial(const QString &templateName, const QVariantMap &vars) const
{
QString temp = templateName;
if (!temp.contains('/')) {
temp = QLatin1String("partial/") + temp;
}
return (actionController) ? actionController->getRenderingData(temp, vars) : QString();
}
/*!
Renders the React \a component on the server. Calls ReactDOMServer.renderToString()
internally.
*/
QString TActionView::renderReact(const QString &component)
{
QStringList path = { (Tf::app()->publicPath() + "js" + QDir::separator() + "components"),
(Tf::app()->publicPath() + "js")
};
return TReactComponent(component, path).renderToString(component);
}
/*!
Returns a authenticity token for CSRF protection.
*/
QString TActionView::authenticityToken() const
{
return (actionController) ? QString::fromLatin1(actionController->authenticityToken().data()) : QString();
}
/*!
Outputs the string of the HTML attribute \a attr to a view
template.
*/
QString TActionView::echo(const THtmlAttribute &attr)
{
responsebody += attr.toString().trimmed();
return QString();
}
/*!
\fn QString TActionView::echo(const QVariant &var)
Outputs the variant variable \a var to a view template.
*/
QString TActionView::echo(const QVariant &var)
{
if (var.userType() == QMetaType::QUrl) {
responsebody += var.toUrl().toString(QUrl::FullyEncoded);
} else {
responsebody += var.toString();
}
return QString();
}
/*!
Outputs a escaped string of the HTML attribute \a attr to
a view template.
*/
QString TActionView::eh(const THtmlAttribute &attr)
{
return echo(THttpUtility::htmlEscape(attr.toString().trimmed()));
}
/*!
\fn QString TActionView::eh(const QVariant &var)
Outputs a escaped string of the variant variable \a var
to a view template.
*/
QString TActionView::eh(const QVariant &var)
{
if (var.userType() == QMetaType::QUrl) {
return echo(var.toUrl().toString(QUrl::FullyEncoded));
} else {
return echo(THttpUtility::htmlEscape(var.toString()));
}
}
/*!
Returns the requested HTTP message.
*/
const THttpRequest &TActionView::httpRequest() const
{
return controller()->httpRequest();
}
/*!
\fn QString TActionView::echo (const QString &str)
Outputs the string \a str to a view template.
*/
/*!
\fn QString TActionView::echo(const char *str)
Outputs the string \a str to a view template.
*/
/*!
\fn QString TActionView::echo(const QByteArray &str)
Outputs the array \a str to a view template.
*/
/*!
\fn QString TActionView::echo(int n, int base)
Outputs the number \a n to a view template.
*/
/*!
\fn QString TActionView::echo(double d, char format, int precision)
Outputs the number \a d to a view template.
*/
/*!
\fn QString TActionView::eh(const QString &str)
Outputs a escaped string of the \a str to a view template.
*/
/*!
\fn QString TActionView::eh(const char *str)
Outputs a escaped string of the \a str to a view template.
*/
/*!
\fn QString TActionView::eh(const QByteArray &str)
Outputs a escaped array of the \a str to a view template.
*/
/*!
\fn QString TActionView::eh(int n, int base)
Outputs the number \a n to a view template.
*/
/*!
\fn QString TActionView::eh(double d, char format, int precision)
Outputs the number \a d to a view template.
*/
/*!
\fn bool TActionView::hasVariant(const QString &name) const
Returns true if the QVariantMap variable for a view contains
an item with the \a name; otherwise returns false.
*/
/*!
\fn virtual QString TActionView::toString()
This function is reimplemented in subclasses to return a
string to render a view.
*/
/*!
\fn QVariant TActionView::variant(const QString &name) const
Returns the value associated with the \a name in the QVariantMap
variable for a view.
*/
| {
"content_hash": "2020afea373bbaf685a934fb356daf45",
"timestamp": "",
"source": "github",
"line_count": 190,
"max_line_length": 110,
"avg_line_length": 24.236842105263158,
"alnum_prop": 0.6916395222584147,
"repo_name": "hks2002/treefrog-framework",
"id": "b5e493773ac850921285138d705ec4b6724a01b6",
"size": "4817",
"binary": false,
"copies": "1",
"ref": "refs/heads/Composite-Primary-Keys",
"path": "src/tactionview.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "11343"
},
{
"name": "C",
"bytes": "7579"
},
{
"name": "C++",
"bytes": "1058008"
},
{
"name": "HTML",
"bytes": "2876"
},
{
"name": "JavaScript",
"bytes": "493024"
},
{
"name": "QMake",
"bytes": "17735"
},
{
"name": "Shell",
"bytes": "740"
}
],
"symlink_target": ""
} |
@interface QRScanViewController : UIViewController<AVCaptureMetadataOutputObjectsDelegate>
{
int num;
BOOL upOrdown;
NSTimer * timer;
}
@property (strong,nonatomic)AVCaptureDevice * device;
@property (strong,nonatomic)AVCaptureDeviceInput * input;
@property (strong,nonatomic)AVCaptureMetadataOutput * output;
@property (strong,nonatomic)AVCaptureSession * session;
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;
@property (nonatomic, retain) UIImageView * line;
@end
| {
"content_hash": "454c066566f1c94a7da9b6faca630951",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 90,
"avg_line_length": 31.375,
"alnum_prop": 0.796812749003984,
"repo_name": "zlh890318/iOS7Demo",
"id": "6dd55ff5d7bd7c9e75852d93fda3dd7fc6ecbd99",
"size": "719",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "iOS7Sampler/SampleViewControllers/QRScanViewController.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "71109"
}
],
"symlink_target": ""
} |
git node['pentester']['radare2']['install_dir'] do
repository node['pentester']['radare2']['git_repository']
reference node['pentester']['radare2']['git_reference']
end
execute 'sys/install.sh' do
cwd node['pentester']['radare2']['install_dir']
only_if { node['pentester']['radare2']['run_installer'] }
user node['pentester']['user']
group node['pentester']['group']
end
| {
"content_hash": "4511d19dd9a0113a7e6718a531b0a5c8",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 59,
"avg_line_length": 34.90909090909091,
"alnum_prop": 0.6796875,
"repo_name": "sliim-cookbooks/pentester",
"id": "4b05a8b45418cb3ba2e3917ba15f309289e63802",
"size": "971",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "recipes/radare2.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "3035"
},
{
"name": "Ruby",
"bytes": "108035"
},
{
"name": "Shell",
"bytes": "2134"
}
],
"symlink_target": ""
} |
#ifndef SPSPS_XSTRING_H_
#define SPSPS_XSTRING_H_
#include <stddef.h>
#include <wchar.h>
#include <stdbool.h>
/// Opaque type for a string.
typedef struct xstring_ * xstring;
/// Opaque type for a mutable string.
typedef struct mstring_ * mstring;
/**
* A macro to print an xstring to the given stream. The string is
* printed, but no other action is taken. Note that this is a
* statement, not an expression.
* @param m_stream An IO stream, such as stdout.
* @param m_xstring The string to print.
*/
#define XPRINT(m_stream, m_xstring) { \
char * cstring = xstr_cstr(m_xstring); \
fprintf(m_stream, "%s", cstring); \
fflush(m_stream); \
free(cstring); \
}
/**
* A macro to print an mstring to the given stream. The string is
* printed, but no other action is taken. Note that this is a
* statement, not an expression.
* @param m_stream An IO stream, such as stdout.
* @param m_mstring The string to print.
*/
#define MPRINT(m_stream, m_mstring) { \
char * cstring = mstr_cstr(m_mstring); \
fprintf(m_stream, "%s", cstring); \
fflush(m_stream); \
free(cstring); \
}
/// Opaque type for a character. The default is char. To override the
/// default, \#define this prior to inclusion.
#ifdef SPSPS_CHAR
typedef SPSPS_CHAR xchar;
# define TOCHAR(m_ch) ((char) m_ch)
# define SPSPS_CHAR_SIZE sizeof(SPSPS_CHAR)
# define SPSPS_ISCHAR (SPSPS_CHAR_SIZE == sizeof(char))
# undef SPSPS_SIMPLE
#else
typedef char xchar;
# define TOCHAR(m_ch) (m_ch)
# define SPSPS_CHAR_SIZE sizeof(char)
# define SPSPS_ISCHAR true
# define SPSPS_SIMPLE
#endif
/// Incremental size to use for mutable string. To override this \#define
/// it prior to inclusion.
#ifndef MSTR_INC
# define MSTR_INC 64
#endif
#ifdef MSTRING_DEBUG
/**
* Inspect a mstring's internal data. This is of no use other
* than for debugging, and you must therefore set the MSTRING_DEBUG
* flag to see the definition.
* @param str The mstring.
*/
void mstr_inspect(mstring str);
#endif
/**
* Make a new empty and immutable string. You should never need to
* use this, since NULL is a perfectly valid string, and the system
* will defer allocation until needed.
* @return The new empty string.
*/
xstring xstr_new();
/**
* Make a new empty mutable string. If the capacity is zero, then
* a default capacity (MSTR_INC) is used. O(1).
* @param capacity The initial capacity of the string.
* @return The new mutable string.
*/
mstring mstr_new(size_t capacity);
/**
* Free a string. Be sure to call this method instead of simply
* calling free on an xstring instance; the latter will cause a
* memory leak. O(1).
* @param value The value to free.
*/
void xstr_free(xstring value);
/**
* Free a mutable string. Be sure to call this method instead of
* calling free on a mstring instance; the latter will cause a
* memory leak. O(C*len(value)) because all blocks of the string
* must be deallocated.
* @param value The value to free.
*/
void mstr_free(mstring value);
/**
* Convert a C null-terminated string into an xstring. The input
* C string is converted to the proper characters and is not needed
* subsequent to this call. The caller should deallocate it.
* O(len(value)) because each character must be converted and copied.
* @param value The null-terminate C string.
* @return The new immutable string.
*/
xstring xstr_wrap(char * value);
/**
* Convert a C null-terminated string into an xstring. The input
* C string is converted to the proper characters and is not needed
* subsequent to this call, and is explicitly deallocated.
* O(len(value)) because each character must be converted and copied.
* @param value The null-terminate C string.
* @return The new immutable string.
*/
xstring xstr_wrap_f(char * value);
/**
* Convert a C null-terminated string into an mstring. The input
* C string is converted to the proper characters and is not needed
* subsequent to this call. The caller should deallocate it.
* O(len(value)) because each character must be converted and copied.
* @param value The null-terminated C string.
* @return The new mutable string.
*/
mstring mstr_wrap(char * value);
/**
* Convert a C null-terminated string into an mstring. The input
* C string is converted to the proper characters and is not needed
* subsequent to this call, and is explicitly deallocated.
* O(len(value)) because each character must be converted and copied.
* @param value The null-terminated C string.
* @return The new mutable string.
*/
mstring mstr_wrap_f(char * value);
/**
* Convert a C null-terminated string into an xstring. The input
* C string is converted to the proper characters and is not needed
* subsequent to this call. The caller should deallocate it.
* O(len(value)) because each character must be converted and copied.
* @param value The null-terminate C string.
* @return The new immutable string.
*/
xstring xstr_wwrap(wchar_t * value);
/**
* Convert a C null-terminated string into an xstring. The input
* C string is converted to the proper characters and is not needed
* subsequent to this call, and is explicitly deallocated.
* O(len(value)) because each character must be converted and copied.
* @param value The null-terminate C string.
* @return The new immutable string.
*/
xstring xstr_wwrap_f(wchar_t * value);
/**
* Convert a C null-terminated string into an mstring. The input
* C string is converted to the proper characters and is not needed
* subsequent to this call. The caller should deallocate it.
* O(len(value)) because each character must be converted and copied.
* @param value The null-terminated C string.
* @return The new mutable string.
*/
mstring mstr_wwrap(wchar_t * value);
/**
* Convert a C null-terminated string into an mstring. The input
* C string is converted to the proper characters and is not needed
* subsequent to this call, and is explicitly deallocated.
* O(len(value)) because each character must be converted and copied.
* @param value The null-terminated C string.
* @return The new mutable string.
*/
mstring mstr_wwrap_f(wchar_t * value);
/**
* Create a copy of the string. The resulting copy is independent
* of the original. The main purpose for this is to allow copies
* to be passed around, with the recipient assuming responsibility
* for deallocating its instance. O(len(other)) using memcopy.
* @param other The string to copy.
* @return The new copy.
*/
xstring xstr_copy(xstring other);
/**
* Create a copy of the string. The resulting copy is independent
* of the original. The main purpose for this is to allow modification
* of the original and the copy independently. Note that the new copy
* may be more efficient than the original. O(len(other)) because each
* block must be memcopy'd.
* @param other The string to copy.
* @return The new copy.
*/
mstring mstr_copy(mstring other);
/**
* Convert a mutable string to an immutable string. O(len(other)).
* @param other The mutable string.
* @return The immutable string.
*/
xstring mstr_to_xstr(mstring other);
/**
* Convert an immutable string to a mutable string. O(len(other)).
* @param other The immutable string.
* @return The mutable string.
*/
mstring xstr_to_mstr(xstring other);
/**
* Obtain the length of the string, in characters. O(1).
* @param value The string.
* @return The number of characters in the string.
*/
size_t xstr_length(xstring value);
/**
* Obtain the length of the string, in characters. O(1).
* @param value The string.
* @return The number of charactesr in the string.
*/
size_t mstr_length(mstring value);
/**
* Append a character to the end of the string. A new string is
* created (since xstrings are immutable) and returned. As such,
* this is not a particularly efficient way to build up a string.
* O(len(value)) because of memcopy.
* @param value The string.
* @param ch The character to add.
* @return The new string.
*/
xstring xstr_append(xstring value, xchar ch);
/**
* Append a character to the end of the string. This modifies the
* string in place and - if the string has excess capacity - does
* not perform any allocation. The input string is returned. This
* is the primary use for the mstring. O(C*len(value)) because the
* last block must be located.
* @param value The string.
* @param ch The character to add.
* @return The string.
*/
mstring mstr_append(mstring value, xchar ch);
/**
* Append a character to the end of the string. A new string is
* created (since xstrings are immutable) and returned. As such,
* this is not a particularly efficient way to build up a string.
* The input string is explicitly deallocated. O(len(value)) because
* of memcopy.
* @param value The string.
* @param ch The character to add.
* @return The new string.
*/
xstring xstr_append_f(xstring value, xchar ch);
/**
* Append a C string to the end of the given xstring. The
* C string is not stored by this action, and can be deallocated
* by the caller. The input string not modified; a new string is
* returned. O(len(value)+len(cstr)).
* @param value The string.
* @param cstr The string to append.
* @return The input string, modified.
*/
xstring xstr_append_cstr(xstring value, char * cstr);
/**
* Append a C string to the end of the given xstring. The
* C string is automatically deallocated by this function, as is
* the input xstring. A new xstring is allocated and returned.
* Because the input C string is deallocated, you should not use
* string literals. O(len(value)+len(cstr)).
* @param value The string.
* @param cstr The string to append.
* @return The input string, modified.
*/
xstring xstr_append_cstr_f(xstring value, char * cstr);
/**
* Append a C string to the end of the given mstring. The
* C string is not stored by this action, and can be deallocated
* by the caller. The input string is modified and returned.
* O(C*len(value)+len(cstr)) because the last block must be found
* and the C string converted and copied.
* @param value The string.
* @param cstr The string to append.
* @return The input string, modified.
*/
mstring mstr_append_cstr(mstring value, char * cstr);
/**
* Append a C string to the end of the given mstring. The
* C string is automatically deallocated by this function.
* The input string is modified and returned. Because the C string
* is deallocated, you should not use string literals.
* O(C*len(value)+len(cstr)) because the last block must be found and
* the C string converted and copied.
* @param value The string.
* @param cstr The string to append.
* @return The input string, modified.
*/
mstring mstr_append_cstr_f(mstring value, char * cstr);
/**
* Concatenate two strings. The second string is appended to the
* end of the first string, creating a new string. The input
* strings are not modified, since the are immutable.
* O(len(first)+len(second)).
* @param first The first string.
* @param second The second string.
* @return The new string.
*/
xstring xstr_concat(xstring first, xstring second);
/**
* Concatenate two strings. The second string is appended to the
* end of the first string, which is modified in-place. The two
* strings are used as-is by this operation, and should not be
* deallocated! No memory allocation is performed by this method.
* O(C*len(first)) because only the last block of the first string
* need be located.
* @param first The first string.
* @param second The second string.
* @return The first string, with the second appended.
*/
mstring mstr_concat(mstring first, mstring second);
/**
* Concatenate two strings. The second string is appended to the
* end of the first string, creating a new string. The input strings
* are explicitly deallocated. O(len(first)+len(second)).
* @param first The first string.
* @param second The second string.
* @return The new string.
*/
xstring xstr_concat_f(xstring first, xstring second);
/**
* Obtain a character from the given string. If the index is out
* of range of the string, then the null character is returned (0).
* O(1).
* @param value The string.
* @param index The zero-based index of the character.
* @return The requested character.
*/
xchar xstr_char(xstring value, size_t index);
/**
* Obtain a character from the given string. If the index is out
* of range of the string, then the null character is returned (0).
* O(C*len(index)) because the block list must be traversed.
* @param value The string.
* @param index The zero-based index of the character.
* @return The requested character.
*/
xchar mstr_char(mstring value, size_t index);
/**
* Extract a substring from the given string. The substring can
* be empty. If the start position is out of the string's range,
* or the number of characters is too large, or both, then the
* returned string is padded with null characters (0). O(num).
* @param value The string.
* @param start The zero-based index of the first character.
* @param num The number of characters to extract.
* @return The requested substring.
*/
xstring xstr_substr(xstring value, size_t start, size_t num);
/**
* Extract a substring from the given string. The substring can
* be empty. If the start position is out of the string's range,
* or the number of characters is too large, or both, then the
* returned string is padded with null characters (0).
* O(C*start+num) because the block index must be
* traversed.
* @param value The string.
* @param start The zero-based index of the first character.
* @param num The number of characters to extract.
* @return The requested substring.
*/
mstring mstr_substr(mstring value, size_t start, size_t num);
/**
* Extract a substring from the given string. The substring can
* be empty. If the start position is out of the string's range,
* or the number of characters is too large, or both, then the
* returned string is padded with null characters (0). The input
* string is explicitly deallocated. O(num).
* @param value The string.
* @param start The zero-based index of the first character.
* @param num The number of characters to extract.
* @return The requested substring.
*/
xstring xstr_substr_f(xstring value, size_t start, size_t num);
/**
* Extract a substring from the given string. The substring can
* be empty. If the start position is out of the string's range,
* or the number of characters is too large, or both, then the
* returned string is padded with null characters (0). The input
* string is explicitly deallocated. O(C*start+num).
* @param value The string.
* @param start The zero-based index of the first character.
* @param num The number of characters to extract.
* @return The requested substring.
*/
mstring mstr_substr_f(mstring value, size_t start, size_t num);
/**
* Compare two strings. The return value is the standard C
* comparison. The value is negative iff lhs is less than
* rhs. The value is zero iff they are equal. The value is
* positive iff lhs is greater than rhs. The comparison is
* done lexicographically. O(max(len(lhs),len(rhs))).
* @param lhs The first string.
* @param rhs The second string.
* @return The comparison result.
*/
int xstr_strcmp(xstring lhs, xstring rhs);
/**
* Compare two strings. The return value is the standard C
* comparison. The value is negative iff lhs is less than
* rhs. The value is zero iff they are equal. The value is
* positive iff lhs is greater than rhs. The comparison is
* done lexicographically. O(C*max(len(lhs),len(rhs))).
* @param lhs The first string.
* @param rhs The second string.
* @return The comparison result.
*/
int mstr_strcmp(mstring lhs, mstring rhs);
/**
* Convert a string into a C null-terminated character array and
* return it. The caller is responsible for freeing the returned
* string. O(len(value)).
* @param value The string.
* @return The null-terminated array of chars.
*/
char * xstr_cstr(xstring value);
/**
* Convert a string into a C null-terminated character array and
* return it. The caller is responsible for freeing the returned
* string. The input string is explicitly deallocated. O(len(value)).
* @param value The string.
* @return The null-terminated array of chars.
*/
char * xstr_cstr_f(xstring value);
/**
* Convert a string into a C null-terminated character array and
* return it. The caller is responsible for freeing the returned
* string. O(len(value)).
* @param value The string.
* @return The null-terminated array of chars.
*/
char * mstr_cstr(mstring value);
/**
* Convert a string into a C null-terminated character array and
* return it. The caller is responsible for freeing the returned
* string. The input string is explicitly deallocated. O(len(value)).
* @param value The string.
* @return The null-terminated array of chars.
*/
char * mstr_cstr_f(mstring value);
/**
* Convert a string into a C null-terminated wide character array.
* O(len(value)).
* @param value The string.
* @return The null-terminated array of wide characters.
*/
wchar_t * xstr_wcstr(xstring value);
/**
* Convert a string into a C null-terminated wide character array.
* The input string is explicitly deallocated. O(len(value)).
* @param value The string.
* @return The null-terminated array of wide characters.
*/
wchar_t * xstr_wcstr_f(xstring value);
/**
* Convert a string into a C null-terminated wide character array and
* return it. The caller is responsible for freeing the returned
* string. O(len(value)).
* @param value The string.
* @return The null-terminated array of wide chars.
*/
wchar_t * mstr_wcstr(mstring value);
/**
* Convert a string into a C null-terminated wide character array and
* return it. The caller is responsible for freeing the returned
* string. The input string is explicitly deallocated. O(len(value)).
* @param value The string.
* @return The null-terminated array of wide chars.
*/
wchar_t * mstr_wcstr_f(mstring value);
#endif /* SPSPS_XSTRING_H_ */
| {
"content_hash": "8b1481494e36d014c6b4251a613362fb",
"timestamp": "",
"source": "github",
"line_count": 522,
"max_line_length": 74,
"avg_line_length": 35.111111111111114,
"alnum_prop": 0.7064600611086862,
"repo_name": "sprowell/spsps",
"id": "14178e8ba94bc72c208e0c2c2023cb28a442b874",
"size": "19892",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/xstring.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "83810"
},
{
"name": "C++",
"bytes": "26806"
},
{
"name": "CMake",
"bytes": "2967"
}
],
"symlink_target": ""
} |
using namespace System;
//Type Boolean::MyType = { (__typeCtor)null, L"bool", (__typeBoxer)&Boolean::_box, (__typeUnboxer)&Boolean::_unbox, (char*)default(bool) };
//
//// boxing/unboxing
//Object *BooleanType::_box(bool value)
//{
// Boolean *box = null; //gcnew Boolean();
// box->_value = value;
// return (Object *)box;
//}
//
//bool BooleanType::_unbox(Object *value)
//{
// return ((Boolean*)value)->_value;
//}
| {
"content_hash": "30945d5305afa6334e507f0176c5d0d4",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 139,
"avg_line_length": 27.1875,
"alnum_prop": 0.6022988505747127,
"repo_name": "BclEx/GpuStructs",
"id": "640f61b39b07ec3dd716cb1919338c69828c7168",
"size": "459",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Thunk/Thunk.cpu/System.1/Boolean.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Bison",
"bytes": "45727"
},
{
"name": "C",
"bytes": "3784724"
},
{
"name": "C#",
"bytes": "5110307"
},
{
"name": "C++",
"bytes": "970081"
},
{
"name": "Cuda",
"bytes": "9043036"
},
{
"name": "Objective-C",
"bytes": "2166"
},
{
"name": "PowerShell",
"bytes": "31854"
},
{
"name": "Shell",
"bytes": "73"
}
],
"symlink_target": ""
} |
module Backburner
# A single backburner job which can be processed and removed by the worker
class Job < SimpleDelegator
include Backburner::Helpers
# Raises when a job times out
class JobTimeout < RuntimeError; end
class JobNotFound < RuntimeError; end
class JobFormatInvalid < RuntimeError; end
attr_accessor :task, :body, :name, :args
# Construct a job to be parsed and processed
#
# task is a reserved object containing the json body in the form of
# { :class => "NewsletterSender", :args => ["foo@bar.com"] }
#
# @example
# Backburner::Job.new(payload)
#
def initialize(task)
@task = task
@body = task.body.is_a?(Hash) ? task.body : JSON.parse(task.body)
@name, @args = body["class"], body["args"]
@hooks = Backburner::Hooks
rescue => ex # Job was not valid format
self.bury
raise JobFormatInvalid, "Job body could not be parsed: #{ex.inspect}"
end
# Sets the delegator object to the underlying beaneater job
# self.bury
def __getobj__
__setobj__(@task)
super
end
# Processes a job and handles any failure, deleting the job once complete
#
# @example
# @task.process
#
def process
# Invoke before hook and stop if false
res = @hooks.invoke_hook_events(job_class, :before_perform, *args)
return false unless res
# Execute the job
@hooks.around_hook_events(job_class, :around_perform, *args) do
timeout_job_after(task.ttr - 1) { job_class.perform(*args) }
end
task.delete
# Invoke after perform hook
@hooks.invoke_hook_events(job_class, :after_perform, *args)
rescue => e
@hooks.invoke_hook_events(job_class, :on_failure, e, *args)
raise e
end
protected
# Returns the class for the job handler
#
# @example
# job_class # => NewsletterSender
#
def job_class
handler = constantize(self.name) rescue nil
raise(JobNotFound, self.name) unless handler
handler
end
# Timeout job within specified block after given time.
#
# @example
# timeout_job_after(3) { do_something! }
#
def timeout_job_after(secs, &block)
begin
Timeout::timeout(secs) { yield }
rescue Timeout::Error => e
raise JobTimeout, "#{name} hit #{secs}s timeout.\nbacktrace: #{e.backtrace}"
end
end
end # Job
end # Backburner
| {
"content_hash": "4c94ad6287c078fd32fc3a8b42f884e3",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 84,
"avg_line_length": 28.6046511627907,
"alnum_prop": 0.6239837398373984,
"repo_name": "hammeraj/backburner",
"id": "99c2ee8bb6f18a129e0c352f83023de0586014bc",
"size": "2460",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/backburner/job.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "114283"
}
],
"symlink_target": ""
} |
var React = require('react')
var PropTypes = React.PropTypes
var styles = require('../styles')
var Link = require('react-router').Link
var UserDetailsWrapper = require('./UserDetailsWrapper')
var UserDetails = require('./UserDetails')
var MainContainer = require('./MainContainer')
var Loading = require('./Loading')
function StartOver () {
return (
<div className='col-sm-12' style={styles.space}>
<Link to='/playerOne'>
<button type='button' className='btn btn-lg btn-danger'>Start Over</button>
</Link>
</div>
)
}
function Tie (props) {
return (
<MainContainer>
<h1>It's a Tie!</h1>
<StartOver />
</MainContainer>
)
}
function Results (props) {
if (props.isLoading === true) {
return <Loading text='One Moment' speed={100} />
}
if (props.scores[0] === props.scores[1]) {
return (
<Tie scores={props.scores} playersInfo={props.playersInfo} />
)
}
// Assigning winner and loser
var winningIndex = props.scores[0] > props.scores[1] ? 0 : 1
var losingIndex = winningIndex === 0 ? 1 : 0
return (
<MainContainer>
<div className='col-sm-8 col-sm-offset-2'>
<UserDetailsWrapper header='Winner'>
<UserDetails score={props.scores[winningIndex]} info={props.playersInfo[winningIndex]} />
</UserDetailsWrapper>
<UserDetailsWrapper header='Loser'>
<UserDetails score={props.scores[losingIndex]} info={props.playersInfo[losingIndex]} />
</UserDetailsWrapper>
</div>
<StartOver />
</MainContainer>
)
}
Results.propTypes = {
isLoading: PropTypes.bool.isRequired,
playersInfo: PropTypes.array.isRequired,
scores: PropTypes.array.isRequired
}
module.exports = Results
| {
"content_hash": "b29498da72d42064a1f93ca626f69fc9",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 99,
"avg_line_length": 26.333333333333332,
"alnum_prop": 0.6490218642117376,
"repo_name": "baronkwan/github-battle",
"id": "ddd1a747b500b3731acbd09d90444eb24c9b0fd8",
"size": "1738",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/components/Results.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "219"
},
{
"name": "HTML",
"bytes": "252"
},
{
"name": "JavaScript",
"bytes": "15706"
}
],
"symlink_target": ""
} |
using OxyEngine.Events.Args;
using OxyEngine.Interfaces;
namespace OxyEngine.Events
{
public class GlobalEventsManager : IModule
{
#region Global game events
// Public because used by scripting
public readonly EventSystem Global;
#endregion
public GlobalEventsManager()
{
Global = new EventSystem();
}
#region Fabrics
/// <summary>
/// Return new event system
/// </summary>
/// <returns>New event system</returns>
public EventSystem NewEventSystem()
{
return new EventSystem();
}
#endregion
#region Global invokers
internal void Init()
{
Global.Invoke(EventNames.Initialization.OnInit, null);
}
internal void Load()
{
Global.Invoke(EventNames.Initialization.OnLoad, null);
}
internal void Unload()
{
Global.Invoke(EventNames.Initialization.OnUnload, null);
}
internal void BeginUpdate()
{
Global.Invoke(EventNames.Gameloop.Update.OnBeginUpdate, null);
}
internal void Update(double dt)
{
Global.Invoke(EventNames.Gameloop.Update.OnUpdate, new EngineUpdateEventArgs { DeltaTime = dt });
}
internal void EndUpdate()
{
Global.Invoke(EventNames.Gameloop.Update.OnEndUpdate, null);
}
internal void BeginDraw()
{
Global.Invoke(EventNames.Gameloop.Draw.OnBeginDraw, null);
}
internal void Draw()
{
Global.Invoke(EventNames.Gameloop.Draw.OnDraw, null);
}
internal void EndDraw()
{
Global.Invoke(EventNames.Gameloop.Draw.OnEndDraw, null);
}
internal void Resize()
{
Global.Invoke(EventNames.Window.OnResize, null);
}
#endregion
}
} | {
"content_hash": "9196f1121e7f3780d5302407c018741c",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 103,
"avg_line_length": 20.2183908045977,
"alnum_prop": 0.6281978396816373,
"repo_name": "OxyTeam/OxyEngine",
"id": "f1e69e287db53249ab66eec65679a0a4f4d26010",
"size": "1761",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/OxyEngine/Events/GlobalEventsManager.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "128159"
}
],
"symlink_target": ""
} |
<?php
class sfRedisDateTimeField extends sfRedisField
{
const TZ_REDIS = 'UTC';
public $name = null;
public $type = 'datetime';
public $format;
public static function createFromAnnotation($name, RedisField $annotation) {
$field = new sfRedisDateTimeField($name);
$field->type = $annotation->type;
switch($field->type) {
case 'date': $field->format = 'Y-m-d H:i:s'; break;
case 'datetime': $field->format = 'Y-m-d H:i:s'; break;
case 'timestamp': $field->format = 'U'; break;
}
return $field;
}
public function fromRedis($value) {
$dt = new DateTime($value, new DateTimeZone(self::TZ_REDIS));
$dt->setTimezone( new DateTimeZone(date_default_timezone_get()) );
return $dt->format($this->format);
}
public function toRedis($value) {
$dt = new DateTime($value, new DateTimeZone(date_default_timezone_get()));
if($field->type == 'date')
$dt->setTime(0, 0, 0);
$dt->setTimezone( new DateTimeZone(self::TZ_REDIS) );
return $dt->format($this->format);
}
} | {
"content_hash": "db19fb943160e28d822382b1ed5d4b33",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 82,
"avg_line_length": 28.25,
"alnum_prop": 0.5325824617860017,
"repo_name": "scraton/sfRedisPlugin",
"id": "56ac714e0e3148b19077bb3fd3622c6a125edcf0",
"size": "1243",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/fields/sfRedisDateTimeField.class.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "192019"
}
],
"symlink_target": ""
} |
module AuthlogicCrowdRest
module ActsAsAuthentic
def self.included(klass)
klass.class_eval do
extend Config
add_acts_as_authentic_module(Methods, :prepend)
end
end
module Config
# Whether or not to validate the crowd_login field. If set to false ALL crowd validation will need to be
# handled by you.
#
# * <tt>Default:</tt> true
# * <tt>Accepts:</tt> Boolean
def validate_crowd_login(value = nil)
rw_config(:validate_crowd_login, value, true)
end
alias_method :validate_crowd_login=, :validate_crowd_login
end
module Methods
# Set up some simple validations
def self.included(klass)
return if !klass.column_names.include?("crowd_login")
klass.class_eval do
attr_accessor :crowd_password
if validate_crowd_login
validates_uniqueness_of :crowd_login, :scope => validations_scope, :if => :using_crowd?
validate :validate_crowd
validates_length_of_password_field_options validates_length_of_password_field_options.merge(:if => :validate_password_with_crowd?)
validates_confirmation_of_password_field_options validates_confirmation_of_password_field_options.merge(:if => :validate_password_with_crowd?)
validates_length_of_password_confirmation_field_options validates_length_of_password_confirmation_field_options.merge(:if => :validate_password_with_crowd?)
end
end
end
# Set the crowd_login field and also resets the persistence_token if this value changes.
def crowd_login=(value)
write_attribute(:crowd_login, value.blank? ? nil : value)
reset_persistence_token if crowd_login_changed?
end
def save(perform_validation = true, &block)
return false if perform_validation && block_given? && authenticate_with_crowd? && !authenticate_with_crowd
return false if new_record? && !crowd_complete?
result = super
yield(result) if block_given?
result
end
private
def using_crowd?
respond_to?(:crowd_login) && !crowd_login.blank?
end
def authenticate_with_crowd
@crowd_error = nil
if !crowd_complete?
session_class.controller.session[:crowd_attributes] = attributes_to_save
else
map_saved_attributes(session_class.controller.session[:crowd_attributes])
session_class.controller.session[:crowd_attributes] = nil
end
options = {}
options[:required] = self.class.openid_required_fields
options[:optional] = self.class.openid_optional_fields
options[:return_to] = session_class.controller.url_for(:for_model => "1",:controller=>"users",:action=>"create")
session_class.controller.send(:authenticate_with_open_id, openid_identifier, options) do |result, openid_identifier, registration|
if result.unsuccessful?
@openid_error = result.message
else
self.openid_identifier = openid_identifier
map_openid_registration(registration)
end
return true
end
return false
end
# Override this method to map the OpenID registration fields with fields in your model. See the required_fields and
# optional_fields configuration options to enable this feature.
#
# Basically you will get a hash of values passed as a single argument. Then just map them as you see fit. Check out
# the source of this method for an example.
def map_openid_registration(registration) # :doc:
registration.symbolize_keys!
[self.class.openid_required_fields+self.class.openid_optional_fields].flatten.each do |field|
setter="#{field.to_s}=".to_sym
if respond_to?(setter)
send setter,registration[field]
end
end
end
# This method works in conjunction with map_saved_attributes.
#
# Let's say a user fills out a registration form, provides an OpenID and submits the form. They are then redirected to their
# OpenID provider. All is good and they are redirected back. All of those fields they spent time filling out are forgetten
# and they have to retype them all. To avoid this, AuthlogicOpenid saves all of these attributes in the session and then
# attempts to restore them. See the source for what attributes it saves. If you need to block more attributes, or save
# more just override this method and do whatever you want.
def attributes_to_save # :doc:
attrs_to_save = attributes.clone.delete_if do |k, v|
[:id, :password, crypted_password_field, password_salt_field, :persistence_token, :perishable_token, :single_access_token, :login_count,
:failed_login_count, :last_request_at, :current_login_at, :last_login_at, :current_login_ip, :last_login_ip, :created_at,
:updated_at, :lock_version].include?(k.to_sym)
end
attrs_to_save.merge!(:password => password, :password_confirmation => password_confirmation)
end
# This method works in conjunction with attributes_to_save. See that method for a description of the why these methods exist.
#
# If the default behavior of this method is not sufficient for you because you have attr_protected or attr_accessible then
# override this method and set them individually. Maybe something like this would be good:
#
# attrs.each do |key, value|
# send("#{key}=", value)
# end
def map_saved_attributes(attrs) # :doc:
self.attributes = attrs
end
def validate_openid
errors.add(:openid_identifier, "had the following error: #{@openid_error}") if @openid_error
end
def using_openid?
respond_to?(:openid_identifier) && !openid_identifier.blank?
end
def openid_complete?
session_class.controller.params[:open_id_complete] && session_class.controller.params[:for_model]
end
def authenticate_with_openid?
session_class.activated? && ((using_openid? && openid_identifier_changed?) || openid_complete?)
end
def validate_password_with_openid?
!using_openid? && require_password?
end
end
end
end
| {
"content_hash": "ee932d37bdccf5284d8b5bc62041a78b",
"timestamp": "",
"source": "github",
"line_count": 149,
"max_line_length": 168,
"avg_line_length": 43.7248322147651,
"alnum_prop": 0.6417498081350729,
"repo_name": "robdimarco/authlogic_crowd_rest",
"id": "59c582b86fa9f95004fb180f20177d597aba292e",
"size": "6684",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/authlogic_crowd_rest/acts_as_authentic.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "21349"
}
],
"symlink_target": ""
} |
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.activiti.web.rest.client;
import com.activiti.domain.ServerConfig;
import com.activiti.repository.ServerConfigRepository;
import com.activiti.service.activiti.AppVersionClientService;
import com.activiti.service.activiti.EndpointUserProfileService;
import com.activiti.web.rest.exception.BadRequestException;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class AbstractClientResource {
private static final String SERVER_ID = "serverId";
@Autowired
protected ServerConfigRepository configRepository;
@Autowired
protected AppVersionClientService appVersionClientService;
@Autowired
protected EndpointUserProfileService endpointUserProfileService;
@Autowired
protected Environment env;
protected ServerConfig retrieveServerConfig() {
List<ServerConfig> serverConfigs = configRepository.findAll();
if (serverConfigs == null) {
throw new BadRequestException("No server config found");
}
if (serverConfigs.size() > 1) {
throw new BadRequestException("Only one server config allowed");
}
return serverConfigs.get(0);
}
protected Map<String, String[]> getRequestParametersWithoutServerId(HttpServletRequest request) {
Map<String, String[]> parameterMap = request.getParameterMap();
Map<String, String[]> resultMap = new HashMap<String, String[]>();
resultMap.putAll(parameterMap);
resultMap.remove(SERVER_ID);
return resultMap;
}
}
| {
"content_hash": "6ad84c71205afd8a31ebcd19e23ca662",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 98,
"avg_line_length": 33.642857142857146,
"alnum_prop": 0.7715498938428875,
"repo_name": "wellisonraul/ProjetoDoutorado",
"id": "ef2e8bd5d199a71ceb39ce908096524612119873",
"size": "2355",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Activiti-master/modules/activiti-admin/src/main/java/com/activiti/web/rest/client/AbstractClientResource.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "31537"
},
{
"name": "CSS",
"bytes": "403900"
},
{
"name": "HTML",
"bytes": "5657412"
},
{
"name": "Java",
"bytes": "24023806"
},
{
"name": "JavaScript",
"bytes": "9167995"
},
{
"name": "PLSQL",
"bytes": "1426"
},
{
"name": "PLpgSQL",
"bytes": "4868"
},
{
"name": "Shell",
"bytes": "56143"
},
{
"name": "XSLT",
"bytes": "4723"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PublishR.Exceptions
{
public class ForbiddenException : Exception
{
}
}
| {
"content_hash": "fb1f4ed3b54eef6c84e184ea35027dc3",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 47,
"avg_line_length": 16.384615384615383,
"alnum_prop": 0.7511737089201878,
"repo_name": "clusta/publishr",
"id": "9deb70c0a0745087954ca5e5bf96532d3b7fac2a",
"size": "215",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PublishR/Exceptions/ForbiddenException.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "224"
},
{
"name": "C#",
"bytes": "168487"
},
{
"name": "JavaScript",
"bytes": "178013"
},
{
"name": "TypeScript",
"bytes": "53228"
}
],
"symlink_target": ""
} |
title: Styling Text
module: topic-08
permalink: /topic-08/basic-styling-text/
---
<div class="divider-heading"></div>
At this stage, you should use element selectors to “point” to structural text elements, like `h1`, `p`, or lists. This will style all elements of that type cohesively.
## Coloring Text
Backgrounds are not the only element that can hold a color value. Likewise, you can color text using the **color property**. Again, <a href="https://www.w3schools.com/cssref/css_colors.asp" target="_blank">color names</a> are a great way state color values at this stage.
<div class="code-heading">
<span class="html">HTML</span>
</div>
```html
* {
color: ;
}
```
## Centering Text
Additionally, you can align text using **text-align property**. By default, browsers align text to the left of the screen; to center text on the page, simply add "center" to the property.
<div class="code-heading">
<span class="html">HTML</span>
</div>
```html
* {
text-align: center;
}
```
<div class="divider-pg"></div>
### Example
See how you can creatively style text using **color** and **text-align: center**!
<div class="external-embed">
<p data-height="600" data-theme-id="30567" data-slug-hash="PRzKed" data-default-tab="html,result" data-user="Media-Ed-Online" data-pen-title="Basic HTML Text Styling" class="codepen"></p>
</div>
| {
"content_hash": "831ef69dd0c0a308ab1f0571a3870d42",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 271,
"avg_line_length": 29.32608695652174,
"alnum_prop": 0.7049666419570052,
"repo_name": "Media-Ed-Online/intro-web-dev",
"id": "f440eb3a03f1c2c1e9a19bcea912d3c5ae92e690",
"size": "1357",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "_docs/topic-08/02-intro-style/page-05.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1107"
},
{
"name": "Dockerfile",
"bytes": "684"
},
{
"name": "HTML",
"bytes": "38850"
},
{
"name": "JavaScript",
"bytes": "1051"
},
{
"name": "Ruby",
"bytes": "492"
},
{
"name": "SCSS",
"bytes": "673520"
}
],
"symlink_target": ""
} |
package leap.spring.boot.web;
import leap.lang.Out;
import leap.lang.intercepting.State;
import leap.web.Response;
import leap.web.Result;
import leap.web.action.ActionContext;
import leap.web.action.FormattingResultInterceptor;
import org.springframework.http.ResponseEntity;
public class LeapFormattingResultInterceptor implements FormattingResultInterceptor {
@Override
public State preProcessReturnValue(ActionContext context, Result result, Out<Object> returnValue) throws Throwable {
Object v = returnValue.get();
if(v instanceof ResponseEntity) {
ResponseEntity re = (ResponseEntity)v;
result.setStatus(re.getStatusCodeValue());
Response response = context.getResponse();
re.getHeaders().forEach((name,values) -> {
for(String value : values) {
response.addHeader(name, value);
}
});
Object body = re.getBody();
if(null == body) {
return State.INTERCEPTED;
}else {
returnValue.set(body);
}
}
return State.CONTINUE;
}
}
| {
"content_hash": "12aba454f3ab07c5a5aa80c1613a97dc",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 120,
"avg_line_length": 28.5609756097561,
"alnum_prop": 0.6259607173356105,
"repo_name": "leapframework/framework",
"id": "0529038ec5252f560f4a6b22640f74a48487f79b",
"size": "1790",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "spring/spring-boot-web/src/main/java/leap/spring/boot/web/LeapFormattingResultInterceptor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "355"
},
{
"name": "HTML",
"bytes": "645766"
},
{
"name": "Java",
"bytes": "13020209"
},
{
"name": "JavaScript",
"bytes": "167"
},
{
"name": "PLSQL",
"bytes": "30834"
},
{
"name": "Shell",
"bytes": "66"
}
],
"symlink_target": ""
} |
'use strict';
var fs = require('fs'),
path = require('path'),
npm = require('npm'),
shell = require('shelljs'),
chalk = require('chalk'),
request = require('request'),
querystring = require('querystring'),
cliVersion = require('../package').version,
ProgressBar = require('progress'),
prompt = require('prompt');
/* Breaking functionality into submodules */
var utils = require('./utils'),
install = require('./install');
var pkgType = {
contrib: 'Contrib',
custom: 'Custom',
core: 'Core'
};
// From express
function emptyDirectory(path, callback) {
fs.readdir('./' + path, function(err, files) {
if (err && 'ENOENT' !== err.code) throw new Error(err);
callback(!files || !files.length);
});
}
function ensureEmpty(path, force, callback) {
emptyDirectory(path, function(empty) {
if (empty || force) {
callback();
} else {
console.log(chalk.yellow('Destination is not empty:'), path);
}
});
}
function getPackageInfo(type, data) {
if (!data) return;
var author = data.author ? chalk.green(' Author: ') + data.author.name : '';
if (type === pkgType.custom && data.author.name === 'Linnovate') type = pkgType.core;
return chalk.green(' ' + type + ': ') + data.name + '@' + data.version + author;
}
function checkVersion() {
console.log();
console.log(' checking meanio and global mean-cli versions');
var meanioVersion, latest;
utils.loadPackageJson(process.cwd() + '/node_modules/meanio/package.json', function(err, data) {
if (err) return console.log(chalk.yellow('Invalid MEAN app or not in app root'));
meanioVersion = data.version;
});
npm.load({
loglevel: 'warn'
}, function(err, npm) {
npm.commands.outdated('meanio', true, function(err, list) {
if (err) {
console.log(chalk.red('Error: npm outdated failed'));
return console.error(err);
}
latest = list[0] ? list[0][3] : meanioVersion; // list[0][3] holds the 'latest' value
if (latest < meanioVersion) {
console.log(chalk.yellow(' meanio is out of date'));
console.log(' Current: ' + meanioVersion + ' Latest: ' + latest);
} else {
console.log(chalk.green(' meanio at latest version:'), meanioVersion);
}
});
});
npm.load({
global: true,
loglevel: 'warn'
}, function(err, npm) {
npm.commands.outdated('mean-cli', true, function(err, list) {
if (err) {
console.log(chalk.red('Error: npm outdated failed'));
return console.error(err);
}
latest = list[0] ? list[0][3] : cliVersion; // list[0][3] holds the 'latest' value
if (latest < cliVersion) {
console.log(chalk.yellow(' mean-cli is out of date'));
console.log(' Current: ' + cliVersion + ' Latest: ' + latest);
} else {
console.log(chalk.green(' mean-cli at latest version:'), cliVersion);
}
});
});
}
function requiresRoot(callback) {
utils.loadPackageJson(process.cwd() + '/package.json', function(err, data) {
if (err || (data.name !== 'mean' && !data.mean)) {
console.log(chalk.yellow('Invalid MEAN app or not in app root'));
} else {
callback();
}
});
}
function mongoConnect(env, callback) {
utils.loadPackageJson('./package.json', function(err, data) {
if (err) return callback(err);
var path = (data.meanVersion < '0.4.0' ? '/server' : '') + '/config/env/' + env + '.js';
var config = require(process.cwd() + path);
var db = require('mongoose').createConnection(config.db, config.dbOptions);
db.on('error', console.error.bind(console, chalk.red(' Error Connecting to database:')));
db.once('open', function() {
console.log(chalk.green(' DB connection successful!'));
console.log();
db.options.url = config.db;
callback(null, db);
});
});
}
/* START OF NETWORK FUNCTIONS - TODO refactor to network.js */
function getUserHome() {
return process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
}
function readToken() {
var file = (process.platform === 'win32') ? '_mean' : '.mean';
var path = getUserHome() + '/' + file;
if (!shell.test('-e', path)) return null;
return shell.cat(path);
}
var whoami = exports.whoami = function(callback) {
var token = readToken();
if (token) {
var options = {
uri: 'https://network.mean.io/api/v0.1/whoami',
method: 'GET',
headers: {
'authorization': token
}
};
request(options, function(error, response, body) {
if (!error && (response.statusCode === 200 || response.statusCode === 201)) {
if (callback) return callback(body);
console.log(body);
} else {
console.log('Client is NOT Authorized. Invalid token.');
}
});
} else {
console.log('Client is NOT Authorized.');
}
};
var authorize = exports.authorize = function(token, callback) {
var file = (process.platform === 'win32') ? '_mean' : '.mean';
var path = getUserHome() + '/' + file;
if (token) {
fs.writeFile(path, token, function(err) {
if (err) console.log(err);
whoami();
});
} else {
prompt.start();
prompt.get({
properties: {
token: {
hidden: true,
required: true
}
}
},
function(err, result) {
fs.writeFile(path, result.token, function(err) {
if (err) console.log(err);
whoami(callback);
});
});
}
};
exports.logout = function() {
var file = (process.platform === 'win32') ? '_mean' : '.mean';
var path = getUserHome() + '/' + file;
shell.rm(path);
};
exports.register = function() {
prompt.start();
prompt.get({
properties: {
name: {
pattern: /^[a-zA-Z\s\-]+$/,
minLength: 4,
maxLength: 15,
message: 'Name must be only letters, spaces, or dashes (min length of 4)',
required: true
},
username: {
minLength: 4,
maxLength: 15,
pattern: /^[a-zA-Z\s\-]+$/,
message: 'Username must be only letters, spaces, or dashes (min length of 4)',
required: true
},
email: {
format: 'email',
required: true
},
password: {
minLength: 8,
maxLength: 15,
pattern: /^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$/,
message: 'Password must be only letters, spaces, or dashes 8-15 characters long',
hidden: true,
required: true
}
}
},
function(err, result) {
if (err) throw err;
var options = {
uri: 'https://network.mean.io/api/v0.1/user',
method: 'POST',
form: result,
headers: {
'Content-Type': 'multipart/form-data',
'Content-Length': querystring.stringify(result).length
}
};
request(options, function(err, response, body) {
if (!err && (response.statusCode === 200 || response.statusCode === 201)) {
console.log('Registration Successful! \n Authorizing the mean client.');
body = JSON.parse(body);
authorize(body.token, function() {
console.log('Run `mean whoami` to see authorized credentials');
});
} else {
console.log(chalk.red('Error: Registration Failed!'));
if (err) {
return console.error(err);
}
}
});
});
};
exports.addKey = function() {
var home = getUserHome();
var keys = shell.ls(home + '/.ssh');
keys.forEach(function(key, index) {
console.log('[' + (index + 1) + '] ' + key);
});
console.log('Select SSH key to associate to your account:');
prompt.start();
prompt.get({
properties: {
key: {
format: 'number',
required: true
}
}
},
function(err, result) {
if (!keys[result.key - 1]) return console.log('Invalid selection');
var sshKey = shell.cat(home + '/.ssh/' + keys[result.key - 1]);
var token = readToken();
if (token) {
var keyData = {
key: sshKey,
title: keys[result.key - 1]
};
var options = {
uri: 'https://network.mean.io/api/v0.1/keys',
method: 'POST',
form: keyData,
headers: {
'Content-Type': 'multipart/form-data',
'Content-Length': querystring.stringify(keyData).length,
'authorization': token
}
};
request(options, function(error, response, body) {
if (!error && (response.statusCode === 200 || response.statusCode === 201)) {
console.log(body);
} else {
console.log('Add Key Failed!');
}
});
}
});
};
exports.login = function() {
prompt.start();
prompt.get({
properties: {
email: {
format: 'email',
required: true
},
password: {
minLength: 8,
maxLength: 15,
pattern: /^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$/,
message: 'Password must be only letters, spaces, or dashes 8-15 characters long',
hidden: true,
required: true
}
}
},
function(err, result) {
if (err) throw err;
var options = {
uri: 'https://network.mean.io/api/v0.1/user/login',
method: 'POST',
form: result,
headers: {
'Content-Type': 'multipart/form-data',
'Content-Length': querystring.stringify(result).length
}
};
request(options, function(err, response, body) {
if (!err && (response.statusCode === 200 || response.statusCode === 201)) {
console.log('Login Successful! \n Authorizing the mean client.');
body = JSON.parse(body);
authorize(body.token.api, function() {
console.log('Run `mean whoami` to see authorized credentials');
});
} else {
console.log(chalk.red('Error: Login Failed!'));
if (err) {
return console.error(err);
}
}
});
});
};
function checKeys(callback) {
var token = readToken();
if (!token) return console.log('Client not authorized! Use `mean authorize` or `mean register` to create a user.');
var options = {
uri: 'https://network.mean.io/api/v0.1/keys',
method: 'GET',
headers: {
'authorization': token
}
};
request(options, function(error, response, body) {
if (!error && response.statusCode === 200 && response.body.length) {
callback(JSON.parse(body));
} else {
callback([]);
}
});
}
exports.publish = function(options) {
utils.loadPackageJson('./package.json', function(err, pck) {
if (err || !pck) return console.log('You must be in a package root');
checKeys(function(keys) {
if (!keys.length) return console.log('You do not have any SSH keys. User `mean addKey`');
if (!shell.which('git')) return console.log(chalk.red(' Prerequisite not installed: git'));
console.log(chalk.green(' You are about to publish your package.'));
console.log(chalk.green(' In doing so your package, once moderated and approved'));
console.log(chalk.green(' will be available for all to use on the mean network.'));
console.log(chalk.green(' An email with instructions will be sent to you once approved'));
console.log(chalk.green(' (A package only needs approval on first publication)'));
console.log();
console.log(chalk.green(' I agree y/Y'));
console.log(chalk.green(' No. Anything else'));
prompt.start();
prompt.get({
properties: {
agree: {
pattern: /^[a-zA-Z\s\-]+$/,
minLength: 1,
maxLength: 5,
message: 'Do you agree to publish your package? y/Y for YES, Anything else NO',
required: true
}
}
},
function(err, result) {
if (err) throw err;
if (result.agree.toLowerCase() !== 'y') return console.log(chalk.red('Package publish aborted by user...'));
publishPackage(pck, options, function(data) {
if (!shell.test('-d', '.git')) {
shell.exec('git init', function(code) {
if (code) return console.log(chalk.red('Error: git init failed'));
});
}
if (!shell.test('-e', '.gitignore')) {
fs.writeFileSync('.gitignore', 'node_modules');
}
var silentState = shell.config.silent; // save old silent state
shell.config.silent = true;
shell.exec('git remote add meanio ' + data.repo, function(code) {
if (!code) {
console.log(chalk.yellow('Remote added'));
console.log(chalk.green('Package Created: ' + data.name));
console.log(chalk.green('You can now push your code to update latest/master '));
console.log(chalk.green(' `git push meanio master`'));
console.log(chalk.green('Running the publish command again will make a tag of the version pushed '));
console.log(chalk.green(' `mean publish`'));
}
});
shell.exec('git log -n 1', function(code) {
if (!code) {
shell.exec('git tag -f ' + data.version.toString(), function(code) {
shell.config.silent = silentState;
if (!code) {
shell.exec('git push meanio --force ' + data.version.toString(), function(code) {
if (!code) {
console.log(chalk.green('Publish Success! ' + data.name + '@' + data.version));
console.log('Use the `git add ` and `git commit ` then git push meanio master` to push your code');
console.log('Use `mean publish` to create tags based on your current version in package.json');
}
});
}
});
}
});
});
});
});
});
};
exports.logs = function(lines) {
utils.loadPackageJson('./package.json', function(err, pck) {
if (err || !pck) return console.log('You must be in a package root');
getLogs(pck, lines, function(data) {
try {
console.log(JSON.parse(data.response).log);
} catch (e) {
console.log('error parsing logs');
}
});
});
};
exports.deploy = function() {
utils.loadPackageJson('./package.json', function(err, pck) {
if (err || !pck) return console.log('You must be in a package root');
checKeys(function(keys) {
if (!keys.length) return console.log('You do not have any SSH keys. User `mean addKey`');
if (!shell.which('git')) return console.log(chalk.red(' Prerequisite not installed: git'));
console.log(chalk.green(' You are about to deploy your app.'));
console.log(chalk.green(' In doing so we will create a free public git repository on git.mean.io'));
console.log(chalk.green(' which you can use to develop and collaborate with'));
console.log(chalk.green(' Pushing your code to master will deploy it in the cloud <app>.<username>.cloud.mean.io'));
console.log();
console.log(chalk.green(' I agree y/Y'));
console.log(chalk.green(' No. Anything else'));
prompt.start();
prompt.get({
properties: {
agree: {
pattern: /^[a-zA-Z\s\-]+$/,
minLength: 1,
maxLength: 5,
message: 'Do you agree to deploy your app? y/Y for YES, Anything else NO',
required: true
}
}
},
function(err, result) {
if (err) throw err;
if (result.agree.toLowerCase() !== 'y') return console.log(chalk.red('Package publish aborted by user...'));
publishApp(pck, function(data) {
if (!shell.test('-d', '.git')) {
shell.exec('git init', function(code) {
if (code) return console.log(chalk.red('Error: git init failed'));
});
}
if (!shell.test('-e', '.gitignore')) {
fs.writeFileSync('.gitignore', 'node_modules');
}
var silentState = shell.config.silent; // save old silent state
shell.config.silent = true;
shell.exec('git remote add meanio ' + data.repo, function(code) {
if (!code) {
console.log(chalk.yellow('Remote added'));
console.log(chalk.green('App Created: ' + data.name));
console.log(chalk.green('You can now push your code to deploy the app '));
console.log(chalk.green(' executing `git push meanio master`...'));
}
shell.exec('git log -n 1', function(code) {
if (!code) {
shell.config.silent = false;
shell.exec('git push meanio master', function(code) {
if (!code) {
console.log(chalk.green('Publish Success! ' + data.name + '@' + data.version));
console.log(chalk.green('Your code has been pushed and is being deployed'));
console.log(chalk.green('Pushing changes to the master branch will automatically redepoy'));
getAppStatusTail(data.repo);
} else {
console.log(chalk.red('Failed pushing changes to the master branch. Pushing to master will auto deploy'));
}
});
}
shell.config.silent = silentState;
});
});
});
});
});
});
};
function getAppStatusTail(repo) {
var contentLength = 10;
var bar = new ProgressBar(' Deploying [:bar] :percent :etas :message', {
complete: '=',
incomplete: ' ',
width: 20,
total: contentLength
});
var barOptions = {};
barOptions.last = null;
barOptions.points = {
'creating gear': 1,
'creating DNS alias': 2,
'cloning gear and user repositories': 2,
'deploying mean.json': 3,
'finished': 2
};
setTimeout(function() {
appStatus(repo, bar, barOptions, true, 0);
}, 1000);
}
function appStatus(repo, bar, barOptions, tail, status) {
var repoStr = repo.replace('git@git.mean.io:', '').replace('.git', '').replace('/', '.').split('.');
if (status === 3) return console.log(chalk.green('\n deployed to -> http://' + repoStr[1] + '.' + repoStr[0] + '.cloud.mean.io \n git repo -> ' + repo));
var uri = repo.replace('git@git.mean.io:', 'https://network.mean.io/api/v0.1/app/status/').replace('.git', '');
var options = {
uri: uri,
method: 'GET'
};
request(options, function(error, response, body) {
if (!error && (response.statusCode === 200 || response.statusCode === 201)) {
body = JSON.parse(body);
if (barOptions.last !== body.message) {
barOptions.last = body.message;
bar.tick(barOptions.points[body.message || body.status], {
message: body.message || body.status || 'Deploying'
});
}
if (tail) return setTimeout(
function() {
if (body.status === 'finished') status++;
appStatus(repo, bar, barOptions, tail, status);
}, 1000);
}
});
}
exports.remoteCommand = function(command) {
utils.loadPackageJson('./package.json', function(err, pck) {
if (err || !pck) return console.log('You must be in a package root');
var body = {
name: pck.name,
command: command,
};
var token = readToken();
var options = {
uri: 'https://network.mean.io/api/v0.1/app/command',
method: 'POST',
form: querystring.stringify(body),
headers: {
'Content-Type': 'multipart/form-data',
'Content-Length': querystring.stringify(body).length,
'authorization': token
}
};
request(options, function(error, response, body) {
if (!error && (response.statusCode === 200 || response.statusCode === 201)) {
console.log(JSON.parse(body).response);
} else {
console.log('Failed to create app: ');
console.log(error);
}
});
});
};
function publishApp(data, callback) {
var body = {
name: data.name,
description: data.description,
version: data.version,
keywords: data.keywords
};
var token = readToken();
var options = {
uri: 'https://network.mean.io/api/v0.1/app/create',
method: 'POST',
form: querystring.stringify(body),
headers: {
'Content-Type': 'multipart/form-data',
'Content-Length': querystring.stringify(body).length,
'authorization': token
}
};
request(options, function(error, response, body) {
if (!error && (response.statusCode === 200 || response.statusCode === 201)) {
callback(JSON.parse(body));
} else {
console.log(chalk.red('Failed to create the app named ') + data.name);
console.log(chalk.red(body));
if (error) console.log(error);
}
});
}
function getLogs(data, lines, callback) {
var body = {
name: data.name,
lines: lines
};
var token = readToken();
var options = {
uri: 'https://network.mean.io/api/v0.1/app/logs',
method: 'POST',
form: querystring.stringify(body),
headers: {
'Content-Type': 'multipart/form-data',
'Content-Length': querystring.stringify(body).length,
'authorization': token
}
};
request(options, function(error, response, body) {
if (!error && (response.statusCode === 200 || response.statusCode === 201)) {
callback(JSON.parse(body));
} else {
console.log('Failed to retrieve logs: ');
console.log(error);
}
});
}
function publishPackage(data, opt, callback) {
var body = {
name: data.name,
description: data.description,
version: data.version,
keywords: data.keywords,
remote: opt.remote
};
var token = readToken();
var options = {
uri: 'https://network.mean.io/api/v0.1/packages/publish',
method: 'POST',
form: querystring.stringify(body),
headers: {
'Content-Type': 'multipart/form-data',
'Content-Length': querystring.stringify(body).length,
'authorization': token
}
};
request(options, function(error, response, body) {
if (!error && (response.statusCode === 200 || response.statusCode === 201)) {
callback(JSON.parse(body));
} else {
console.log('Failed to publish: ');
console.log(error);
}
});
}
exports.search = function(keywords) {
var options = {
uri: 'https://network.mean.io/api/v0.1/packages/search?q=' + keywords,
method: 'GET'
};
request(options, function(error, response, body) {
if (!error && (response.statusCode === 200 || response.statusCode === 201)) {
var results = JSON.parse(body);
console.log(chalk.green(results.length + ' found.'));
results.forEach(function(pkg) {
var authors = [];
pkg.authors.forEach(function(author) {
authors.push(author.username);
});
console.log(chalk.green(pkg.name) + '@' + pkg.version + ' ' + pkg.description + chalk.green(' by: ') + authors.join(','));
});
} else {
console.log(error);
}
});
};
/* END OF NETWORK FUNCTIONS */
exports.init = function(options) {
install.init(options);
};
function getPackage(name, callback) {
var options = {
uri: 'https://network.mean.io/api/v0.1/packages/' + name,
method: 'GET'
};
request(options, function(error, response, body) {
if (!error && (response.statusCode === 200 || response.statusCode === 201)) {
if (callback) return callback(JSON.parse(body));
} else {
console.log('Package not found.');
}
});
}
exports.install = function(module, options) {
options = options || {};
requiresRoot(function() {
utils.loadPackageJson('./node_modules/meanio/package.json', function(err, data) {
var destination = 'packages/contrib/';
if (err || data.version < '0.5.18') destination = 'node_modules/';
var packageName = module.split('@')[0];
var tag = 'master';
tag = tag === 'latest' ? 'master' : tag;
getPackage(packageName, function(data) {
console.log(chalk.green('Installing module: %s:'), packageName);
if (data.repo.indexOf('git.mean.io') === -1) {
options.git = true;
}
var cloneUrl = options.git ? data.repo : 'https://git.mean.io/' + data.repo.split(':')[1];
shell.rm('-rf', destination + data.name);
console.log('git clone --branch ' + tag + ' ' + cloneUrl + ' ' + destination + data.name);
var silentState = shell.config.silent; // save old silent state
shell.config.silent = true;
shell.exec('git clone --branch ' + tag + ' ' + cloneUrl + ' ' + destination + data.name, function(code) {
shell.config.silent = silentState;
if (code) return console.log('Failed to clone repo');
var pkgPath = destination + data.name;
shell.rm('-rf', destination + data.name + '/.git');
shell.rm('-rf', destination + data.name + '/.gitignore');
// Load mean.json
packagesMeanJson(__dirname);
if (options.skipNpm) return;
// Load package.json
utils.loadPackageJson(pkgPath + '/package.json', function(err, data) {
if (err) return console.error(err);
console.log();
if (!data.mean) {
console.log();
console.log(chalk.yellow('Warning: The module installed is not a valid MEAN module'));
}
shell.cd(pkgPath);
shell.exec('npm install .', function(code) {
if (code) return console.log(code);
console.log(chalk.green(' Dependencies installed for package ' + data.name));
require('bower').commands.install().on('error', function(err) {
console.log(chalk.yellow(' ' + err + ' ' + data.name));
});
});
});
});
});
});
});
};
exports.postinstall = function() {
requiresRoot(function() {
var bower = require('bower');
console.log(chalk.green('Installing Bower dependencies'));
bower.commands.update().on('error', function(err) {
console.log(chalk.red(err));
});
packagesNpmInstall('packages');
packagesNpmInstall('packages/custom');
packagesNpmInstall('packages/core');
// Load mean.json
var source = process.cwd();
packagesMeanJson(source);
});
};
function packagesNpmInstall(source) {
var packages = path.join(process.cwd(), source);
npm.load({
loglevel: 'error'
}, function(err, npm) {
fs.readdir(packages, function(err, files) {
if (err && 'ENOENT' !== err.code) throw Error(err);
if (!files || !files.length) return;
console.log(chalk.green('Auto installing package dependencies'));
files.forEach(function(file) {
var pkgPath = path.join(packages, file);
packagesMeanJson(pkgPath);
utils.loadPackageJson(path.join(pkgPath, 'package.json'), function(err, data) {
if (err || !data.mean) return;
npm.commands.install(pkgPath, [pkgPath], function(err) {
if (err) {
console.log(chalk.red('Error: npm install failed'));
return console.error(err);
} else {
console.log(chalk.green(' Dependencies installed for package ' + file));
}
});
});
});
});
});
}
function packagesMeanJson(source) {
// Load mean.json
utils.loadPackageJson(path.join(source, 'mean.json'), function(err, data) {
if (err || !data) return;
for (var dep in data.dependencies) {
shell.cd(process.cwd());
exports.install(dep + '@' + data.dependencies[dep]);
}
});
}
exports.uninstall = function(module) {
requiresRoot(function() {
console.log(chalk.yellow('Removing module:'), module);
if (shell.test('-d', './packages/' + module)) {
shell.rm('-rf', './packages/' + module);
} else if (shell.test('-d', './packages/core/' + module)) {
shell.rm('-rf', './packages/core/' + module);
} else if (shell.test('-d', './packages/contrib/' + module)) {
shell.rm('-rf', './packages/contrib/' + module);
} else if (shell.test('-d', './packages/custom/' + module)) {
shell.rm('-rf', './packages/custom/' + module);
}
console.log(chalk.green(' uninstall complete'));
});
};
exports.list = function() {
requiresRoot(function() {
console.log(chalk.green(' MEAN Packages List:'));
console.log(' -----------------');
function look(type) {
var path = './packages/' + type + '/';
fs.readdir(path, function(err, files) {
if (err || !files.length) return console.log(chalk.yellow(' No ' + type + ' Packages'));
files.forEach(function(file) {
utils.loadPackageJson(path + file + '/package.json', function(err, data) {
if (!err && data.mean) console.log(getPackageInfo(type, data));
});
});
});
}
// look in node_modules for external packages
look('core');
// look in node_modules for external packages
look('contrib');
// look in packages for local packages
look('custom');
});
};
exports.status = function(options) {
requiresRoot(function() {
console.log();
console.log(chalk.green(' MEAN Status'));
console.log(' -----------');
console.log();
utils.loadPackageJson('./package.json', function(err, data) {
if (err) throw new Error(err);
console.log(' MEAN VERSION: ' + data.meanVersion);
console.log();
mongoConnect(options.env, function(err, db) {
if (err) throw new Error(err);
console.log(' MongoDB URI: ' + db.options.url);
checkVersion();
db.close();
});
});
});
};
exports.pkg = function(name, options) {
requiresRoot(function() {
if (options.delete) {
console.log(chalk.yellow('Removing package:'), name);
shell.rm('-rf', './packages/' + name);
} else {
ensureEmpty('./packages/' + name, options.force, function() {
require('./scaffold.js').packages(name, options);
});
}
});
};
exports.printUser = function(email, options) {
requiresRoot(function() {
mongoConnect(options.env, function(err, db) {
if (err) throw new Error(err);
db.collection('users').find({
email: email
}).toArray(function(err, user) {
console.dir(user);
db.close();
});
});
});
};
exports.updateRole = function(email, options, type) {
requiresRoot(function() {
var update = {};
switch (type) {
case 'a':
console.log(' Adding role `' + options.addRole + '` to user `' + email + '`');
update.$push = {
roles: options.addRole
};
break;
case 'r':
console.log(' Removing role `' + options.removeRole + '` from user `' + email + '`');
update.$pull = {
roles: options.removeRole
};
break;
default:
return;
}
mongoConnect(options.env, function(err, db) {
if (err) throw new Error(err);
db.collection('users').update({
email: email
}, update, {
w: 1,
upsert: false,
multi: false
}, function(err) {
if (err) console.error(err);
else console.log(chalk.green('successfully updated'));
db.close();
});
});
});
};
| {
"content_hash": "d302f61677b783aa7851961350dfe408",
"timestamp": "",
"source": "github",
"line_count": 1133,
"max_line_length": 155,
"avg_line_length": 28.285083848190645,
"alnum_prop": 0.5530626891752738,
"repo_name": "BlakeBrown/Fermat",
"id": "c4b75f41ca8c78d4f6cc6627d63b467e946a28e8",
"size": "32047",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/meanio/node_modules/mean-cli/lib/cli.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "16492"
},
{
"name": "HTML",
"bytes": "25913"
},
{
"name": "JavaScript",
"bytes": "262286"
},
{
"name": "Perl",
"bytes": "48"
}
],
"symlink_target": ""
} |
using System;
namespace Motherlode.Data.NHibernate.Wpf.Interceptor.ObjectFactory
{
public interface IObjectFactory
{
#region Public Methods and Operators
T Create<T>();
object Create(Type type);
#endregion
}
}
| {
"content_hash": "27888d7ac52b40c31d4ddeffaa67e51c",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 66,
"avg_line_length": 17.2,
"alnum_prop": 0.6511627906976745,
"repo_name": "xSkara/Motherlode",
"id": "c2de7964e0db86b2cb4e327a9e7abef51e5c3085",
"size": "258",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Motherlode.Data.NHibernate/Wpf/Interceptor/ObjectFactory/IObjectFactory.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "394984"
},
{
"name": "PowerShell",
"bytes": "39315"
},
{
"name": "Shell",
"bytes": "216"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Last Colony</title>
<script src="js/common.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/game.js" type="text/javascript" charset="utf-8"></script>
<script src="js/mouse.js" type="text/javascript" charset="utf-8"></script>
<script src="js/singleplayer.js" type="text/javascript" charset="utf-8"></script>
<script src="js/maps.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" href="styles.css" type="text/css" media="screen" charset="utf-8">
</head>
<body>
<div id="gamecontainer">
<div id="gamestartscreen" class="gamelayer">
<span id="singleplayer" onclick = "singleplayer.start();">Campaign</span><br>
<span id="multiplayer" onclick = "multiplayer.start();">Multiplayer</span><br>
</div>
<div id="missionscreen" class="gamelayer">
<input type="button" id="entermission" onclick = "singleplayer.play();">
<input type="button" id="exitmission" onclick = "singleplayer.exit();">
<div id="missonbriefing">Welcome to your first mission.
</div>
</div>
<div id="gameinterfacescreen" class="gamelayer">
<div id="gamemessages"></div>
<div id="callerpicture"></div>
<div id="cash"></div>
<div id="sidebarbuttons">
</div>
<canvas id="gamebackgroundcanvas" height="400" width="480"></canvas>
<canvas id="gameforegroundcanvas" height="400" width="480"></canvas>
</div>
<div id="loadingscreen" class="gamelayer">
<div id="loadingmessage"></div>
</div>
</div>
</body>
</html> | {
"content_hash": "30a0e4db8f9c9310d9c190c6a4053b80",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 91,
"avg_line_length": 46.214285714285715,
"alnum_prop": 0.5806285419886656,
"repo_name": "renehugentobler/UltimaNeo",
"id": "40df7029473673930424b567dcf1ee85fddb4f4d",
"size": "1941",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Apress Pro HTML5 Games/9781430247104_ch05-code/9781430212345_ch05-code/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "41832"
},
{
"name": "C#",
"bytes": "68594"
},
{
"name": "CSS",
"bytes": "50067"
},
{
"name": "HTML",
"bytes": "84725"
},
{
"name": "JavaScript",
"bytes": "1197498"
}
],
"symlink_target": ""
} |
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0099cc"
tools:context=".FullscreenActivity" >
<!--
The primary full-screen view. This can be replaced with whatever view
is needed to present your content, e.g. VideoView, SurfaceView,
TextureView, etc.
-->
<TextView
android:id="@+id/fullscreen_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:keepScreenOn="true"
android:text="@string/dummy_content"
android:textColor="#33b5e5"
android:textSize="50sp"
android:textStyle="bold" />
<!--
This FrameLayout insets its children based on system windows using
android:fitsSystemWindows.
-->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true" >
<LinearLayout
android:id="@+id/fullscreen_content_controls"
style="?buttonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:background="@color/black_overlay"
android:orientation="horizontal"
tools:ignore="UselessParent" >
<Button
android:id="@+id/dummy_button"
style="?buttonBarButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/dummy_button" />
</LinearLayout>
</FrameLayout>
</FrameLayout>
| {
"content_hash": "390b2e8daee94926c40bab734ee12ef8",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 78,
"avg_line_length": 33.49122807017544,
"alnum_prop": 0.6144578313253012,
"repo_name": "nbeckman/nolacoaster",
"id": "8108373775bd343512bcf4dcff36cea1c9bf54a7",
"size": "1909",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Megabudget/res/layout/activity_fullscreen.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "135"
},
{
"name": "Emacs Lisp",
"bytes": "6477"
},
{
"name": "HTML",
"bytes": "14577"
},
{
"name": "Java",
"bytes": "314235"
},
{
"name": "Python",
"bytes": "3817"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.sandbox.regression.gmm.IVRegressionResults.load — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/stylesheets/deprecation.css">
<link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="../_static/material.css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" />
<script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/_sphinx_javascript_frameworks_compat.js"></script>
<script src="../_static/doctools.js"></script>
<script src="../_static/sphinx_highlight.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.sandbox.regression.gmm.IVRegressionResults.normalized_cov_params" href="statsmodels.sandbox.regression.gmm.IVRegressionResults.normalized_cov_params.html" />
<link rel="prev" title="statsmodels.sandbox.regression.gmm.IVRegressionResults.initialize" href="statsmodels.sandbox.regression.gmm.IVRegressionResults.initialize.html" />
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.sandbox.regression.gmm.IVRegressionResults.load" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels 0.14.0 (+596)</span>
<span class="md-header-nav__topic"> statsmodels.sandbox.regression.gmm.IVRegressionResults.load </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="get" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../../versions-v2.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../gmm.html" class="md-tabs__link">Generalized Method of Moments <code class="xref py py-mod docutils literal notranslate"><span class="pre">gmm</span></code></a></li>
<li class="md-tabs__item"><a href="statsmodels.sandbox.regression.gmm.IVRegressionResults.html" class="md-tabs__link">statsmodels.sandbox.regression.gmm.IVRegressionResults</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels 0.14.0 (+596)</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../duration.html" class="md-nav__link">Methods for Survival and Duration Analysis</a>
</li>
<li class="md-nav__item">
<a href="../nonparametric.html" class="md-nav__link">Nonparametric Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">nonparametric</span></code></a>
</li>
<li class="md-nav__item">
<a href="../gmm.html" class="md-nav__link">Generalized Method of Moments <code class="xref py py-mod docutils literal notranslate"><span class="pre">gmm</span></code></a>
</li>
<li class="md-nav__item">
<a href="../miscmodels.html" class="md-nav__link">Other Models <code class="xref py py-mod docutils literal notranslate"><span class="pre">miscmodels</span></code></a>
</li>
<li class="md-nav__item">
<a href="../multivariate.html" class="md-nav__link">Multivariate Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">multivariate</span></code></a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Contents</label>
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a href="#generated-statsmodels-sandbox-regression-gmm-ivregressionresults-load--page-root" class="md-nav__link">statsmodels.sandbox.regression.gmm.IVRegressionResults.load</a><nav class="md-nav">
<ul class="md-nav__list">
<li class="md-nav__item"><a href="#statsmodels.sandbox.regression.gmm.IVRegressionResults.load" class="md-nav__link"><code class="docutils literal notranslate"><span class="pre">IVRegressionResults.load</span></code></a>
</li></ul>
</nav>
</li>
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.sandbox.regression.gmm.IVRegressionResults.load.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<section id="statsmodels-sandbox-regression-gmm-ivregressionresults-load">
<h1 id="generated-statsmodels-sandbox-regression-gmm-ivregressionresults-load--page-root">statsmodels.sandbox.regression.gmm.IVRegressionResults.load<a class="headerlink" href="#generated-statsmodels-sandbox-regression-gmm-ivregressionresults-load--page-root" title="Permalink to this heading">¶</a></h1>
<dl class="py method">
<dt class="sig sig-object py" id="statsmodels.sandbox.regression.gmm.IVRegressionResults.load">
<em class="property"><span class="pre">classmethod</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">IVRegressionResults.</span></span><span class="sig-name descname"><span class="pre">load</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">fname</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.sandbox.regression.gmm.IVRegressionResults.load" title="Permalink to this definition">¶</a></dt>
<dd><p>Load a pickled results instance</p>
<div class="admonition warning">
<p class="admonition-title">Warning</p>
<p>Loading pickled models is not secure against erroneous or
maliciously constructed data. Never unpickle data received from
an untrusted or unauthenticated source.</p>
</div>
<dl class="field-list">
<dt class="field-odd">Parameters<span class="colon">:</span></dt>
<dd class="field-odd"><dl>
<dt><strong>fname</strong><span class="classifier">{<a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#str" title="(in Python v3.11)"><code class="docutils literal notranslate"><span class="pre">str</span></code></a>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">handle</span></code>, <a class="reference external" href="https://docs.python.org/3/library/pathlib.html#pathlib.Path" title="(in Python v3.11)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">pathlib.Path</span></code></a>}</span></dt><dd><p>A string filename or a file handle.</p>
</dd>
</dl>
</dd>
<dt class="field-even">Returns<span class="colon">:</span></dt>
<dd class="field-even"><dl class="simple">
<dt><code class="xref py py-obj docutils literal notranslate"><span class="pre">Results</span></code></dt><dd><p>The unpickled results instance.</p>
</dd>
</dl>
</dd>
</dl>
</dd></dl>
</section>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.sandbox.regression.gmm.IVRegressionResults.initialize.html" title="statsmodels.sandbox.regression.gmm.IVRegressionResults.initialize"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.sandbox.regression.gmm.IVRegressionResults.initialize </span>
</div>
</a>
<a href="statsmodels.sandbox.regression.gmm.IVRegressionResults.normalized_cov_params.html" title="statsmodels.sandbox.regression.gmm.IVRegressionResults.normalized_cov_params"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.sandbox.regression.gmm.IVRegressionResults.normalized_cov_params </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Nov 11, 2022.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 5.3.0.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html> | {
"content_hash": "adbf27b516139c432d00cd597eeff51a",
"timestamp": "",
"source": "github",
"line_count": 491,
"max_line_length": 999,
"avg_line_length": 41.92871690427699,
"alnum_prop": 0.6167484334774372,
"repo_name": "statsmodels/statsmodels.github.io",
"id": "1689c9fd4e3cf090138883b2dc77ae403024c62e",
"size": "20591",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "devel/generated/statsmodels.sandbox.regression.gmm.IVRegressionResults.load.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
/// <reference path="jquery-1.4.1-vsdoc.js" />
// Extend jQuery. Use $(selector).image(src, callback);
$.fn.image = function (src, f)
{
return this.each(function ()
{
$("<img />").appendTo(this).each(function ()
{
this.src = src;
this.onload = f;
});
});
}
$(document).ready(function ()
{
$.getJSON("http://alpha.kita.dk:8000/static/galleri.json", null, function (galleriData)
{
// Bind pre/next link click event
$("#images a.controls-prev").live("click", function (event) { event.preventDefault(); PreviousImage(); });
$("#images a.controls-next").live("click", function (event) { event.preventDefault(); NextImage(); });
$("#galleryImage").parent().click(function (event) { event.preventDefault(); NextImage(); });
// Register keypress events on the whole document
$(document).keypress(function (e)
{
switch (e.keyCode)
{
case 37: /* Left arrow */
PreviousImage();
break;
case 39: /* Right arrow */
NextImage();
break;
}
});
// Globals
var hidden = $("body").append('<div id="img-cache" style="display:none;"></div>').children("#img-cache");
var iPreloadCount = 0;
var iMaxPreload = 5;
var allImages = [];
var preloadedImages = [];
var iIndex = 0;
var prevLinkSet = false;
var nextLinkSet = false;
var directionForward = true;
function BuildImageArray()
{
var photographer;
for (var i = 0; i < galleriData.photographers.length; i++)
{
photographer = galleriData.photographers[i];
for (var ii = 0, j = photographer.images.length; ii < j; ii++)
{
allImages.push({ "image": photographer.images[ii].image, "photographer": photographer });
}
}
}
function BuildImageUrl(i)
{
return galleriData.baseUrl + allImages[i].photographer.encodedName + "/" + allImages[i].image;
}
function SetPhotographer(i)
{
var aLink = $("#collection-image-photographer a");
aLink.html(allImages[i].photographer.name);
aLink.attr("href", "http://staging.anime-kita.dk/galleri/server.fcgi/fotograf/" + allImages[i].photographer.encodedName);
}
function ChangeLinks(i)
{
// "Previous" link
if (i > 0 && !prevLinkSet)
{
var prevSpanInner = $("#images span.controls-prev").html();
$("#images span.controls-prev").replaceWith('<a class="controls-prev" href="#images">' + prevSpanInner + "</a>");
prevLinkSet = true;
}
else if (i == 0)
{
var prevAInner = $("#images a.controls-prev").html();
$("#images a.controls-prev").replaceWith('<span class="controls-prev">' + prevAInner + "</span>");
prevLinkSet = false;
}
// "Next" link
if (i < allImages.length && !nextLinkSet)
{
var nextSpanInner = $("#images span.controls-next").html();
$("#images span.controls-next").replaceWith('<a class="controls-next" href="#images">' + nextSpanInner + "</a>");
nextLinkSet = true;
}
else if (i == allImages.length - 1)
{
var nextAInner = $("#images a.controls-next").html();
$("#images a.controls-next").replaceWith('<span class="controls-next">' + nextAInner + "</span>");
nextLinkSet = false;
}
}
function ImageIsPreloaded(image)
{
var Preloaded = false;
for (var i = 0, j = preloadedImages.length; i < j; i++)
{
if (preloadedImages[i] == image)
{
Preloaded = true;
break;
}
}
return Preloaded;
}
function PreLoad(i)
{
// Check for 'out of index'
var j = allImages.length;
if (i >= j || i < 0) { return; }
// Check if preload has to stop
if (iPreloadCount > iMaxPreload) { return; }
iPreloadCount++;
// Make sure not to preload any existing images.
while (ImageIsPreloaded(allImages[i].image))
{
if (directionForward) { i++; }
else { i--; }
// Check for 'out of index'
if (i >= j || i < 0) { return; }
}
// Set next index
var i_Next = directionForward ? (i + 1) : (i - 1);
// Add to preloaded list
preloadedImages.push(allImages[i].image);
// Preload image and set callback
$(hidden).image(BuildImageUrl(i), function ()
{
PreLoad(i_Next);
});
}
function NextImage()
{
if (iIndex + 1 >= allImages.length) { return; }
// Set next index
iIndex++;
directionForward = true;
// Set the app state
SetState(iIndex);
}
function PreviousImage()
{
if (iIndex - 1 < 0) { return; }
// Set previous index
iIndex--;
directionForward = false;
// Set the app state
SetState(iIndex);
}
function LoadImage(i)
{
// Set image
$("#galleryImage").attr("src", BuildImageUrl(i));
// Set ScrollTop
$(window).scrollTop($("#images").offset().top);
// Set current index
$(".imageIndex").html("billede " + (i + 1) + " ud af " + allImages.length);
// Change prev/next links
ChangeLinks(i);
// Set photographer
SetPhotographer(i);
// Preload the next pictures
iPreloadCount = 0;
i++;
setTimeout(function ()
{
PreLoad(i);
}, 1000);
}
function SetState(i)
{
$.bbq.pushState({ index: i });
}
BuildImageArray();
$(window).bind("hashchange", function (e)
{
iIndex = e.getState("index") || 0;
iIndex = parseInt(iIndex);
// Force inrange validation
if (iIndex > allImages.length - 1)
{
SetState((allImages.length - 1));
return;
}
else if (iIndex < 0)
{
SetState(0);
return;
}
LoadImage(iIndex);
});
$(window).trigger("hashchange");
});
});
| {
"content_hash": "ce0b321ea476b1c576cbf4215b6fbf3c",
"timestamp": "",
"source": "github",
"line_count": 237,
"max_line_length": 133,
"avg_line_length": 30.848101265822784,
"alnum_prop": 0.4469976747366981,
"repo_name": "animekita/anime-kita-static",
"id": "8a0fd60e6b3428419af4aa5da4ee6a7e6284d89f",
"size": "7313",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/gallery.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "321037"
},
{
"name": "CSS",
"bytes": "30272"
},
{
"name": "JavaScript",
"bytes": "151835"
},
{
"name": "PHP",
"bytes": "7956"
}
],
"symlink_target": ""
} |
PACKAGE_NAME=oras
PACKAGE_VERSION=${1:-v0.11.1}
PACKAGE_URL=https://github.com/oras-project/oras
yum install -y wget git tar gcc make
GO_VERSION=1.14
# Install Go and setup working directory
wget https://golang.org/dl/go$GO_VERSION.linux-ppc64le.tar.gz
tar -C /bin -xf go$GO_VERSION.linux-ppc64le.tar.gz
mkdir -p /home/tester/go/src
rm -f go$GO_VERSION.linux-ppc64le.tar.gz
export PATH=$PATH:/bin/go/bin
export GOPATH=/home/tester/go
OS_NAME=$(cat /etc/os-release | grep ^PRETTY_NAME | cut -d= -f2)
export PATH=$GOPATH/bin:$PATH
export GO111MODULE=on
cd /home/tester/go/src
git clone --recurse $PACKAGE_URL
cd $PACKAGE_NAME
git checkout $PACKAGE_VERSION
if ! go build -a -v ./...; then
echo "------------------$PACKAGE_NAME:install_fails-------------------------------------"
echo "$PACKAGE_NAME | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail | Intsall_Fails"
exit 1
fi
if ! make test; then
echo "------------------$PACKAGE_NAME:test_fails-------------------------------------"
echo "$PACKAGE_NAME | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail | Install_Success_Test_Fails"
exit 1
else
echo "------------------$PACKAGE_NAME:install_&_test_both_success-------------------------"
echo "$PACKAGE_NAME | $PACKAGE_VERSION | $OS_NAME | GitHub | Pass | Install_and_Test_Success"
echo "------------------$PACKAGE_NAME:Installed at path: /home/tester/go/src/$PACKAGE_NAME------------------------"
exit 0
fi
| {
"content_hash": "e00d09854cde4884bdb58ea171195671",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 123,
"avg_line_length": 32.52173913043478,
"alnum_prop": 0.5882352941176471,
"repo_name": "ppc64le/build-scripts",
"id": "729e82af0398445dcc079f09dca1df6c24a4d600",
"size": "2270",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "g/github.com_deislabs_oras/github.com_deislabs_oras_ubi_8.5.sh",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1464"
},
{
"name": "C",
"bytes": "14922"
},
{
"name": "Dockerfile",
"bytes": "731231"
},
{
"name": "Groovy",
"bytes": "984"
},
{
"name": "Makefile",
"bytes": "7280"
},
{
"name": "OpenEdge ABL",
"bytes": "37872"
},
{
"name": "Python",
"bytes": "37596"
},
{
"name": "Roff",
"bytes": "7458"
},
{
"name": "Shell",
"bytes": "13688799"
}
],
"symlink_target": ""
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.springboot.starter.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
*
* @author Jun Hwong
*/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/home","/test/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("123").roles("USER");
}
}
| {
"content_hash": "7b4a5b3dd6afc08cede0f55ca5c9f839",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 107,
"avg_line_length": 35.022222222222226,
"alnum_prop": 0.6732233502538071,
"repo_name": "junhwong/springboot-starter",
"id": "2e3def9265181762bde964f711d0f4934d467d8e",
"size": "1576",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "springboot-starter-web/src/main/java/org/springboot/starter/web/WebSecurityConfig.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "9690"
}
],
"symlink_target": ""
} |
/* eslint-disable @typescript-eslint/no-var-requires */
const pkg = require('../package.json');
const fs = require('fs-extra');
const buildConfig = pkg['datauri-build'];
const names = Object.keys(buildConfig);
function createConfig(source, keys) {
const obj = {};
Object.keys(source)
.filter((key) => keys.includes(key))
.forEach((key) => (obj[key] = source[key]));
return obj;
}
const createPkg = async (name, meta) => {
const props = [
'version',
'repository',
'engines',
'keywords',
'author',
'license',
'maintainers'
];
const config = createConfig(pkg, props);
const newPkg = Object.assign({}, config, meta);
const encoding = 'utf-8';
const [readme] = await Promise.all([
fs.readFile(`docs/${name}.md`, encoding),
fs.outputFile(`lib/${name}/package.json`, JSON.stringify(newPkg), encoding),
fs.outputFile(`lib/${name}/.npmignore`, 'node_modules', encoding)
]);
await fs.outputFile(`lib/${name}/readme.md`, readme, encoding);
};
function getMetadata(name) {
const meta = {
name: name,
dependencies: createConfig(pkg.devDependencies, buildConfig[name].dependencies)
};
if (name.endsWith('cli')) {
meta.dependencies[names[0]] = pkg.version;
meta.bin = buildConfig[name].bin;
}
meta.description = buildConfig[name].description;
return meta;
}
names.forEach(async (name) => await createPkg(name, getMetadata(name)));
| {
"content_hash": "9fa6f02654e68256c0eaea9ae63f251e",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 83,
"avg_line_length": 25.446428571428573,
"alnum_prop": 0.6519298245614035,
"repo_name": "heldr/datauri",
"id": "65e53fcc3b83dc547252f645a22ea7962eed64ac",
"size": "1425",
"binary": false,
"copies": "1",
"ref": "refs/heads/dependabot/npm_and_yarn/minimist-1.2.6",
"path": "tools/pkg-json.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "26"
},
{
"name": "JavaScript",
"bytes": "28410"
}
],
"symlink_target": ""
} |
<?php
namespace PHPExiftool\Driver\Tag\MXF;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class UserName extends AbstractTag
{
protected $Id = 'mixed';
protected $Name = 'UserName';
protected $FullName = 'MXF::Main';
protected $GroupName = 'MXF';
protected $g0 = 'MXF';
protected $g1 = 'MXF';
protected $g2 = 'Video';
protected $Type = 'mixed';
protected $Writable = false;
protected $Description = 'User Name';
}
| {
"content_hash": "8e082cb717ccd45a5ae4b6c25b3f0791",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 46,
"avg_line_length": 15.457142857142857,
"alnum_prop": 0.6469500924214417,
"repo_name": "romainneutron/PHPExiftool",
"id": "ddae21a3ae26a60c3d504097ee7c6d399c6a012a",
"size": "763",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/PHPExiftool/Driver/Tag/MXF/Username.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "22042446"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Core.CIM;
using ArcGIS.Core.Data;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Catalog;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Extensions;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Dialogs;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
namespace EditingTemplates
{
internal class CreateFeatures : Button
{
protected override async void OnClick()
{
MapView mapvView = MapView.Active;
if (mapvView == null)
return;
// get the Fire Stations layer
FeatureLayer layer = mapvView.Map.GetLayersAsFlattenedList().
OfType<FeatureLayer>().FirstOrDefault(l => l.Name == "Fire Stations");
if (layer == null)
return;
await QueuedTask.Run(async () =>
{
// use the center of the mapextent as the geometry
var extent = mapvView.Extent;
var geometry = extent.Center;
// set up 2 other geometries offset
var geometry2 = GeometryEngine.Instance.Move(geometry, extent.Width / 4, extent.Height / 4);
var geometry3 = GeometryEngine.Instance.Move(geometry, -extent.Width / 4, -extent.Height / 4);
// get one of the templates
var template = layer.GetTemplate("Fire Stations");
if (template != null)
{
// activate the template - use the default tool
await template.ActivateDefaultToolAsync();
// you can also activate a template via a specific tool
// (assuming tool is available for the template)
// await template.ActivateToolAsync("esri_editing_SketchPointTool");
// perform the creation
var op = new EditOperation();
op.Name = "Create feature";
// use template default field values
op.Create(template, geometry);
// to modify default template properties
var insp = template.Inspector;
insp["City"] = "xxx";
// create with the modified fields and a different geometry
op.Create(template, geometry2);
// reset the modified fields back to original defaults
insp.Cancel();
// change the field again
insp["City"] = "yyy";
// create with the modified fields and a different geometry
op.Create(template, geometry3);
// reset the modified fields back to original defaults
insp.Cancel();
// execute the operation
bool result = op.Execute();
}
});
}
}
}
| {
"content_hash": "f5c994c70fb8c719c7b1f52799992579",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 102,
"avg_line_length": 32.4,
"alnum_prop": 0.6387073347857661,
"repo_name": "Esri/arcgis-pro-sdk-community-samples",
"id": "459deea20a4eaed2d55d7d71b210cb905057af69",
"size": "3338",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Editing/EditingTemplates/CreateFeatures.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "6521661"
},
{
"name": "CSS",
"bytes": "4426"
},
{
"name": "HTML",
"bytes": "9928"
},
{
"name": "Python",
"bytes": "3248"
},
{
"name": "Visual Basic .NET",
"bytes": "31990"
},
{
"name": "XSLT",
"bytes": "11612"
}
],
"symlink_target": ""
} |
namespace CMT {
using std::pair;
using std::make_pair;
using Eigen::ArrayXXd;
using Eigen::Array;
using Eigen::Dynamic;
class Preconditioner {
public:
virtual ~Preconditioner();
virtual int dimIn() const = 0;
virtual int dimInPre() const = 0;
virtual int dimOut() const = 0;
virtual int dimOutPre() const = 0;
virtual pair<ArrayXXd, ArrayXXd> operator()(
const ArrayXXd& input,
const ArrayXXd& output) const = 0;
virtual pair<ArrayXXd, ArrayXXd> operator()(
const pair<ArrayXXd, ArrayXXd>& data) const;
virtual pair<ArrayXXd, ArrayXXd> inverse(
const ArrayXXd& input,
const ArrayXXd& output) const = 0;
virtual pair<ArrayXXd, ArrayXXd> inverse(
const pair<ArrayXXd, ArrayXXd>& data) const;
virtual ArrayXXd operator()(const ArrayXXd& input) const = 0;
virtual ArrayXXd inverse(const ArrayXXd& input) const = 0;
virtual Array<double, 1, Dynamic> logJacobian(
const ArrayXXd& input,
const ArrayXXd& output) const = 0;
virtual Array<double, 1, Dynamic> logJacobian(
const pair<ArrayXXd, ArrayXXd>& data) const;
virtual pair<ArrayXXd, ArrayXXd> adjustGradient(
const ArrayXXd& inputGradient,
const ArrayXXd& outputGradient) const = 0;
virtual pair<ArrayXXd, ArrayXXd> adjustGradient(
const pair<ArrayXXd, ArrayXXd>& dataGradient) const;
};
}
#endif
| {
"content_hash": "3868b25af193297423bcdb0a415444f0",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 64,
"avg_line_length": 28.851063829787233,
"alnum_prop": 0.7020648967551623,
"repo_name": "lucastheis/cmt",
"id": "fb8837b9b62607a978eb08d2ccc24fbc8cb1fc00",
"size": "1457",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "code/cmt/include/preconditioner.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "157487"
},
{
"name": "C++",
"bytes": "3657450"
},
{
"name": "CMake",
"bytes": "6810"
},
{
"name": "CSS",
"bytes": "15459"
},
{
"name": "Dockerfile",
"bytes": "599"
},
{
"name": "HTML",
"bytes": "20393"
},
{
"name": "MATLAB",
"bytes": "38255"
},
{
"name": "Makefile",
"bytes": "4379"
},
{
"name": "Python",
"bytes": "105242"
},
{
"name": "Shell",
"bytes": "706"
}
],
"symlink_target": ""
} |
using namespace gl;
namespace gloperate
{
CameraCollisionCapability::CameraCollisionCapability()
: m_fbo(nullptr)
, m_size(1024)
, m_samplingSize(1)
{
}
CameraCollisionCapability::~CameraCollisionCapability()
{
}
void CameraCollisionCapability::setCollisionFBO(globjects::ref_ptr<globjects::Framebuffer> collisionFBO, size_t texSize)
{
m_fbo = collisionFBO;
m_size = texSize;
}
void CameraCollisionCapability::setSamplingSize(size_t samplingSize)
{
m_samplingSize = samplingSize;
}
float CameraCollisionCapability::getDistance(const glm::vec3 &dir) const
{
if(!m_fbo)
{
return std::numeric_limits<float>::max();
}
float xAbs = std::abs(dir.x);
float yAbs = std::abs(dir.y);
float zAbs = std::abs(dir.z);
float main, u, v;
GLenum face;
if(xAbs == 0 && yAbs == 0 && zAbs == 0)
{
return std::numeric_limits<float>::max();
}
// Find the correct axis to sample
if(xAbs > yAbs && xAbs > zAbs)
{
face = GL_COLOR_ATTACHMENT0;
main = dir.x; u = -dir.z; v = -dir.y;
} else if(yAbs > zAbs)
{
auto sign = std::signbit(dir.y) ? -1 : 1;
face = GL_COLOR_ATTACHMENT2;
main = dir.y; u = dir.x; v = sign *dir.z;
} else
{
face = GL_COLOR_ATTACHMENT4;
main = dir.z; u = -dir.x; v = -dir.y;
}
// Find the correct orientation on this axis
face = face + static_cast<int>(std::signbit(main));
// Sample the coordinates
glm::vec2 uv{u/std::abs(main), v/std::abs(main)};
glm::ivec2 i_uv = uv * static_cast<float>(m_size/2)+static_cast<float>(m_size/2);
std::vector<glm::vec3> buf(m_samplingSize*m_samplingSize);
m_fbo->bind();
std::array<GLint,4> sampleRange{i_uv.x,i_uv.y,m_samplingSize,m_samplingSize};
m_fbo->readPixels(face, sampleRange,GL_RGB,GL_FLOAT,buf.data());
m_fbo->unbind();
return buf[0].x;
}
} // namespace gloperate
| {
"content_hash": "57e51fcc4909ba78aed16e2e8045cd68",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 120,
"avg_line_length": 22.705882352941178,
"alnum_prop": 0.6176165803108808,
"repo_name": "Beta-Alf/gloperate",
"id": "4880e9cb4f269edb11694e95fa58c6deff9df403",
"size": "2220",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/gloperate/source/painter/CameraCollisionCapability.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "33365"
},
{
"name": "C++",
"bytes": "4252836"
},
{
"name": "CMake",
"bytes": "128174"
},
{
"name": "GLSL",
"bytes": "10201"
},
{
"name": "JavaScript",
"bytes": "350"
},
{
"name": "M4",
"bytes": "25387"
},
{
"name": "Makefile",
"bytes": "25779"
},
{
"name": "Objective-C",
"bytes": "9308"
},
{
"name": "Python",
"bytes": "450989"
},
{
"name": "Shell",
"bytes": "26517"
}
],
"symlink_target": ""
} |
require 'test_helper'
class GamesControllerTest < ActionController::TestCase
test "should get index" do
get :index
assert_response :success
end
test "should get new" do
get :new
assert_response :success
end
test "should get create" do
get :create
assert_response :success
end
end
| {
"content_hash": "507287a9674dbf1b66ba3d24c564d60b",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 54,
"avg_line_length": 16.842105263157894,
"alnum_prop": 0.69375,
"repo_name": "kantoorwolven/kantoorwolven",
"id": "d387316f009088c027d0d6b6f16f3c24386dbbed",
"size": "320",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/controllers/games_controller_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1828"
},
{
"name": "CoffeeScript",
"bytes": "422"
},
{
"name": "Harbour",
"bytes": "8293"
},
{
"name": "JavaScript",
"bytes": "10116"
},
{
"name": "Ruby",
"bytes": "31217"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Analytico</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link href="app-content/app.css" rel="stylesheet" />
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.css" />
</head>
<body class="container">
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Analytico</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li ng-class="{active: activeTab === 'home'}"><a ui-sref="home"><i class="fa fa-home"></i> Home</a></li>
<li ng-class="{active: activeTab === 'account'}"><a ui-sref="account"><i class="fa fa-bars"></i> Account</a></li>
<li ng-class="{active: activeTab === 'analytics'}"><a ui-sref="analytics"><i class="fa fa-area-chart"></i> Analytics</a></li>
<li ng-class="{active: activeTab === 'community'}"><a ui-sref="community"><i class="fa fa-group"></i> Community</a></li>
<li ng-class="{active: activeTab === 'about'}"><a ui-sref="about"><i class="fa fa-shield"></i> About</a></li>
<li><a href="/login" target="_self"><i class="fa fa-sign-out"></i> Logout</a></li>
</ul>
</div>
</div>
</nav>
<div class="flash-message" ng-if="flash">
<div class="{{'alert alert-' + flash.type}}" ng-bind="flash.message"></div>
</div>
<!-- main -->
<main ui-view></main>
<!-- footer -->
<footer></footer>
<!-- external scripts -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.10.0/ui-bootstrap-tpls.min.js"></script>
<link rel="stylesheet" href="bower_components/angular-gridster/dist/angular-gridster.min.css"/>
<script src="bower_components/javascript-detect-element-resize/jquery.resize.js"></script>
<script src="bower_components/angular-gridster/dist/angular-gridster.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/data.js"></script>
<script src="https://code.highcharts.com/modules/drilldown.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/highcharts-3d.js"></script>
<!-- application scripts -->
<script src="app.js"></script>
<script src="app-services/user.service.js"></script>
<script src="app-services/flash.service.js"></script>
<script src="home/index.controller.js"></script>
<script src="account/index.controller.js"></script>
<script src="community/index.controller.js"></script>
<script src="analytics/index.controller.js"></script>
<script src="about/index.controller.js"></script>
</body>
</html> | {
"content_hash": "6f19850fe079091f073015a06500784d",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 216,
"avg_line_length": 57.75949367088607,
"alnum_prop": 0.6072759149682226,
"repo_name": "mishran1/analytico-app",
"id": "c29b13db29f50539d494985876eae63a049426c3",
"size": "4565",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "69128"
},
{
"name": "HTML",
"bytes": "51350"
},
{
"name": "JavaScript",
"bytes": "169915"
}
],
"symlink_target": ""
} |
( function( window ) {
'use strict';
var transEndEventNames = {
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'transitionend',
'OTransition': 'oTransitionEnd',
'msTransition': 'MSTransitionEnd',
'transition': 'transitionend'
},
transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ],
support = { transitions : Modernizr.csstransitions };
function extend( a, b ) {
for( var key in b ) {
if( b.hasOwnProperty( key ) ) {
a[key] = b[key];
}
}
return a;
}
function UIMorphingButton( el, options ) {
this.el = el;
console.log('el is: ' + el);
this.options = extend( {}, this.options );
extend( this.options, options );
this._init();
}
UIMorphingButton.prototype.options = {
closeEl : '',
onBeforeOpen : function() { return false; },
onAfterOpen : function() { return false; },
onBeforeClose : function() { return false; },
onAfterClose : function() { return false; }
}
UIMorphingButton.prototype._init = function(index) {
// the button
this.button = this.el.querySelector( 'button' );
// state
this.expanded = false;
// content el
this.contentEl = this.el.querySelector( '.morph-content' );
// init events
this._initEvents();
}
UIMorphingButton.prototype._initEvents = function() {
var self = this;
// open
this.button.addEventListener( 'click', function() { self.toggle(); } );
// close
if( this.options.closeEl !== '' ) {
var closeEl = this.el.querySelector( this.options.closeEl );
if( closeEl ) {
closeEl.addEventListener( 'click', function() { self.toggle(); } );
}
}
}
UIMorphingButton.prototype.toggle = function() {
if( this.isAnimating ) return false;
// callback
if( this.expanded ) {
this.options.onBeforeClose();
}
else {
// add class active (solves z-index problem when more than one button is in the page)
classie.addClass( this.el, 'active' );
this.options.onBeforeOpen();
}
this.isAnimating = true;
var self = this,
onEndTransitionFn = function( ev ) {
if( ev.target !== this ) return false;
if( support.transitions ) {
// open: first opacity then width/height/left/top
// close: first width/height/left/top then opacity
if( self.expanded && ev.propertyName !== 'opacity' || !self.expanded && ev.propertyName !== 'width' && ev.propertyName !== 'height' && ev.propertyName !== 'left' && ev.propertyName !== 'top' ) {
return false;
}
this.removeEventListener( transEndEventName, onEndTransitionFn );
}
self.isAnimating = false;
// callback
if( self.expanded ) {
// remove class active (after closing)
classie.removeClass( self.el, 'active' );
self.options.onAfterClose();
}
else {
self.options.onAfterOpen();
}
self.expanded = !self.expanded;
};
if( support.transitions ) {
this.contentEl.addEventListener( transEndEventName, onEndTransitionFn );
}
else {
onEndTransitionFn();
}
// set the left and top values of the contentEl (same like the button)
var buttonPos = this.button.getBoundingClientRect();
// need to reset
classie.addClass( this.contentEl, 'no-transition' );
this.contentEl.style.left = 'auto';
this.contentEl.style.top = 'auto';
// add/remove class "open" to the button wraper
setTimeout( function() {
self.contentEl.style.left = buttonPos.left + 'px';
self.contentEl.style.top = buttonPos.top + 'px';
if( self.expanded ) {
classie.removeClass( self.contentEl, 'no-transition' );
classie.removeClass( self.el, 'open' );
}
else {
setTimeout( function() {
classie.removeClass( self.contentEl, 'no-transition' );
classie.addClass( self.el, 'open' );
}, 25 );
}
}, 25 );
}
// add to global namespace
window.UIMorphingButton = UIMorphingButton;
})( window ); | {
"content_hash": "21afd05b7546fbd6c88a5032b54f2111",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 214,
"avg_line_length": 32.91095890410959,
"alnum_prop": 0.5180020811654527,
"repo_name": "EngineeringStudentCouncil/EngineeringStudentCouncil.github.io",
"id": "4596d60ac70e07a054be4414a8919be1dbbad357",
"size": "4805",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pj/2/js/ui-button-fixed.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "80576"
},
{
"name": "JavaScript",
"bytes": "148366"
}
],
"symlink_target": ""
} |
/**
* OperatingSystemVersion.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201508;
/**
* Represents a specific version of an operating system.
*/
public class OperatingSystemVersion extends com.google.api.ads.dfp.axis.v201508.Technology implements java.io.Serializable {
/* The operating system major version. */
private java.lang.Integer majorVersion;
/* The operating system minor version. */
private java.lang.Integer minorVersion;
/* The operating system micro version. */
private java.lang.Integer microVersion;
public OperatingSystemVersion() {
}
public OperatingSystemVersion(
java.lang.Long id,
java.lang.String name,
java.lang.Integer majorVersion,
java.lang.Integer minorVersion,
java.lang.Integer microVersion) {
super(
id,
name);
this.majorVersion = majorVersion;
this.minorVersion = minorVersion;
this.microVersion = microVersion;
}
/**
* Gets the majorVersion value for this OperatingSystemVersion.
*
* @return majorVersion * The operating system major version.
*/
public java.lang.Integer getMajorVersion() {
return majorVersion;
}
/**
* Sets the majorVersion value for this OperatingSystemVersion.
*
* @param majorVersion * The operating system major version.
*/
public void setMajorVersion(java.lang.Integer majorVersion) {
this.majorVersion = majorVersion;
}
/**
* Gets the minorVersion value for this OperatingSystemVersion.
*
* @return minorVersion * The operating system minor version.
*/
public java.lang.Integer getMinorVersion() {
return minorVersion;
}
/**
* Sets the minorVersion value for this OperatingSystemVersion.
*
* @param minorVersion * The operating system minor version.
*/
public void setMinorVersion(java.lang.Integer minorVersion) {
this.minorVersion = minorVersion;
}
/**
* Gets the microVersion value for this OperatingSystemVersion.
*
* @return microVersion * The operating system micro version.
*/
public java.lang.Integer getMicroVersion() {
return microVersion;
}
/**
* Sets the microVersion value for this OperatingSystemVersion.
*
* @param microVersion * The operating system micro version.
*/
public void setMicroVersion(java.lang.Integer microVersion) {
this.microVersion = microVersion;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof OperatingSystemVersion)) return false;
OperatingSystemVersion other = (OperatingSystemVersion) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj) &&
((this.majorVersion==null && other.getMajorVersion()==null) ||
(this.majorVersion!=null &&
this.majorVersion.equals(other.getMajorVersion()))) &&
((this.minorVersion==null && other.getMinorVersion()==null) ||
(this.minorVersion!=null &&
this.minorVersion.equals(other.getMinorVersion()))) &&
((this.microVersion==null && other.getMicroVersion()==null) ||
(this.microVersion!=null &&
this.microVersion.equals(other.getMicroVersion())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
if (getMajorVersion() != null) {
_hashCode += getMajorVersion().hashCode();
}
if (getMinorVersion() != null) {
_hashCode += getMinorVersion().hashCode();
}
if (getMicroVersion() != null) {
_hashCode += getMicroVersion().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(OperatingSystemVersion.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201508", "OperatingSystemVersion"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("majorVersion");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201508", "majorVersion"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("minorVersion");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201508", "minorVersion"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("microVersion");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201508", "microVersion"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| {
"content_hash": "517c47050d14322f4452466bdf49cac9",
"timestamp": "",
"source": "github",
"line_count": 206,
"max_line_length": 138,
"avg_line_length": 34.398058252427184,
"alnum_prop": 0.6346316680779001,
"repo_name": "shyTNT/googleads-java-lib",
"id": "f091e5149b0e910026090d38ba4c01e36c65f86d",
"size": "7086",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201508/OperatingSystemVersion.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "91011716"
}
],
"symlink_target": ""
} |
'use strict';
// Use local.env.js for environment variables that grunt will set when the server starts locally.
// Use for your api keys, secrets, etc. This file should not be tracked by git.
//
// You will need to set these on the server you deploy to.
module.exports = {
DOMAIN: 'http://localhost:9000',
SESSION_SECRET: '-secret',
FACEBOOK_ID: 'app-id',
FACEBOOK_SECRET: 'secret',
TWITTER_ID: 'app-id',
TWITTER_SECRET: 'secret',
REDISTOGO_URL:'redis://localhost:6379',
// Control debug level for modules using visionmedia/debug
DEBUG: ''
};
| {
"content_hash": "e34b8ea9ed023dd98f303b198a17ebf4",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 97,
"avg_line_length": 25.82608695652174,
"alnum_prop": 0.6632996632996633,
"repo_name": "seeReadCode/gotothelibrary.com",
"id": "08e828c9ab627506bae1b9a3b6d5c21582b8cb82",
"size": "594",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/config/local.env.sample.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2500"
},
{
"name": "CoffeeScript",
"bytes": "15690"
},
{
"name": "JavaScript",
"bytes": "63625"
}
],
"symlink_target": ""
} |
title: "Лекция 14. Unicode"
date: 2021-07-17
tags:
- lecture
category:
- pyneng-11
---
По этой теме нет заданий.
### Презентация
* [Unicode](https://github.com/pyneng/all-pyneng-slides/blob/main/pyneng/16_unicode.md)
### Соответствующие разделы в книге
* [Unicode](https://pyneng.readthedocs.io/ru/latest/book/16_unicode/index.html)
### Дополнительная информация
Материалы по Unicode:
1. 🐍 [Pragmatic Unicode](https://nedbatchelder.com/text/unipain.html)
2. 🦉 [The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)](https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/)
3. 🐍 [Unicode HOWTO](https://docs.python.org/3/howto/unicode.html)
### Следующая лекция
Для подготовки к лекции надо прочитать раздел: [17. Работа с файлами в формате CSV, JSON, YAML](https://pyneng.readthedocs.io/ru/latest/book/17_serialization/index.html)
| {
"content_hash": "dc9a3ac4c4a194a8f08004248abe6235",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 307,
"avg_line_length": 36.241379310344826,
"alnum_prop": 0.7611798287345385,
"repo_name": "pyneng/pyneng.github.io",
"id": "29f2a4c8b7aba4ec075100f0cecd8920f318d42b",
"size": "1231",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/pyneng-11/2021-07-17-lecture-14.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "65272"
},
{
"name": "JavaScript",
"bytes": "53349"
},
{
"name": "Python",
"bytes": "3073"
},
{
"name": "Ruby",
"bytes": "207"
},
{
"name": "SCSS",
"bytes": "65356"
}
],
"symlink_target": ""
} |
#import "NSObject.h"
@class NSArray, NSString, NSURL, SKUIArtworkList;
@interface SKUICategory : NSObject
{
SKUIArtworkList *_artworkList;
long long _categoryIdentifier;
NSArray *_children;
NSString *_name;
NSString *_parentLabel;
NSURL *_url;
}
@property(readonly, nonatomic) NSURL *URL; // @synthesize URL=_url;
@property(readonly, nonatomic) NSString *parentLabel; // @synthesize parentLabel=_parentLabel;
@property(readonly, nonatomic) NSString *name; // @synthesize name=_name;
@property(readonly, nonatomic) NSArray *children; // @synthesize children=_children;
@property(readonly, nonatomic) long long categoryIdentifier; // @synthesize categoryIdentifier=_categoryIdentifier;
@property(readonly, nonatomic) SKUIArtworkList *artworkList; // @synthesize artworkList=_artworkList;
- (void).cxx_destruct;
- (id)subcategoryContainingURL:(id)arg1;
- (_Bool)containsURL:(id)arg1;
- (id)initWithCategoryDictionary:(id)arg1;
@end
| {
"content_hash": "1da4adcf5daf5dfcbcd0e00e00c33fb7",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 115,
"avg_line_length": 33.10344827586207,
"alnum_prop": 0.7510416666666667,
"repo_name": "matthewsot/CocoaSharp",
"id": "63814686ec678f15472f1073427422235ef0b2fe",
"size": "1100",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Headers/PrivateFrameworks/StoreKitUI/SKUICategory.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "259784"
},
{
"name": "C#",
"bytes": "2789005"
},
{
"name": "C++",
"bytes": "252504"
},
{
"name": "Objective-C",
"bytes": "24301417"
},
{
"name": "Smalltalk",
"bytes": "167909"
}
],
"symlink_target": ""
} |
'use strict';
const { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
const { Runtime } = Cu.import('resource://qbrt/modules/Runtime.jsm', {});
const { Services } = Cu.import('resource://gre/modules/Services.jsm', {});
const SHELL_URL = 'chrome://app/content/shell.xul';
const WINDOW_FEATURES = [
'width=640',
'height=480',
'resizable',
'scrollbars',
].join(',');
// On startup, activate ourselves, since starting up from Node doesn't do this.
// TODO: do this by default for all apps started via Node.
if (Services.appinfo.OS === 'Darwin') {
Cc['@mozilla.org/widget/macdocksupport;1'].getService(Ci.nsIMacDockSupport).activateApplication(true);
}
const url = Runtime.commandLineArgs[0] || Runtime.packageJSON.mainURL || 'index.html';
const argument = Cc['@mozilla.org/supports-string;1'].createInstance(Ci.nsISupportsString);
argument.data = url;
// TODO: report error if URL isn't found.
Services.ww.openWindow(null, SHELL_URL, '_blank', WINDOW_FEATURES, argument);
| {
"content_hash": "08659ed04215825240c2f6cdb0ac2715",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 104,
"avg_line_length": 34.689655172413794,
"alnum_prop": 0.7067594433399602,
"repo_name": "mykmelez/qbrt",
"id": "455cb8fda00451c66284cc83fa3b27f2893e6d4a",
"size": "1592",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "shell/main.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "118"
},
{
"name": "HTML",
"bytes": "2199"
},
{
"name": "JavaScript",
"bytes": "97878"
},
{
"name": "Shell",
"bytes": "2844"
}
],
"symlink_target": ""
} |
package zergling_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Zergling", func() {
It("should pass", func(){
Expect("zergling").To(Equal("zergling"))
})
})
| {
"content_hash": "e51fc6a522dc0e2cdca5f20e99398a0d",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 42,
"avg_line_length": 17.166666666666668,
"alnum_prop": 0.6359223300970874,
"repo_name": "zergs/zergling",
"id": "e0f0d539d98e5706431c44fe66175a19349b5343",
"size": "206",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "zergling_test.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "403"
}
],
"symlink_target": ""
} |
THE_BASE_DIR_PATH=$(cd -P -- "$(dirname -- "$0")" && pwd -P)
source $THE_BASE_DIR_PATH/_init.sh
echo 'configure-undo input start:'
THE_SOURCE_FILE_PATH=$THE_BAK_DIR_PATH/org.freedesktop.ibus.gschema.ori.xml
THE_TARGET_FILE_PATH=/usr/share/glib-2.0/schemas/org.freedesktop.ibus.gschema.xml
sudo cp $THE_SOURCE_FILE_PATH $THE_TARGET_FILE_PATH -f
sudo glib-compile-schemas /usr/share/glib-2.0/schemas
| {
"content_hash": "0c14369c17805e02371a705ff242e6dd",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 81,
"avg_line_length": 33.583333333333336,
"alnum_prop": 0.7270471464019851,
"repo_name": "samwhelp/fix-ubuntu-1404",
"id": "4d4beb418068b542ac2073234531b4095340a47e",
"size": "424",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "main/app/input/bin/configure-undo.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "10163"
},
{
"name": "Shell",
"bytes": "51485"
}
],
"symlink_target": ""
} |
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| {
"content_hash": "843805ec40a51c8840f8ac7c061ba3fd",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 60,
"avg_line_length": 16.857142857142858,
"alnum_prop": 0.7796610169491526,
"repo_name": "PeakCheung/ios-dev-resources",
"id": "146bb615044aa7655514c08b616e95b617c5169b",
"size": "296",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "UIKit/UIProgressView/UIProgressViewDemo/UIProgressViewDemo/AppDelegate.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "194168"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Sphaerella etrusca Tognini
### Remarks
null | {
"content_hash": "a1dd0f9b2f38a9611376be0214d1bf05",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 26,
"avg_line_length": 10.076923076923077,
"alnum_prop": 0.7175572519083969,
"repo_name": "mdoering/backbone",
"id": "8f262bf7e6d18b9c80e1e91bb2e26cf470854e61",
"size": "181",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Sphaerella/Sphaerella etrusca/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
export default function addClassTo(classNames, string) {
if (string.charAt(1) === '/') { return string; }
const index = string.indexOf('class=');
const classString = classNames.join(' ');
if (index > -1) {
const indexEnd = index + 7;
return `${string.slice(0, indexEnd)}${classString} ${string.slice(indexEnd)}`;
} else {
return `${string.slice(0, -1)} class="${classString}">`;
}
}
| {
"content_hash": "ab36014005efdc07533df92c0c12bf85",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 82,
"avg_line_length": 29.285714285714285,
"alnum_prop": 0.6195121951219512,
"repo_name": "null-null-null/ember-letter-by-letter",
"id": "da9effd6ebad98e7690b578c438c7430ea4f7841",
"size": "410",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "addon/utils/add-class-to.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "23780"
},
{
"name": "HTML",
"bytes": "28944"
},
{
"name": "JavaScript",
"bytes": "64807"
}
],
"symlink_target": ""
} |
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Banshee.Cdrom
{
public enum RecorderResult
{
Error,
Canceled,
Finished,
Retry
}
}
| {
"content_hash": "b8bcc2eb5293ce4b739d790bd051bf2e",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 80,
"avg_line_length": 40.24242424242424,
"alnum_prop": 0.7221385542168675,
"repo_name": "google-code/banshee32",
"id": "e43df4bcc0593d819a088e17c90446fd84a549b4",
"size": "1592",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Banshee.Base/Cdrom/RecorderResult.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "2955061"
},
{
"name": "Inno Setup",
"bytes": "3967"
}
],
"symlink_target": ""
} |
package JSHOP2;
/** Each predicate, both at compile time and at run time, is an instance of
* this class.
*
* @author Okhtay Ilghami
* @author <a href="http://www.cs.umd.edu/~okhtay">http://www.cs.umd.edu/~okhtay</a>
* @version 1.0.3
*/
public class Predicate extends CompileTimeObject
{
/** The index of the constant symbol that is the head of this predicate.
*/
private int head;
/** The argument list of this predicate.
*/
private Term param;
/** The number of variables in this predicate. Used to return a binding of
* the appropriate size.
*/
private int varCount;
/** In case this predicate is a variable symbol and not a real atom, this
* represents its index. Otherwise, its value will be -1.
*/
private int varIdx;
/**
* A unique ID to identify this predicate. Used in conjunction with JSHOP2GUI to allow
* it to discern exactly which task atom is being referenced at every step of the plan
* finding process.
*/
private static int staticID = 0;
private int ID;
/** To initialize this predicate.
*
* @param headIn
* the head of the predicate.
* @param varCountIn
* number of the variables of the predicate.
* @param paramIn
* the argument list of the predicate.
*/
public Predicate(int headIn, int varCountIn, Term paramIn)
{
head = headIn;
varCount = varCountIn;
param = paramIn;
//-- This is a real predicate, so set 'varIdx' to -1.
varIdx = -1;
ID = staticID++;
}
/** To initialize this predicate when it is not a real predicate but a
* variable symbol.
*
* @param varIdxIn
* the index of the variable symbol that represents this predicate.
* @param varCountIn
* number of the variables of the predicate.
*/
public Predicate(int varIdxIn, int varCountIn)
{
head = -1;
varCount = varCountIn;
param = TermList.NIL;
varIdx = varIdxIn;
}
/** To apply a binding to this predicate.
*
* @param bindings
* the binding to be applied.
* @return
* the resulting predicate.
*/
public Predicate applySubstitution(Term[] bindings)
{
//-- If this predicate is a variable symbol,
if (isVar())
{
//-- If the variable symbol is not bound to anything, just return this
//-- predicate itself.
if (bindings[varIdx] == null)
return this;
//-- Find out the list this variable symbol is mapped to and make up the
//-- predicate out of that list.
return ((TermList)bindings[varIdx]).toPredicate(varCount);
}
//-- Apply the binding and return the result.
return new Predicate(head, varCount, param.bind(bindings));
}
/** Whether or not the argument list of another predicate is equal to the
* the argument list of this predicate.
*
* @param t
* the argument list of the other predicate.
* @return
* <code>true</code> if the two argument lists are equal,
* <code>false</code> otherwise.
*/
public boolean equals(Term t)
{
if (isVar())
return false;
return (param.equals(t));
}
/** To find a unifier that unifies the argument list of another predicate
* with the argument list of this predicate.
*
* @param t
* the argument list of the other predicate.
* @return
* the binding that unifies the two argument lists in case they are
* unifiable, <code>null</code> otherwise.
*/
public Term[] findUnifier(Term t)
{
//-- First, make an empty binding of the appropriate size.
Term[] retVal = new Term[varCount];
for (int i = 0; i < varCount; i++)
retVal[i] = null;
//-- If this predicate is a variable, just map the variable to the whole
//-- argument list and return.
if (isVar())
{
retVal[varIdx] = t;
return retVal;
}
if (param.findUnifier(t, retVal))
return retVal;
return null;
}
/** To get the head of this predicate.
*
* @return
* the head of this predicate.
*/
public int getHead()
{
//-- TODO: What to do when Predicate is a variable?
return head;
}
/** To get the parameter list of this predicate.
*
* @return
* the parameter list of this predicate.
*/
public Term getParam()
{
//-- TODO: What to do when Predicate is a variable?
return param;
}
/** To get the number of variables for this predicate.
*
* @return
* the number of variables for this predicate.
*/
public int getVarCount()
{
return varCount;
}
/** To check if this predicate is ground (i.e., has no variables).
*
* @return
* <code>true</code> if this predicate is ground, <code>false</code>
* otherwise.
*/
public boolean isGround()
{
if (isVar())
return false;
return param.isGround();
}
/** To check if this predicate is a variable symbol or a real predicate.
*
* @return
* <code>true</code> if this predicate is a variable symbol,
* <code>false</code> if it is a real predicate.
*/
public boolean isVar()
{
return (varIdx != -1);
}
/** This function is used to print this predicate.
*/
public void print()
{
System.out.println(this);
}
/** This function is used to print this predicate.
*
* @param constants
* what <code>String</code> should each constant symbol be mapped
* to.
*/
public void print(String[] constants)
{
System.out.println(toString(constants));
}
/** To set the number of variables for this predicate.
*
* @param varCountIn
* the number of variables for this predicate.
*/
public void setVarCount(int varCountIn)
{
varCount = varCountIn;
}
/** This function produces Java code to create this predicate.
*/
public String toCode()
{
if (isVar())
return "new Predicate(" + varIdx + ", " + varCount + ")";
return "new Predicate(" + head + ", " + varCount + ", " + param.toCode() + ")";
}
/** This function returns a printable <code>String</code> representation of
* this predicate. This function is used to print the predicates known to be
* logical atoms, because the indexes in this predicate representing
* constant symbols are mapped back by default to <code>String</code>
* representations of the constant symbols in logical atoms.
*
* @return
* the <code>String</code> representation of this predicate.
*/
public String toString()
{
//-- If this predicate is a variable symbol, just print it as a variable.
if (isVar())
return "VAR" + varIdx;
//-- Find out what the String representation of the head of this predicate
//-- is.
String s = "(" + JSHOP2.getDomain().getConstant(head);
//-- If the argument list is a list term (which it should be usually):
if (param instanceof TermList)
if (param.isNil())
//-- Converting (a . NIL) to (a).
return s + ")";
else
//-- Converting (a . (b)) to (a b).
return s + " " + ((TermList)param).getList() + ")";
//-- If the argument list is not a list term (which should not happen
//-- usually, but there is no reason to assume that it will not happen.
else
return s + "." + param + ")";
}
/** This function returns a printable <code>String</code> representation of
* this predicate. This function is used to print predicates other than
* logical atoms (such as task atoms).
*
* @param constants
* what <code>String</code> should each constant symbol be mapped
* to.
* @return
* the <code>String</code> representation of this predicate.
*/
public String toString(String[] constants)
{
//-- If this predicate is a variable symbol, just print it as a variable.
if (isVar())
return "VAR" + varIdx;
//-- First, make up the head of the predicate.
String s = "(" + constants[head];
//-- If the argument list is a list term (which it should be usually):
if (param instanceof TermList)
if (param.isNil())
//-- Converting (a . NIL) to (a).
return s + ")";
else
//-- Converting (a . (b)) to (a b).
return s + " " + ((TermList)param).getList() + ")";
else
//-- If the argument list is not a list term (which should not happen
//-- usually, but there is no reason to assume that it will not happen.
return s + "." + param + ")";
}
/**
* Returns the unique identifier for this predicate
* @return
* an integer representing the unique ID
*/
public int getID() {
return ID;
}
}
| {
"content_hash": "bbc99fd37e407e4a88e024c6f5050b73",
"timestamp": "",
"source": "github",
"line_count": 318,
"max_line_length": 89,
"avg_line_length": 27.60691823899371,
"alnum_prop": 0.6089531837339105,
"repo_name": "jormunmor/doctorado",
"id": "8ee76b3b906cf5407bd24ea69da2b8fb9c33a03e",
"size": "8779",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "JSHOP2/src/JSHOP2/Predicate.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2671"
},
{
"name": "C",
"bytes": "14433"
},
{
"name": "C#",
"bytes": "18659"
},
{
"name": "C++",
"bytes": "2923396"
},
{
"name": "CMake",
"bytes": "38809"
},
{
"name": "CSS",
"bytes": "949322"
},
{
"name": "GAP",
"bytes": "24568"
},
{
"name": "HTML",
"bytes": "62229389"
},
{
"name": "Java",
"bytes": "2437530"
},
{
"name": "JavaScript",
"bytes": "8047306"
},
{
"name": "Makefile",
"bytes": "293709"
},
{
"name": "Objective-C++",
"bytes": "7535732"
},
{
"name": "PostScript",
"bytes": "13039"
},
{
"name": "Python",
"bytes": "4330"
},
{
"name": "QMake",
"bytes": "5527"
},
{
"name": "Shell",
"bytes": "2037"
},
{
"name": "TeX",
"bytes": "2066789"
}
],
"symlink_target": ""
} |
<?php
namespace PHPExiftool\Driver\Tag\XMPAux;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class FlashCompensation extends AbstractTag
{
protected $Id = 'FlashCompensation';
protected $Name = 'FlashCompensation';
protected $FullName = 'XMP::aux';
protected $GroupName = 'XMP-aux';
protected $g0 = 'XMP';
protected $g1 = 'XMP-aux';
protected $g2 = 'Camera';
protected $Type = 'rational';
protected $Writable = true;
protected $Description = 'Flash Compensation';
}
| {
"content_hash": "60c9d500b5f578590c7901c68a5d91d8",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 50,
"avg_line_length": 16.5,
"alnum_prop": 0.6734006734006734,
"repo_name": "bburnichon/PHPExiftool",
"id": "e6722e80089d29e4c3c607732d0da31cc5c5ed5d",
"size": "818",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/PHPExiftool/Driver/Tag/XMPAux/FlashCompensation.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "22076400"
}
],
"symlink_target": ""
} |
Copyright (c) 2014, Daniel Shields
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| {
"content_hash": "c7c4a97d9b70f1e2ab3325b1f8ce7429",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 80,
"avg_line_length": 56.391304347826086,
"alnum_prop": 0.812644564379337,
"repo_name": "shieldsd/SmartStatusPlay",
"id": "540bffbad347724d4c8d6601602c2fb0578b39de",
"size": "1297",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LICENSE.md",
"mode": "33188",
"license": "bsd-2-clause",
"language": [],
"symlink_target": ""
} |
<?php
/**
*
* This file is part of the Apix Project.
*
* (c) Franck Cassedanne <franck at ouarz.net>
*
* @license http://opensource.org/licenses/BSD-3-Clause New BSD License
*
*/
namespace Apix\Cache\tests\Serializer;
use Apix\Cache\Serializer\Stringset;
class StringsetTest extends TestCase
{
public function setUp()
{
$this->formatter = new Stringset();
}
public function serializerProvider()
{
return array(
array(array('a', 'b', 'c'), 'a b c '),
array(array('juju', 'molly', 'loulou'), 'juju molly loulou '),
array(array('a-b', 'c', 'd'), 'a-b c d '),
array(array(), ''),
array(null, '')
);
}
/**
* @dataProvider serializerProvider
*/
public function testSerialize($arr, $str)
{
$this->assertEquals( $str, $this->formatter->serialize($arr) );
}
public function unserializerProvider()
{
return array(
array(array('a', 'b', 'c'), 'a b c ', 0),
array(array('a', 'c'), 'a b c -b -x ', 2),
array(array('c'), 'a b c -b -x -a', 3),
array(null, 'a -a', 1)
);
}
/**
* @dataProvider unserializerProvider
*/
public function testUnserializer($arr, $str, $dirt)
{
$this->assertEquals($arr, $this->formatter->unserialize($str));
$this->assertEquals($dirt, $this->formatter->getDirtiness());
}
public function isSerializerProvider()
{
return array(
array(array('a', 'b', 'c'), 'a b c '),
array(array('juju', 'molly', 'loulou'), 'juju molly loulou '),
array(array('a-b', 'c', 'd'), 'a-b c d ')
);
}
/**
* @dataProvider isSerializerProvider
*/
public function testIsSerialized($arr, $str)
{
$this->assertFalse($this->formatter->isSerialized($arr));
$this->assertTrue($this->formatter->isSerialized($str));
}
}
| {
"content_hash": "f192a656c5b925265824668349cb306a",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 76,
"avg_line_length": 24.85,
"alnum_prop": 0.528169014084507,
"repo_name": "jspalink/apix-cache",
"id": "f3944c54eaa0235ecfe0d33d79ebe89963ddd2fa",
"size": "1988",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/Serializer/StringsetTest.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "164244"
},
{
"name": "Shell",
"bytes": "1347"
}
],
"symlink_target": ""
} |
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use App\Models\TravelDocument;
class UpdateTravelDocumentRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return TravelDocument::$rules;
}
}
| {
"content_hash": "1ffb34d7fe016f413ff4479b621c4d9a",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 64,
"avg_line_length": 17.6,
"alnum_prop": 0.6212121212121212,
"repo_name": "rekale/gio",
"id": "91bd80ec68c07f639ea0dcc5ff1a09423572231c",
"size": "528",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/Http/Requests/Admin/UpdateTravelDocumentRequest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "553"
},
{
"name": "HTML",
"bytes": "75704"
},
{
"name": "PHP",
"bytes": "143121"
},
{
"name": "Vue",
"bytes": "563"
}
],
"symlink_target": ""
} |
package com.scheible.risingempire.game.core.star;
import java.util.ArrayList;
/**
*
* @author sj
*/
public class Stars extends ArrayList<Star> {
public Star getByName(String star) {
for(Star currentStar : this) {
if(currentStar.getName().equals(star)) {
return currentStar;
}
}
throw new IllegalStateException("The star '" + star + "' is unknown!");
}
}
| {
"content_hash": "85636a200c595cdff33bb89775d2bab8",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 73,
"avg_line_length": 19.1,
"alnum_prop": 0.6701570680628273,
"repo_name": "janScheible/rising-empire",
"id": "f9a9b672f4b8119e624f7cc4e0948aebee07802c",
"size": "382",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/scheible/risingempire/game/core/star/Stars.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "3299"
},
{
"name": "Java",
"bytes": "52987"
},
{
"name": "JavaScript",
"bytes": "204147"
},
{
"name": "TypeScript",
"bytes": "20033"
}
],
"symlink_target": ""
} |
CREATE SEQUENCE SqlTest.[Table04Sequence]
AS int
START WITH 1
INCREMENT BY 1
NO MAXVALUE
NO CYCLE
CACHE 10
| {
"content_hash": "be19394f91f78a03317d5e80ae04c769",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 42,
"avg_line_length": 18.142857142857142,
"alnum_prop": 0.6850393700787402,
"repo_name": "isoquark/isocore.data",
"id": "5cc5767a327e7db6a4b40dfa562b8093c146dd75",
"size": "129",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "IQ.Schemas.Test/SqlTest/Sequences/Table04Sequence.sql",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1707"
},
{
"name": "C#",
"bytes": "12962"
},
{
"name": "F#",
"bytes": "713290"
},
{
"name": "PLSQL",
"bytes": "27433"
},
{
"name": "PLpgSQL",
"bytes": "2248"
},
{
"name": "SQLPL",
"bytes": "295"
}
],
"symlink_target": ""
} |
namespace Analytics
{
partial class Analytics
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Username = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.Password = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.ProfileIds = new System.Windows.Forms.ListView();
this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
this.label3 = new System.Windows.Forms.Label();
this.Go = new System.Windows.Forms.Button();
this.label4 = new System.Windows.Forms.Label();
this.columnHeader3 = new System.Windows.Forms.ColumnHeader();
this.columnHeader4 = new System.Windows.Forms.ColumnHeader();
this.GetPageviews = new System.Windows.Forms.Button();
this.ListPageviews = new System.Windows.Forms.ListView();
this.SuspendLayout();
//
// Username
//
this.Username.Location = new System.Drawing.Point(16, 38);
this.Username.Name = "Username";
this.Username.Size = new System.Drawing.Size(119, 20);
this.Username.TabIndex = 0;
this.Username.Text = "sample@gmail.com";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(13, 20);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(55, 13);
this.label1.TabIndex = 1;
this.label1.Text = "Username";
//
// Password
//
this.Password.Location = new System.Drawing.Point(158, 38);
this.Password.Name = "Password";
this.Password.PasswordChar = '*';
this.Password.Size = new System.Drawing.Size(119, 20);
this.Password.TabIndex = 2;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(155, 20);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(53, 13);
this.label2.Text = "Password";
//
// ProfileIds
//
this.ProfileIds.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader2});
this.ProfileIds.FullRowSelect = true;
this.ProfileIds.GridLines = true;
this.ProfileIds.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.ProfileIds.Location = new System.Drawing.Point(16, 135);
this.ProfileIds.Name = "ProfileIds";
this.ProfileIds.Size = new System.Drawing.Size(300, 135);
this.ProfileIds.TabIndex = 4;
this.ProfileIds.UseCompatibleStateImageBehavior = false;
this.ProfileIds.View = System.Windows.Forms.View.Details;
//
// columnHeader1
//
this.columnHeader1.Text = "Title";
this.columnHeader1.Width = 150;
//
// columnHeader2
//
this.columnHeader2.Text = "Profile ID";
this.columnHeader2.Width = 125;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(13, 113);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(53, 13);
this.label3.Text = "Profile Ids";
//
// Go
//
this.Go.Location = new System.Drawing.Point(16, 65);
this.Go.Name = "Go";
this.Go.Size = new System.Drawing.Size(75, 23);
this.Go.TabIndex = 3;
this.Go.Text = "Get Profiles";
this.Go.UseVisualStyleBackColor = true;
this.Go.Click += new System.EventHandler(this.Go_Click);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(389, 113);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(59, 13);
this.label4.Text = "Pageviews";
//
// columnHeader3
//
this.columnHeader3.Text = "Title";
this.columnHeader3.Width = 150;
//
// columnHeader4
//
this.columnHeader4.Text = "Pageviews";
this.columnHeader4.Width = 125;
//
// GetPageviews
//
this.GetPageviews.Location = new System.Drawing.Point(16, 278);
this.GetPageviews.Name = "GetPageviews";
this.GetPageviews.Size = new System.Drawing.Size(96, 23);
this.GetPageviews.TabIndex = 5;
this.GetPageviews.Text = "Get Pageviews";
this.GetPageviews.UseVisualStyleBackColor = true;
this.GetPageviews.Click += new System.EventHandler(this.GoGet_Click);
//
// ListPageviews
//
this.ListPageviews.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader3,
this.columnHeader4});
this.ListPageviews.FullRowSelect = true;
this.ListPageviews.GridLines = true;
this.ListPageviews.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.ListPageviews.Location = new System.Drawing.Point(392, 135);
this.ListPageviews.Name = "ListPageviews";
this.ListPageviews.Size = new System.Drawing.Size(300, 135);
this.ListPageviews.UseCompatibleStateImageBehavior = false;
this.ListPageviews.View = System.Windows.Forms.View.Details;
//
// Analytics
//
this.ClientSize = new System.Drawing.Size(794, 313);
this.Controls.Add(this.GetPageviews);
this.Controls.Add(this.label4);
this.Controls.Add(this.ListPageviews);
this.Controls.Add(this.Go);
this.Controls.Add(this.label3);
this.Controls.Add(this.ProfileIds);
this.Controls.Add(this.label2);
this.Controls.Add(this.Password);
this.Controls.Add(this.label1);
this.Controls.Add(this.Username);
this.Name = "Analytics";
this.Text = "Google Analytics Demo Application";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox Username;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox Password;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ListView ProfileIds;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button Go;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.ListView ListPageviews;
private System.Windows.Forms.ColumnHeader columnHeader3;
private System.Windows.Forms.ColumnHeader columnHeader4;
private System.Windows.Forms.Button GetPageviews;
}
}
| {
"content_hash": "b521aaf71aef4a5ee9ab288f89060774",
"timestamp": "",
"source": "github",
"line_count": 202,
"max_line_length": 107,
"avg_line_length": 43.01485148514851,
"alnum_prop": 0.5534583956726896,
"repo_name": "david-mitchell/MonoMac-Demo",
"id": "453a231e3a1c615975caeee6fe1c440832c096ca",
"size": "8689",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "libgoogle-data-mono-1.7.0.1/samples/analytics/analytics.Designer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "15689"
},
{
"name": "C#",
"bytes": "4609569"
},
{
"name": "Python",
"bytes": "6338"
},
{
"name": "Shell",
"bytes": "10500"
},
{
"name": "Visual Basic",
"bytes": "16520"
}
],
"symlink_target": ""
} |
import unittest
from flask import current_app
from app import create_app, db
class BasicsTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_context.pop()
def test_app_exists(self):
self.assertFalse(current_app is None)
def test_app_is_testing(self):
self.assertTrue(current_app.config['TESTING'])
| {
"content_hash": "25deec4b6a211ee1fd4178be8a96590c",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 54,
"avg_line_length": 24.695652173913043,
"alnum_prop": 0.6338028169014085,
"repo_name": "sharkspeed/dororis",
"id": "0bcdc171ce439a2902d2259a8907fefbd493b79c",
"size": "616",
"binary": false,
"copies": "2",
"ref": "refs/heads/dev",
"path": "packages/python/flask/flask-dog-book/8-chapter/tests/test_basics.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Agda",
"bytes": "152"
},
{
"name": "AppleScript",
"bytes": "4936"
},
{
"name": "Assembly",
"bytes": "6654"
},
{
"name": "C",
"bytes": "568507"
},
{
"name": "C#",
"bytes": "2446"
},
{
"name": "C++",
"bytes": "15567"
},
{
"name": "CSS",
"bytes": "74090"
},
{
"name": "Clojure",
"bytes": "986"
},
{
"name": "CoffeeScript",
"bytes": "1055"
},
{
"name": "Crystal",
"bytes": "13171"
},
{
"name": "Dart",
"bytes": "22343"
},
{
"name": "Elixir",
"bytes": "27938"
},
{
"name": "Fortran",
"bytes": "400"
},
{
"name": "Go",
"bytes": "117383"
},
{
"name": "HTML",
"bytes": "780346"
},
{
"name": "Haskell",
"bytes": "33977"
},
{
"name": "Idris",
"bytes": "167"
},
{
"name": "Java",
"bytes": "105613"
},
{
"name": "JavaScript",
"bytes": "1453348"
},
{
"name": "Kotlin",
"bytes": "24078"
},
{
"name": "Lex",
"bytes": "1156"
},
{
"name": "Makefile",
"bytes": "22596"
},
{
"name": "Mako",
"bytes": "1976"
},
{
"name": "Objective-C",
"bytes": "1500"
},
{
"name": "PHP",
"bytes": "868941"
},
{
"name": "Python",
"bytes": "553417"
},
{
"name": "Racket",
"bytes": "11698"
},
{
"name": "Roff",
"bytes": "3741"
},
{
"name": "Ruby",
"bytes": "129923"
},
{
"name": "Rust",
"bytes": "27692"
},
{
"name": "Scala",
"bytes": "791"
},
{
"name": "Shell",
"bytes": "17297"
},
{
"name": "Smarty",
"bytes": "421"
},
{
"name": "Swift",
"bytes": "197600"
},
{
"name": "TeX",
"bytes": "3875"
},
{
"name": "TypeScript",
"bytes": "24815"
},
{
"name": "Vim script",
"bytes": "6936"
},
{
"name": "Vue",
"bytes": "32921"
},
{
"name": "Zig",
"bytes": "634"
}
],
"symlink_target": ""
} |
package dht
import (
"context"
"fmt"
"testing"
"time"
tu "github.com/libp2p/go-libp2p-testing/etc"
"github.com/stretchr/testify/require"
)
// TODO Debug test failures due to timing issue on windows
// Tests are timing dependent as can be seen in the 2 seconds timed context that we use in "tu.WaitFor".
// While the tests work fine on OSX and complete in under a second,
// they repeatedly fail to complete in the stipulated time on Windows.
// However, increasing the timeout makes them pass on Windows.
func TestRTEvictionOnFailedQuery(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
d1 := setupDHT(ctx, t, false)
d2 := setupDHT(ctx, t, false)
for i := 0; i < 10; i++ {
connect(t, ctx, d1, d2)
for _, conn := range d1.host.Network().ConnsToPeer(d2.self) {
conn.Close()
}
}
// peers should be in the RT because of fixLowPeers
require.NoError(t, tu.WaitFor(ctx, func() error {
if !checkRoutingTable(d1, d2) {
return fmt.Errorf("should have routes")
}
return nil
}))
// close both hosts so query fails
require.NoError(t, d1.host.Close())
require.NoError(t, d2.host.Close())
// peers will still be in the RT because we have decoupled membership from connectivity
require.NoError(t, tu.WaitFor(ctx, func() error {
if !checkRoutingTable(d1, d2) {
return fmt.Errorf("should have routes")
}
return nil
}))
// failed queries should remove the peers from the RT
_, err := d1.GetClosestPeers(ctx, "test")
require.NoError(t, err)
_, err = d2.GetClosestPeers(ctx, "test")
require.NoError(t, err)
require.NoError(t, tu.WaitFor(ctx, func() error {
if checkRoutingTable(d1, d2) {
return fmt.Errorf("should not have routes")
}
return nil
}))
}
func TestRTAdditionOnSuccessfulQuery(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
d1 := setupDHT(ctx, t, false)
d2 := setupDHT(ctx, t, false)
d3 := setupDHT(ctx, t, false)
connect(t, ctx, d1, d2)
connect(t, ctx, d2, d3)
// validate RT states
// d1 has d2
require.NoError(t, tu.WaitFor(ctx, func() error {
if !checkRoutingTable(d1, d2) {
return fmt.Errorf("should have routes")
}
return nil
}))
// d2 has d3
require.NoError(t, tu.WaitFor(ctx, func() error {
if !checkRoutingTable(d2, d3) {
return fmt.Errorf("should have routes")
}
return nil
}))
// however, d1 does not know about d3
require.NoError(t, tu.WaitFor(ctx, func() error {
if checkRoutingTable(d1, d3) {
return fmt.Errorf("should not have routes")
}
return nil
}))
// but when d3 queries d2, d1 and d3 discover each other
_, err := d3.GetClosestPeers(ctx, "something")
require.NoError(t, err)
require.NoError(t, tu.WaitFor(ctx, func() error {
if !checkRoutingTable(d1, d3) {
return fmt.Errorf("should have routes")
}
return nil
}))
}
func checkRoutingTable(a, b *IpfsDHT) bool {
// loop until connection notification has been received.
// under high load, this may not happen as immediately as we would like.
return a.routingTable.Find(b.self) != "" && b.routingTable.Find(a.self) != ""
}
| {
"content_hash": "85eafdadef29d321968134c5acbdd04b",
"timestamp": "",
"source": "github",
"line_count": 118,
"max_line_length": 105,
"avg_line_length": 26.635593220338983,
"alnum_prop": 0.6859688195991092,
"repo_name": "libp2p/go-libp2p-kad-dht",
"id": "e79af514fbef7f0060721b9036bf7653268b2dd9",
"size": "3143",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "query_test.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "353385"
},
{
"name": "Makefile",
"bytes": "175"
}
],
"symlink_target": ""
} |
<?php
require_once('../php_image_magician.php');
/* Purpose: Open image
* Usage: resize('filename.type')
* Params: filename.type - the filename to open
*/
$magicianObj = new imageLib('sample_images/racecar.jpg');
/* Purpose: Convert image to a negative
* Usage: negative()
* Params: n/a
*/
$magicianObj -> negative();
/* Purpose: Save image
* Usage: saveImage('[filename.type]', [quality])
* Params: filename.type - the filename and file type to save as
* quality - (optional) 0-100 (100 being the highest (default))
* Only applies to jpg & png only
*/
$magicianObj -> saveImage('output_2.6.png', 100);
?>
| {
"content_hash": "9930ad7922057cdd43fb25506f6a8e94",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 70,
"avg_line_length": 25.51851851851852,
"alnum_prop": 0.6081277213352685,
"repo_name": "santuchal/kuber_gemological_lab_private_web_app",
"id": "414061b8e27bf1c0c645b9818987ba1fd951e10a",
"size": "689",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "Application/Login/php-image-magician/examples/2.6_negative.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "126"
},
{
"name": "CSS",
"bytes": "360498"
},
{
"name": "HTML",
"bytes": "256182"
},
{
"name": "JavaScript",
"bytes": "214563"
},
{
"name": "PHP",
"bytes": "2707938"
},
{
"name": "Shell",
"bytes": "150"
}
],
"symlink_target": ""
} |
package components
import (
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"fmt"
"reflect"
"sort"
"time"
k8sv1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"kubevirt.io/client-go/log"
v1 "kubevirt.io/client-go/api/v1"
"kubevirt.io/kubevirt/pkg/certificates/bootstrap"
"kubevirt.io/kubevirt/pkg/certificates/triple"
"kubevirt.io/kubevirt/pkg/certificates/triple/cert"
)
const (
KubeVirtCASecretName = "kubevirt-ca"
VirtHandlerCertSecretName = "kubevirt-virt-handler-certs"
VirtHandlerServerCertSecretName = "kubevirt-virt-handler-server-certs"
VirtOperatorCertSecretName = "kubevirt-operator-certs"
VirtApiCertSecretName = "kubevirt-virt-api-certs"
VirtControllerCertSecretName = "kubevirt-controller-certs"
CABundleKey = "ca-bundle"
localPodDNStemplateString = "%s.%s.pod.cluster.local"
caClusterLocal = "cluster.local"
)
type CertificateCreationCallback func(secret *k8sv1.Secret, caCert *tls.Certificate, duration time.Duration) (cert *x509.Certificate, key *rsa.PrivateKey)
var populationStrategy = map[string]CertificateCreationCallback{
KubeVirtCASecretName: func(secret *k8sv1.Secret, _ *tls.Certificate, duration time.Duration) (cert *x509.Certificate, key *rsa.PrivateKey) {
caKeyPair, _ := triple.NewCA("kubevirt.io", duration)
return caKeyPair.Cert, caKeyPair.Key
},
VirtOperatorCertSecretName: func(secret *k8sv1.Secret, caCert *tls.Certificate, duration time.Duration) (cert *x509.Certificate, key *rsa.PrivateKey) {
caKeyPair := &triple.KeyPair{
Key: caCert.PrivateKey.(*rsa.PrivateKey),
Cert: caCert.Leaf,
}
keyPair, _ := triple.NewServerKeyPair(
caKeyPair,
fmt.Sprintf(localPodDNStemplateString, VirtOperatorServiceName, secret.Namespace),
VirtOperatorServiceName,
secret.Namespace,
caClusterLocal,
nil,
nil,
duration,
)
return keyPair.Cert, keyPair.Key
},
VirtApiCertSecretName: func(secret *k8sv1.Secret, caCert *tls.Certificate, duration time.Duration) (cert *x509.Certificate, key *rsa.PrivateKey) {
caKeyPair := &triple.KeyPair{
Key: caCert.PrivateKey.(*rsa.PrivateKey),
Cert: caCert.Leaf,
}
keyPair, _ := triple.NewServerKeyPair(
caKeyPair,
fmt.Sprintf(localPodDNStemplateString, VirtApiServiceName, secret.Namespace),
VirtApiServiceName,
secret.Namespace,
caClusterLocal,
nil,
nil,
duration,
)
return keyPair.Cert, keyPair.Key
},
VirtControllerCertSecretName: func(secret *k8sv1.Secret, caCert *tls.Certificate, duration time.Duration) (cert *x509.Certificate, key *rsa.PrivateKey) {
caKeyPair := &triple.KeyPair{
Key: caCert.PrivateKey.(*rsa.PrivateKey),
Cert: caCert.Leaf,
}
keyPair, _ := triple.NewServerKeyPair(
caKeyPair,
fmt.Sprintf(localPodDNStemplateString, VirtControllerServiceName, secret.Namespace),
VirtControllerServiceName,
secret.Namespace,
caClusterLocal,
nil,
nil,
duration,
)
return keyPair.Cert, keyPair.Key
},
VirtHandlerServerCertSecretName: func(secret *k8sv1.Secret, caCert *tls.Certificate, duration time.Duration) (cert *x509.Certificate, key *rsa.PrivateKey) {
caKeyPair := &triple.KeyPair{
Key: caCert.PrivateKey.(*rsa.PrivateKey),
Cert: caCert.Leaf,
}
keyPair, _ := triple.NewServerKeyPair(
caKeyPair,
"kubevirt.io:system:node:virt-handler",
VirtHandlerServiceName,
secret.Namespace,
caClusterLocal,
nil,
nil,
duration,
)
return keyPair.Cert, keyPair.Key
},
VirtHandlerCertSecretName: func(secret *k8sv1.Secret, caCert *tls.Certificate, duration time.Duration) (cert *x509.Certificate, key *rsa.PrivateKey) {
caKeyPair := &triple.KeyPair{
Key: caCert.PrivateKey.(*rsa.PrivateKey),
Cert: caCert.Leaf,
}
clientKeyPair, _ := triple.NewClientKeyPair(caKeyPair,
"kubevirt.io:system:client:virt-handler",
nil,
duration,
)
return clientKeyPair.Cert, clientKeyPair.Key
},
}
func PopulateSecretWithCertificate(secret *k8sv1.Secret, caCert *tls.Certificate, duration *metav1.Duration) (err error) {
strategy, ok := populationStrategy[secret.Name]
if !ok {
return fmt.Errorf("no certificate population strategy found for secret")
}
crt, certKey := strategy(secret, caCert, duration.Duration)
secret.Data = map[string][]byte{
bootstrap.CertBytesValue: cert.EncodeCertPEM(crt),
bootstrap.KeyBytesValue: cert.EncodePrivateKeyPEM(certKey),
}
if secret.Annotations == nil {
secret.Annotations = map[string]string{}
}
secret.Annotations["kubevirt.io/duration"] = duration.String()
return nil
}
func NewCACertSecret(operatorNamespace string) *k8sv1.Secret {
return &k8sv1.Secret{
TypeMeta: metav1.TypeMeta{
Kind: "Secret",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: KubeVirtCASecretName,
Namespace: operatorNamespace,
Labels: map[string]string{
v1.ManagedByLabel: v1.ManagedByLabelOperatorValue,
},
},
Type: "Opaque",
}
}
func NewKubeVirtCAConfigMap(operatorNamespace string) *k8sv1.ConfigMap {
return &k8sv1.ConfigMap{
TypeMeta: metav1.TypeMeta{
Kind: "ConfigMap",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: KubeVirtCASecretName,
Namespace: operatorNamespace,
Labels: map[string]string{
v1.ManagedByLabel: v1.ManagedByLabelOperatorValue,
},
},
}
}
func NewCertSecrets(installNamespace string, operatorNamespace string) []*k8sv1.Secret {
secrets := []*k8sv1.Secret{
{
TypeMeta: metav1.TypeMeta{
Kind: "Secret",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: VirtApiCertSecretName,
Namespace: installNamespace,
Labels: map[string]string{
v1.ManagedByLabel: v1.ManagedByLabelOperatorValue,
},
},
Type: "Opaque",
},
{
TypeMeta: metav1.TypeMeta{
Kind: "Secret",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: VirtControllerCertSecretName,
Namespace: installNamespace,
Labels: map[string]string{
v1.ManagedByLabel: v1.ManagedByLabelOperatorValue,
},
},
Type: "Opaque",
},
{
TypeMeta: metav1.TypeMeta{
Kind: "Secret",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: VirtHandlerServerCertSecretName,
Namespace: installNamespace,
Labels: map[string]string{
v1.ManagedByLabel: v1.ManagedByLabelOperatorValue,
},
},
Type: "Opaque",
},
{
TypeMeta: metav1.TypeMeta{
Kind: "Secret",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: VirtHandlerCertSecretName,
Namespace: installNamespace,
Labels: map[string]string{
v1.ManagedByLabel: v1.ManagedByLabelOperatorValue,
},
},
Type: "Opaque",
},
{
TypeMeta: metav1.TypeMeta{
Kind: "Secret",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: VirtOperatorCertSecretName,
Namespace: operatorNamespace,
Labels: map[string]string{
v1.ManagedByLabel: v1.ManagedByLabelOperatorValue,
},
},
Type: "Opaque",
},
}
return secrets
}
// nextRotationDeadline returns a value for the threshold at which the
// current certificate should be rotated, 80% of the expiration of the
// certificate.
func NextRotationDeadline(cert *tls.Certificate, ca *tls.Certificate, renewBefore *metav1.Duration, caRenewBefore *metav1.Duration) time.Time {
if cert == nil {
return time.Now()
}
if ca != nil {
certPool := x509.NewCertPool()
certPool.AddCert(ca.Leaf)
_, err := cert.Leaf.Verify(x509.VerifyOptions{
Roots: certPool,
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
})
if err != nil {
log.DefaultLogger().Reason(err).Infof("The certificate with common name '%s' is not signed with the supplied CA. Triggering a rotation.", cert.Leaf.Subject.CommonName)
return time.Now()
}
}
certNotAfter := cert.Leaf.NotAfter
deadline := cert.Leaf.NotAfter.Add(-renewBefore.Duration)
if ca != nil {
caNotAfter := ca.Leaf.NotAfter
if caNotAfter.Before(certNotAfter) {
log.DefaultLogger().Infof("The certificate with common name '%s' expires after the supplied CA does. Scheduling rotation based on CA's lifetime.", cert.Leaf.Subject.CommonName)
deadline = caNotAfter
if caRenewBefore != nil {
// Set cert rotation for the middle of the period of time when CA's overlap
deadline = caNotAfter.Add(-time.Duration(float64(caRenewBefore.Duration) * 0.5))
}
}
}
log.DefaultLogger().V(4).Infof("Certificate with common name '%s' expiration is %v, rotation deadline is %v", cert.Leaf.Subject.CommonName, certNotAfter, deadline)
return deadline
}
func ValidateSecret(secret *k8sv1.Secret) error {
if _, ok := secret.Data[bootstrap.CertBytesValue]; !ok {
return fmt.Errorf("%s value not found in %s secret\n", bootstrap.CertBytesValue, secret.Name)
}
if _, ok := secret.Data[bootstrap.KeyBytesValue]; !ok {
return fmt.Errorf("%s value not found in %s secret\n", bootstrap.KeyBytesValue, secret.Name)
}
return nil
}
func LoadCertificates(secret *k8sv1.Secret) (serverCrt *tls.Certificate, err error) {
if err := ValidateSecret(secret); err != nil {
return nil, err
}
crt, err := tls.X509KeyPair(secret.Data[bootstrap.CertBytesValue], secret.Data[bootstrap.KeyBytesValue])
if err != nil {
return nil, fmt.Errorf("failed to load certificate: %v\n", err)
}
leaf, err := cert.ParseCertsPEM(secret.Data[bootstrap.CertBytesValue])
if err != nil {
return nil, fmt.Errorf("failed to load leaf certificate: %v\n", err)
}
crt.Leaf = leaf[0]
return &crt, nil
}
func MergeCABundle(currentCert *tls.Certificate, currentBundle []byte, overlapDuration time.Duration) ([]byte, int, error) {
current := cert.EncodeCertPEM(currentCert.Leaf)
certs, err := cert.ParseCertsPEM(currentBundle)
if err != nil {
return nil, 0, err
}
// ensure that no one does something nasty and adds thousands of certs
if len(certs) > 10 {
certs = certs[:10]
}
now := time.Now()
var newBundle []byte
// To ensure that no one messes this up, sort
// We want the newest certs first
sort.SliceStable(certs, func(i, j int) bool {
return certs[i].NotBefore.Unix() > certs[j].NotBefore.Unix()
})
certCount := 0
// we check for every cert i > 0, if in context to the certificate i-1 it existed already longer than the overlap
// duration. We check the certificate i = 0 against the current certificate.
for i, crt := range certs {
if i == 0 {
if currentCert.Leaf.NotBefore.Add(overlapDuration).Before(now) {
log.DefaultLogger().Infof("Kept old CA certificates for a duration of at least %v, dropping them now.", overlapDuration)
break
}
} else {
if certs[i-1].NotBefore.Add(overlapDuration).Before(now) {
log.DefaultLogger().Infof("Kept old CA certificates for a duration of at least %v, dropping them now.", overlapDuration)
break
}
}
// drop expired CAs
if crt.NotAfter.Before(now) {
continue
}
certBytes := cert.EncodeCertPEM(crt)
// don't add the current CA multiple times
if reflect.DeepEqual(certBytes, current) {
continue
}
newBundle = append(newBundle, certBytes...)
certCount++
}
newBundle = append(current, newBundle...)
certCount++
return newBundle, certCount, nil
}
| {
"content_hash": "0c1912c4e13099631de42d6a1388142b",
"timestamp": "",
"source": "github",
"line_count": 379,
"max_line_length": 179,
"avg_line_length": 29.728232189973614,
"alnum_prop": 0.7061329546463122,
"repo_name": "davidvossel/kubevirt",
"id": "8c0985242261b6240cf31f9ea8da14ee65e52eda",
"size": "11267",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "pkg/virt-operator/resource/generate/components/secrets.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "5369"
},
{
"name": "Dockerfile",
"bytes": "5039"
},
{
"name": "Go",
"bytes": "7515877"
},
{
"name": "Makefile",
"bytes": "6525"
},
{
"name": "Python",
"bytes": "2743"
},
{
"name": "Shell",
"bytes": "195964"
},
{
"name": "Starlark",
"bytes": "856839"
}
],
"symlink_target": ""
} |
#ifndef __TERRAIN_MESH_H__
#define __TERRAIN_MESH_H__
#include <TerrainAbstract.h>
class TerrainMesh : public TerrainAbstract
{
public:
TerrainMesh(void);
TerrainMesh(const unsigned short width, const unsigned short height, const unsigned short depth, const float unitLength=2.0f);
TerrainMesh(const TerrainMesh& src);
virtual ~TerrainMesh(void);
TerrainMesh& operator = (const TerrainMesh& src);
void setGridNode(const unsigned short x, const float y, const unsigned short z);
void setSize(const unsigned short width, const unsigned short height, const unsigned short depth);
void render(void);
void release(void);
private:
void _resetGrid(void);
private:
float** _grid;
unsigned int _meshId;
};
#endif | {
"content_hash": "5dcfa72a69f9bd0ea1110e0b0eb9a0c7",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 134,
"avg_line_length": 27.833333333333332,
"alnum_prop": 0.6550898203592814,
"repo_name": "AndySmile/BachelorThesis",
"id": "6688b9ef50362b3a321dbc08a102ebef3e347266",
"size": "981",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DemoApp/Src/TerrainMesh.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1430"
},
{
"name": "C++",
"bytes": "151119"
},
{
"name": "Perl",
"bytes": "26440"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>pi-calc: 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 / pi-calc - 8.10.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
pi-calc
<small>
8.10.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-04-18 10:02:02 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-04-18 10:02:02 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.9.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.09.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.1 Official release 4.09.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "http://www.dimi.uniud.it/~scagnett/pi-calculus.html"
license: "Unknown"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/PiCalc"]
depends: [
"ocaml"
"coq" {>= "8.10" & < "8.11~"}
]
tags: [
"keyword: process algebras"
"keyword: pi-calculus"
"keyword: concurrency"
"keyword: higher-order syntax"
"category: Computer Science/Concurrent Systems and Protocols/Theory of concurrent systems"
"date: 1998-07"
]
authors: [
"Ivan Scagnetto <scagnett@dimi.uniud.it>"
]
bug-reports: "https://github.com/coq-contribs/pi-calc/issues"
dev-repo: "git+https://github.com/coq-contribs/pi-calc.git"
synopsis: "Pi-calculus in Coq"
description: """
This is a HOAS-based encoding of the pi-calculus (as originally
conceived by Milner, Parrow and Walker in "A Calculus of Mobile
Processes" Parts I-II, Information and Computation n. 100)
together with the formal verification of a large part of the
metatheory of Strong Late Bisimilarity."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/pi-calc/archive/v8.10.0.tar.gz"
checksum: "md5=8241113ea7e5891704be6bf6762386de"
}
</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-pi-calc.8.10.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-pi-calc -> coq >= 8.10
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-pi-calc.8.10.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": "880947a4c510e59cc22625d760c45183",
"timestamp": "",
"source": "github",
"line_count": 177,
"max_line_length": 159,
"avg_line_length": 40.5819209039548,
"alnum_prop": 0.5499095085618823,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "e6f7dfd5a658a46454c9703fac5af03d619a3a1d",
"size": "7208",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.09.1-2.0.6/released/8.9.1/pi-calc/8.10.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.