text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
//
// IFADynamicCache.m
// Gusty
//
// Created by Marcelo Schroeder on 23/07/10.
// Copyright 2010 InfoAccent Pty Limited. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "GustyLibFoundation.h"
@implementation IFADynamicCache
- (id)init{
if((self=[super init])){
// [self setEvictsObjectsWithDiscardedContent:NO];
[self setDelegate:self];
}
return self;
}
//- (BOOL)containsObjectForKey:(id)key{
// return [self objectForKey:key] != NULL;
//}
- (void)setObject:(id)obj forKey:(id)key{
//NSLog(@"IFADynamicCache setObject: %p forKey: %@", obj, key);
[super setObject:obj forKey:key];
}
/*
- (id)purgeableObjectForKey:(id)key{
IFAPurgeableObject *pObj = ((IFAPurgeableObject*)[self objectForKey:key]);
return pObj.obj;
}
- (void)setPurgeableObject:(id)obj forKey:(id)key{
IFAPurgeableObject *pObj = [[[IFAPurgeableObject alloc] initWithObject:obj] autorelease];
//NSLog(@"IFADynamicCache.setPurgeableObject: %p", pObj);
[self setObject:pObj forKey:key];
}
- (BOOL)retainPurgeableObjectForKey:(id)key{
IFAPurgeableObject *pObj = [self objectForKey:key];
if (pObj==NULL) {
return NO;
}else {
[pObj beginContentAccess];
return YES;
}
}
- (BOOL)releasePurgeableObjectForKey:(id)key{
IFAPurgeableObject *pObj = [self objectForKey:key];
if (pObj==NULL) {
return NO;
}else {
[pObj endContentAccess];
return YES;
}
}
*/
- (void)cache:(NSCache *)cache willEvictObject:(id)obj{
// NSLog(@"IFADynamicCache willEvictObject: %p", obj);
}
#pragma mark - Singleton functions
+ (IFADynamicCache *)sharedInstance {
static dispatch_once_t c_dispatchOncePredicate;
static IFADynamicCache *c_instance = nil;
dispatch_once(&c_dispatchOncePredicate, ^{
c_instance = [self new];
});
return c_instance;
}
@end
| {'content_hash': 'a9461a2183d3c477ab3be10883c2a02e', 'timestamp': '', 'source': 'github', 'line_count': 92, 'max_line_length': 90, 'avg_line_length': 25.130434782608695, 'alnum_prop': 0.7089100346020761, 'repo_name': 'marcelo-schroeder/GustyLibDemoApp-HUD', 'id': 'e5b2e570af01f92c50509f53789b5c178af55810', 'size': '2312', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Pods/GustyLib/GustyLib/GustyLib/Foundation/classes/IFADynamicCache.m', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Objective-C', 'bytes': '124'}, {'name': 'Ruby', 'bytes': '506'}, {'name': 'Swift', 'bytes': '30260'}]} |
@interface ETSConsommation : NSManagedObject
@property (nonatomic, retain) NSDate * date;
@property (nonatomic, retain) NSNumber * download;
@property (nonatomic, retain) NSNumber * upload;
@property (nonatomic, retain) NSString * idChambre;
@property (nonatomic, retain) NSString * id;
@end
| {'content_hash': '8cc35387753b00d5fde9367b5c32dd1c', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 51, 'avg_line_length': 32.666666666666664, 'alnum_prop': 0.7619047619047619, 'repo_name': 'krazdax5/ETSMobile-iOS', 'id': '843004711198905fa152c757baaa2865f92d5cac', 'size': '505', 'binary': False, 'copies': '2', 'ref': 'refs/heads/dev', 'path': 'ETSMobile/ETSConsommation.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Objective-C', 'bytes': '414396'}, {'name': 'Ruby', 'bytes': '545'}, {'name': 'Swift', 'bytes': '36848'}]} |
assert((new Number(Number.POSITIVE_INFINITY)).toString(undefined) === "Infinity"); | {'content_hash': '9eaa53f5cde4c30ffad12bb82a4cb003', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 82, 'avg_line_length': 82.0, 'alnum_prop': 0.7560975609756098, 'repo_name': 'jsdosa/TizenRT', 'id': 'c4775922863b61358e7d03179e8763300996ca1c', 'size': '712', 'binary': False, 'copies': '31', 'ref': 'refs/heads/master', 'path': 'external/iotjs/deps/jerry/tests/jerry-test-suite/15/15.07/15.07.04/15.07.04.02/15.07.04.02-012.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '2044301'}, {'name': 'Batchfile', 'bytes': '42646'}, {'name': 'C', 'bytes': '75170908'}, {'name': 'C++', 'bytes': '813875'}, {'name': 'HTML', 'bytes': '2990'}, {'name': 'Java', 'bytes': '63595'}, {'name': 'Makefile', 'bytes': '815989'}, {'name': 'Perl', 'bytes': '4361'}, {'name': 'PowerShell', 'bytes': '8511'}, {'name': 'Python', 'bytes': '263462'}, {'name': 'Roff', 'bytes': '4401'}, {'name': 'Shell', 'bytes': '233556'}, {'name': 'Tcl', 'bytes': '163693'}]} |
echo "Downloading RGT database to ${RGTDATA}..."
# RGTDATA is defined in build.sh, store the db there
# download data from release
wget ${DOWNLOAD_URL} -O RGT.tar.gz
mkdir RGT
tar xf RGT.tar.gz -C RGT --strip-components 1
cp -r RGT/data/fig/ ${RGTDATA}
cp -r RGT/data/fp_hmms/ ${RGTDATA}
cp -r RGT/data/motifs/ ${RGTDATA}
cp -r RGT/data/hg19/ ${RGTDATA}
cp -r RGT/data/hg38/ ${RGTDATA}
cp -r RGT/data/mm9/ ${RGTDATA}
cp -r RGT/data/mm10/ ${RGTDATA}
cp -r RGT/data/zv9/ ${RGTDATA}
cp -r RGT/data/zv10 ${RGTDATA}
rm -rf RGT
rm RGT.tar.gz
cd ${RGTDATA}
# download Genomic Data
setupGenomicData.py --all
setupGenomicData.py --hg19-rm
setupGenomicData.py --hg38-rm
setupGenomicData.py --mm9-rm
# download Logo Data
setupLogoData.py --all
echo "RGT database is downloaded."
exit 0
| {'content_hash': '7baac4d25341e2d3cdcf66ab5a3fad40', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 52, 'avg_line_length': 23.0, 'alnum_prop': 0.710997442455243, 'repo_name': 'bioconda/recipes', 'id': '7fbd250a46daac19ac3b7c3ae3d7433987aea5e2', 'size': '803', 'binary': False, 'copies': '36', 'ref': 'refs/heads/master', 'path': 'recipes/rgt/download-db.sh', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '55032'}, {'name': 'Makefile', 'bytes': '539'}, {'name': 'Perl', 'bytes': '767'}, {'name': 'Python', 'bytes': '38996'}, {'name': 'Shell', 'bytes': '250193'}]} |
package visualkey;
import java.awt.*;
import javax.swing.*;
import java.io.IOException;
import javax.sound.sampled.Clip;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class KPanel extends JPanel {
// Constantes
final boolean CENTRADO = true;
final boolean HORIZONTAL = false;
// Constructores
public KPanel(){
this.setLayout(layout);
}
public KPanel(Dimension dimension){
this.setPreferredSize(dimension);
this.setLayout(layout);
}
// Mueve objetos en el plano
public int[] move(int[] array,int increment){
for(int h=0;h<array.length;h++){
array[h]+=increment;
}
return array;
}
public Image getImage(String path){
return Toolkit.getDefaultToolkit().getImage(getClass().getResource(path));
}
public ImageIcon getImageIcon(String path){
return new ImageIcon(this.getImage(path));
}
// Labels
private JLabel label;
// Grid
private GridBagConstraints restriction = new GridBagConstraints();
// Layout
private GridBagLayout layout = new GridBagLayout();
public void addLabel(String text, int fila, int columna, int ancho, int alto, boolean centrado) {
label = new JLabel(text);
setRestriction(fila, columna, ancho, alto, 1, 1, centrado);
layout.setConstraints(label, restriction);
this.add(label);
}
public void addComponent(Component component, int fila, int columna, int ancho, int alto, int nweightx, int nweighty, boolean centrado) {
setRestriction(fila, columna, ancho, alto, nweighty, nweightx, centrado);
layout.setConstraints(component, restriction);
this.add(component);
}
public void addComponent(Component component, int fila, int columna, int ancho, int alto, boolean centrado){
addComponent(component, fila, columna, ancho, alto, 1, 1, centrado);
}
public void setRestriction(int fila, int columna, int ancho, int alto, int nweightx, int nweighty, boolean centrado) {
restriction.gridx = columna;
restriction.gridy = fila;
restriction.gridwidth = ancho;
restriction.gridheight = alto;
restriction.weightx = nweightx;
restriction.weighty = nweighty;
if(centrado){
restriction.fill = restriction.CENTER;
}else{
restriction.fill = restriction.HORIZONTAL;
}
}
public void showMessage(String msj){
JOptionPane.showMessageDialog(this,msj);
}
public String playSound(String sound){
String respuesta = "OK";
try {
Clip sonido = AudioSystem.getClip();
sonido.open(AudioSystem.getAudioInputStream(getClass().getResource(sound)));
sonido.start();
} catch (LineUnavailableException e) {
respuesta = "IMPOSIBLE TO PLAY THIS SOUND: "+sound;
e.printStackTrace();
} catch (IOException e) {
respuesta = "FILE NOT FOUND: "+sound;
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
respuesta = "UNSUPPOTED AUDIO INPUT: "+sound;
e.printStackTrace();
}
return respuesta;
}
} | {'content_hash': 'e4020c85b4c316d97da019635ad862fa', 'timestamp': '', 'source': 'github', 'line_count': 107, 'max_line_length': 138, 'avg_line_length': 27.49532710280374, 'alnum_prop': 0.7358939496940856, 'repo_name': 'cjortegon/NextFruit', 'id': '35a20e7a1766db5dc26ce9563fa1d754fb3918e9', 'size': '2942', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Next_Fruit/src/visualkey/KPanel.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '12842'}, {'name': 'HTML', 'bytes': '2407548'}, {'name': 'Java', 'bytes': '351962'}, {'name': 'JavaScript', 'bytes': '827'}]} |
<?php
declare(strict_types=1);
namespace Autowp\Image\Processor;
use Interop\Container\ContainerInterface;
use Laminas\ServiceManager\Config;
use Laminas\ServiceManager\Factory\FactoryInterface;
use function is_array;
class ProcessorPluginManagerFactory implements FactoryInterface
{
/**
* {@inheritDoc}
*
* @param string $name
* @return ProcessorPluginManager
*/
public function __invoke(ContainerInterface $container, $name, ?array $options = null)
{
$pluginManager = new ProcessorPluginManager($container, $options ?: []);
// If we do not have a config service, nothing more to do
if (! $container->has('config')) {
return $pluginManager;
}
$config = $container->get('config');
if (! isset($config['image_processors']) || ! is_array($config['image_processors'])) {
return $pluginManager;
}
(new Config($config['image_processors']))->configureServiceManager($pluginManager);
return $pluginManager;
}
}
| {'content_hash': '2768b834c97c364963a6f833886aa9a3', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 94, 'avg_line_length': 26.923076923076923, 'alnum_prop': 0.6495238095238095, 'repo_name': 'autowp/image', 'id': '8c0968afa7a325da22a3f109b89d63ac005e188b', 'size': '1050', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Processor/ProcessorPluginManagerFactory.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '142675'}]} |
<?php
/**
* @see Zend_Service_DeveloperGarden_SecurityTokenServer_Cache
*/
// require_once 'Zend/Service/DeveloperGarden/SecurityTokenServer/Cache.php';
/**
* @see Zend_Service_DeveloperGarden_Client_ClientAbstract
*/
// require_once 'Zend/Service/DeveloperGarden/Client/ClientAbstract.php';
/**
* @see Zend_Service_DeveloperGarden_Response_SecurityTokenServer_SecurityTokenResponse
*/
// require_once 'Zend/Service/DeveloperGarden/Response/SecurityTokenServer/SecurityTokenResponse.php';
/**
* @see Zend_Service_DeveloperGarden_Response_SecurityTokenServer_GetTokensResponse
*/
// require_once 'Zend/Service/DeveloperGarden/Response/SecurityTokenServer/GetTokensResponse.php';
/**
* @category Zend
* @package Zend_Service
* @subpackage DeveloperGarden
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @author Marco Kaiser
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Service_DeveloperGarden_SecurityTokenServer
extends Zend_Service_DeveloperGarden_Client_ClientAbstract
{
/**
* wsdl file
*
* @var string
*/
protected $_wsdlFile = 'https://sts.idm.telekom.com/TokenService?wsdl';
/**
* wsdl file local
*
* @var string
*/
protected $_wsdlFileLocal = 'Wsdl/TokenService.wsdl';
/**
* Response, Request Classmapping
*
* @var array
*
*/
protected $_classMap = array(
'SecurityTokenResponse' => 'Zend_Service_DeveloperGarden_Response_SecurityTokenServer_SecurityTokenResponse',
'getTokensResponse' => 'Zend_Service_DeveloperGarden_Response_SecurityTokenServer_GetTokensResponse'
);
/**
* does the login and return the specific response
*
* @return Zend_Service_DeveloperGarden_Response_SecurityTokenServer_SecurityTokenResponse
*/
public function getLoginToken()
{
$token = Zend_Service_DeveloperGarden_SecurityTokenServer_Cache::getTokenFromCache(
'securityToken'
);
if ($token === null
|| !$token->isValid()
) {
$token = $this->getSoapClient()->login('login');
Zend_Service_DeveloperGarden_SecurityTokenServer_Cache::setTokenToCache(
'securityToken',
$token
);
}
return $token;
}
/**
* returns the fetched token from token server
*
* @return Zend_Service_DeveloperGarden_Response_SecurityTokenServer_GetTokensResponse
*/
public function getTokens()
{
$token = Zend_Service_DeveloperGarden_SecurityTokenServer_Cache::getTokenFromCache(
'getTokens'
);
if ($token === null
|| !$token->isValid()
) {
$token = $this->getSoapClient()->getTokens(array(
'serviceId' => $this->_serviceAuthId
));
Zend_Service_DeveloperGarden_SecurityTokenServer_Cache::setTokenToCache(
'getTokens',
$token
);
}
return $token;
}
}
| {'content_hash': 'fa1a95f1742e722b29200cd1eb3f07fd', 'timestamp': '', 'source': 'github', 'line_count': 108, 'max_line_length': 117, 'avg_line_length': 28.87962962962963, 'alnum_prop': 0.6377043924334722, 'repo_name': 'Chatventure/zf1', 'id': '725020a1212a837f89fbf507f960591bfb0e446a', 'size': '3902', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'library/Zend/Service/DeveloperGarden/SecurityTokenServer.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'PHP', 'bytes': '15045100'}, {'name': 'Shell', 'bytes': '1409'}]} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': 'f9bc9f5fbce5a6d6d102bc7556283578', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': '137dcd1a9ab566e83a883f14aef725a86fa7876a', 'size': '201', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Dipsacales/Caprifoliaceae/Lonicera/Lonicera maackii/ Syn. Lonicera maackii podocarpa/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
function sendCommand(cmd) {
window.domAutomationController.setAutomationId(1);
window.domAutomationController.send(cmd);
}
function makeImageSet(url1x, url2x) {
return '-webkit-image-set(url(' + url1x + ') 1x, url(' + url2x + ') 2x)';
}
function initialize() {
if (loadTimeData.getBoolean('allowAccessRequests')) {
$('request-access-button').onclick = function(event) {
updateAfterRequestSent();
sendCommand('request');
};
} else {
$('request-access-button').hidden = true;
}
var avatarURL1x = loadTimeData.getString('avatarURL1x');
var avatarURL2x = loadTimeData.getString('avatarURL2x');
if (avatarURL1x) {
$('avatar-img').style.content = makeImageSet(avatarURL1x, avatarURL2x);
$('avatar-img').hidden = false;
$('error-img').hidden = true;
var secondAvatarURL1x = loadTimeData.getString('secondAvatarURL1x');
var secondAvatarURL2x = loadTimeData.getString('secondAvatarURL2x');
if (secondAvatarURL1x) {
$('second-avatar-img').style.content =
makeImageSet(secondAvatarURL1x, secondAvatarURL2x);
$('second-avatar-img').hidden = false;
// The avatar images should overlap a bit.
$('avatar-img').style.left = '10px';
$('avatar-img').style.zIndex = '1';
$('second-avatar-img').style.left = '-10px';
}
}
$('back-button').onclick = function(event) {
sendCommand('back');
};
}
/**
* Updates the interstitial to show that the request was sent.
*/
function updateAfterRequestSent() {
$('error-img').hidden = true;
$('request-access-button').hidden = true;
$('block-page-message').hidden = true;
$('request-sent-message').hidden = false;
if ($('avatar-img').hidden) {
$('request-sent-message').style.marginTop = '40px';
}
}
document.addEventListener('DOMContentLoaded', initialize);
| {'content_hash': 'e3793326247f9a831af39c804e13e8e3', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 75, 'avg_line_length': 33.71186440677966, 'alnum_prop': 0.6711915535444947, 'repo_name': 'sudosurootdev/external_chromium_org', 'id': 'dbf57ecc1976ecae0e3f65d903fd0829d2f94582', 'size': '1989', 'binary': False, 'copies': '28', 'ref': 'refs/heads/L5', 'path': 'chrome/browser/resources/supervised_user_block_interstitial.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '8242'}, {'name': 'AppleScript', 'bytes': '6973'}, {'name': 'Assembly', 'bytes': '23945'}, {'name': 'C', 'bytes': '3791007'}, {'name': 'C++', 'bytes': '215300258'}, {'name': 'CSS', 'bytes': '927304'}, {'name': 'Go', 'bytes': '1631'}, {'name': 'HTML', 'bytes': '18342717'}, {'name': 'Java', 'bytes': '5814680'}, {'name': 'JavaScript', 'bytes': '11377316'}, {'name': 'Makefile', 'bytes': '24659487'}, {'name': 'Objective-C', 'bytes': '1142916'}, {'name': 'Objective-C++', 'bytes': '7211157'}, {'name': 'PHP', 'bytes': '61320'}, {'name': 'PLpgSQL', 'bytes': '144885'}, {'name': 'Perl', 'bytes': '69768'}, {'name': 'Protocol Buffer', 'bytes': '395699'}, {'name': 'Python', 'bytes': '7158565'}, {'name': 'Shell', 'bytes': '473118'}, {'name': 'Standard ML', 'bytes': '4218'}, {'name': 'XSLT', 'bytes': '418'}, {'name': 'nesC', 'bytes': '15206'}]} |
package net.jini.print.attribute.standard;
import java.util.Set;
import javax.print.attribute.Attribute;
import net.jini.print.attribute.Dimension;
import net.jini.print.attribute.OneSetOfSyntax;
/**
*
* @author peter
*/
public class PunchingLocations extends OneSetOfSyntax implements Attribute {
public PunchingLocations(Set<Dimension> locations) {
super(locations);
}
@Override
public Class<? extends Attribute> getCategory() {
return PunchingLocations.class;
}
@Override
public String getName() {
return "punching-locations";
}
}
| {'content_hash': '912e3d0af4a5da4964f11a5fbf22087c', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 76, 'avg_line_length': 20.466666666666665, 'alnum_prop': 0.6921824104234527, 'repo_name': 'pfirmstone/Jini-Print-API', 'id': 'a5b15b7c6d4fe9c21bcec5ebc5697c78b3433ce5', 'size': '1218', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'JiniPrint/src/main/java/net/jini/print/attribute/standard/PunchingLocations.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '167894'}, {'name': 'Java', 'bytes': '974234'}]} |
package hudson.tasks;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
import hudson.Launcher;
import hudson.Util;
import hudson.console.ModelHyperlinkNote;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AutoCompletionCandidates;
import hudson.model.BuildListener;
import hudson.model.Cause.UpstreamCause;
import hudson.model.DependencyGraph;
import hudson.model.DependencyGraph.Dependency;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.Items;
import hudson.model.Job;
import hudson.model.Project;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.model.listeners.ItemListener;
import hudson.model.queue.Tasks;
import hudson.security.ACL;
import hudson.security.ACLContext;
import hudson.util.FormValidation;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.model.DependencyDeclarer;
import jenkins.model.Jenkins;
import jenkins.model.ParameterizedJobMixIn;
import jenkins.triggers.ReverseBuildTrigger;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.springframework.security.core.Authentication;
/**
* Triggers builds of other projects.
*
* <p>
* Despite what the name suggests, this class doesn't actually trigger other jobs
* as a part of {@link #perform} method. Its main job is to simply augment
* {@link DependencyGraph}. Jobs are responsible for triggering downstream jobs
* on its own, because dependencies may come from other sources.
*
* <p>
* This class, however, does provide the {@link #execute(AbstractBuild, BuildListener, BuildTrigger)}
* method as a convenience method to invoke downstream builds.
*
* <p>Its counterpart is {@link ReverseBuildTrigger}.
*
* @author Kohsuke Kawaguchi
*/
public class BuildTrigger extends Recorder implements DependencyDeclarer {
/**
* Comma-separated list of other projects to be scheduled.
*/
private String childProjects;
/**
* Threshold status to trigger other builds.
*
* For compatibility reasons, this field could be null, in which case
* it should read as "SUCCESS".
*/
private final Result threshold;
public BuildTrigger(String childProjects, boolean evenIfUnstable) {
this(childProjects, evenIfUnstable ? Result.UNSTABLE : Result.SUCCESS);
}
@DataBoundConstructor
public BuildTrigger(String childProjects, String threshold) {
this(childProjects, Result.fromString(StringUtils.defaultString(threshold, Result.SUCCESS.toString())));
}
public BuildTrigger(String childProjects, Result threshold) {
if (childProjects == null)
throw new IllegalArgumentException();
this.childProjects = childProjects;
this.threshold = threshold;
}
public BuildTrigger(List<AbstractProject> childProjects, Result threshold) {
this((Collection<AbstractProject>) childProjects, threshold);
}
public BuildTrigger(Collection<? extends AbstractProject> childProjects, Result threshold) {
this(Items.toNameList(childProjects), threshold);
}
public String getChildProjectsValue() {
return childProjects;
}
public Result getThreshold() {
if (threshold == null)
return Result.SUCCESS;
else
return threshold;
}
/**
* @deprecated as of 1.406
* Use {@link #getChildProjects(ItemGroup)}
*/
@Deprecated
public List<AbstractProject> getChildProjects() {
return getChildProjects(Jenkins.get());
}
/** @deprecated use {@link #getChildJobs} */
@Deprecated
public List<AbstractProject> getChildProjects(AbstractProject owner) {
return getChildProjects(owner == null ? null : owner.getParent());
}
@Deprecated
public List<AbstractProject> getChildProjects(ItemGroup base) {
return Items.fromNameList(base, childProjects, AbstractProject.class);
}
@SuppressWarnings("unchecked")
@NonNull
public List<Job<?, ?>> getChildJobs(@NonNull AbstractProject<?, ?> owner) {
return Items.fromNameList(owner.getParent(), childProjects, (Class<Job<?, ?>>) (Class) Job.class);
}
@Override
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
/**
* @deprecated apparently unused
*/
@Deprecated
public boolean hasSame(AbstractProject owner, Collection<? extends AbstractProject> projects) {
List<AbstractProject> children = getChildProjects(owner);
return children.size() == projects.size() && children.containsAll(projects);
}
/**
* @deprecated as of 1.406
* Use {@link #hasSame(AbstractProject, Collection)}
*/
@Deprecated
public boolean hasSame(Collection<? extends AbstractProject> projects) {
return hasSame(null, projects);
}
@Override
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
List<Job<?, ?>> jobs = new ArrayList<>();
for (Job<?, ?> job : getChildJobs(build.getProject())) {
if (job instanceof AbstractProject) {
continue; // taken care of by DependencyGraph
}
jobs.add(job);
}
if (!jobs.isEmpty() && build.getResult().isBetterOrEqualTo(threshold)) {
PrintStream logger = listener.getLogger();
for (Job<?, ?> downstream : jobs) {
if (Jenkins.get().getItemByFullName(downstream.getFullName()) != downstream) {
LOGGER.log(Level.WARNING, "Running as {0} cannot even see {1} for trigger from {2}", new Object[] {Jenkins.getAuthentication2().getName(), downstream, build.getParent()});
continue;
}
if (!downstream.hasPermission(Item.BUILD)) {
listener.getLogger().println(Messages.BuildTrigger_you_have_no_permission_to_build_(ModelHyperlinkNote.encodeTo(downstream)));
continue;
}
if (!(downstream instanceof ParameterizedJobMixIn.ParameterizedJob)) {
logger.println(Messages.BuildTrigger_NotBuildable(ModelHyperlinkNote.encodeTo(downstream)));
continue;
}
ParameterizedJobMixIn.ParameterizedJob<?, ?> pj = (ParameterizedJobMixIn.ParameterizedJob) downstream;
if (pj.isDisabled()) {
logger.println(Messages.BuildTrigger_Disabled(ModelHyperlinkNote.encodeTo(downstream)));
continue;
}
if (!downstream.isBuildable()) { // some other reason; no API to retrieve cause
logger.println(Messages.BuildTrigger_NotBuildable(ModelHyperlinkNote.encodeTo(downstream)));
continue;
}
boolean scheduled = pj.scheduleBuild(pj.getQuietPeriod(), new UpstreamCause((Run) build));
if (Jenkins.get().getItemByFullName(downstream.getFullName()) == downstream) {
String name = ModelHyperlinkNote.encodeTo(downstream);
if (scheduled) {
logger.println(Messages.BuildTrigger_Triggering(name));
} else {
logger.println(Messages.BuildTrigger_InQueue(name));
}
}
}
}
return true;
}
/**
* @deprecated since 1.341; use {@link #execute(AbstractBuild,BuildListener)}
*/
@Deprecated
public static boolean execute(AbstractBuild build, BuildListener listener, BuildTrigger trigger) {
return execute(build, listener);
}
/**
* Convenience method to trigger downstream builds.
*
* @param build
* The current build. Its downstreams will be triggered.
* @param listener
* Receives the progress report.
*/
public static boolean execute(AbstractBuild build, BuildListener listener) {
PrintStream logger = listener.getLogger();
// Check all downstream Project of the project, not just those defined by BuildTrigger
DependencyGraph graphTemp;
try {
// Note: futureDependencyGraph can be null, if no asynchronous computation of the
// dependency graph has been performed.
Future<DependencyGraph> futureDependencyGraph = Jenkins.get().getFutureDependencyGraph();
if (futureDependencyGraph != null) {
graphTemp = futureDependencyGraph.get();
} else {
graphTemp = Jenkins.get().getDependencyGraph();
}
} catch (IllegalStateException | InterruptedException | ExecutionException e) {
// Use old version of dependency graph instead
graphTemp = Jenkins.get().getDependencyGraph();
}
DependencyGraph graph = graphTemp;
List<Dependency> downstreamProjects = new ArrayList<>(
graph.getDownstreamDependencies(build.getProject()));
// Sort topologically
downstreamProjects.sort(new Comparator<Dependency>() {
@Override
public int compare(Dependency lhs, Dependency rhs) {
// Swapping lhs/rhs to get reverse sort:
return graph.compare(rhs.getDownstreamProject(), lhs.getDownstreamProject());
}
});
for (Dependency dep : downstreamProjects) {
List<Action> buildActions = new ArrayList<>();
if (dep.shouldTriggerBuild(build, listener, buildActions)) {
AbstractProject p = dep.getDownstreamProject();
// Allow shouldTriggerBuild to return false first, in case it is skipping because of a lack of Item.READ/DISCOVER permission:
if (p.isDisabled()) {
logger.println(Messages.BuildTrigger_Disabled(ModelHyperlinkNote.encodeTo(p)));
continue;
}
boolean scheduled = p.scheduleBuild(p.getQuietPeriod(), new UpstreamCause((Run) build), buildActions.toArray(new Action[0]));
if (Jenkins.get().getItemByFullName(p.getFullName()) == p) {
String name = ModelHyperlinkNote.encodeTo(p);
if (scheduled) {
logger.println(Messages.BuildTrigger_Triggering(name));
} else {
logger.println(Messages.BuildTrigger_InQueue(name));
}
} // otherwise upstream users should not know that it happened
}
}
return true;
}
@Override
public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) {
for (AbstractProject p : getChildProjects(owner)) // only care about AbstractProject here
graph.addDependency(new Dependency(owner, p) {
@SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification = "TODO needs triage")
@Override
public boolean shouldTriggerBuild(AbstractBuild build, TaskListener listener,
List<Action> actions) {
AbstractProject downstream = getDownstreamProject();
if (Jenkins.get().getItemByFullName(downstream.getFullName()) != downstream) { // this checks Item.READ also on parent folders
LOGGER.log(Level.WARNING, "Running as {0} cannot even see {1} for trigger from {2}", new Object[] {Jenkins.getAuthentication2().getName(), downstream, getUpstreamProject()});
return false; // do not even issue a warning to build log
}
if (!downstream.hasPermission(Item.BUILD)) {
listener.getLogger().println(Messages.BuildTrigger_you_have_no_permission_to_build_(ModelHyperlinkNote.encodeTo(downstream)));
return false;
}
return build.getResult().isBetterOrEqualTo(threshold);
}
});
}
@Override
public boolean needsToRunAfterFinalized() {
return true;
}
/** @deprecated Does not handle folder moves. */
@Deprecated
public boolean onJobRenamed(String oldName, String newName) {
// quick test
if (!childProjects.contains(oldName))
return false;
boolean changed = false;
// we need to do this per string, since old Project object is already gone.
String[] projects = childProjects.split(",");
for (int i = 0; i < projects.length; i++) {
if (projects[i].trim().equals(oldName)) {
projects[i] = newName;
changed = true;
}
}
if (changed) {
childProjects = String.join(",", projects);
}
return changed;
}
/**
* Correct broken data gracefully (JENKINS-1537)
*/
private Object readResolve() {
if (childProjects == null)
return childProjects = "";
return this;
}
@Extension @Symbol("downstream")
public static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
@NonNull
@Override
public String getDisplayName() {
return Messages.BuildTrigger_DisplayName();
}
@Override
public String getHelpFile() {
return "/help/project-config/downstream.html";
}
@Override
public BuildTrigger newInstance(StaplerRequest req, JSONObject formData) throws FormException {
String childProjectsString = formData.getString("childProjects").trim();
if (childProjectsString.endsWith(",")) {
childProjectsString = childProjectsString.substring(0, childProjectsString.length() - 1).trim();
}
return new BuildTrigger(
childProjectsString,
formData.optString("threshold", Result.SUCCESS.toString()));
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
public boolean showEvenIfUnstableOption(@CheckForNull Class<? extends AbstractProject<?, ?>> jobType) {
// UGLY: for promotion process, this option doesn't make sense.
return jobType == null || !jobType.getName().contains("PromotionProcess");
}
/**
* Form validation method.
*/
public FormValidation doCheck(@AncestorInPath AbstractProject project, @QueryParameter String value) {
// JENKINS-32525: Check that it behaves gracefully for an unknown context
if (project == null) return FormValidation.ok(Messages.BuildTrigger_ok_ancestor_is_null());
// Require CONFIGURE permission on this project
if (!project.hasPermission(Item.CONFIGURE)) return FormValidation.ok();
StringTokenizer tokens = new StringTokenizer(Util.fixNull(value), ",");
boolean hasProjects = false;
while (tokens.hasMoreTokens()) {
String projectName = tokens.nextToken().trim();
if (StringUtils.isNotBlank(projectName)) {
Item item = Jenkins.get().getItem(projectName, project, Item.class);
if (item == null) {
Job<?, ?> nearest = Items.findNearest(Job.class, projectName, project.getParent());
String alternative = nearest != null ? nearest.getRelativeNameFrom(project) : "?";
return FormValidation.error(Messages.BuildTrigger_NoSuchProject(projectName, alternative));
}
if (!(item instanceof ParameterizedJobMixIn.ParameterizedJob))
return FormValidation.error(Messages.BuildTrigger_NotBuildable(projectName));
// check whether the supposed user is expected to be able to build
Authentication auth = Tasks.getAuthenticationOf2(project);
if (!item.hasPermission2(auth, Item.BUILD)) {
return FormValidation.error(Messages.BuildTrigger_you_have_no_permission_to_build_(projectName));
}
hasProjects = true;
}
}
if (!hasProjects) {
return FormValidation.error(Messages.BuildTrigger_NoProjectSpecified());
}
return FormValidation.ok();
}
public AutoCompletionCandidates doAutoCompleteChildProjects(@QueryParameter String value, @AncestorInPath Item self, @AncestorInPath ItemGroup container) {
return AutoCompletionCandidates.ofJobNames(Job.class, value, self, container);
}
@Extension
public static class ItemListenerImpl extends ItemListener {
@Override
public void onLocationChanged(final Item item, final String oldFullName, final String newFullName) {
try (ACLContext acl = ACL.as2(ACL.SYSTEM2)) {
locationChanged(item, oldFullName, newFullName);
}
}
private void locationChanged(Item item, String oldFullName, String newFullName) {
// update BuildTrigger of other projects that point to this object.
// can't we generalize this?
for (Project<?, ?> p : Jenkins.get().allItems(Project.class)) {
BuildTrigger t = p.getPublishersList().get(BuildTrigger.class);
if (t != null) {
String cp2 = Items.computeRelativeNamesAfterRenaming(oldFullName, newFullName, t.childProjects, p.getParent());
if (!cp2.equals(t.childProjects)) {
t.childProjects = cp2;
try {
p.save();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to persist project setting during rename from " + oldFullName + " to " + newFullName, e);
}
}
}
}
}
}
}
private static final Logger LOGGER = Logger.getLogger(BuildTrigger.class.getName());
}
| {'content_hash': '3a0cc5931902be48eb19646dc732b563', 'timestamp': '', 'source': 'github', 'line_count': 458, 'max_line_length': 198, 'avg_line_length': 41.87336244541485, 'alnum_prop': 0.623266242569611, 'repo_name': 'rsandell/jenkins', 'id': '08c3a147f8d778c477cd78e593eb11247cb61c4a', 'size': '20386', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/hudson/tasks/BuildTrigger.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1023'}, {'name': 'C', 'bytes': '2091'}, {'name': 'CSS', 'bytes': '217962'}, {'name': 'GAP', 'bytes': '6933'}, {'name': 'Groovy', 'bytes': '78179'}, {'name': 'HTML', 'bytes': '973939'}, {'name': 'Handlebars', 'bytes': '15071'}, {'name': 'Java', 'bytes': '11512027'}, {'name': 'JavaScript', 'bytes': '412700'}, {'name': 'Less', 'bytes': '184030'}, {'name': 'Perl', 'bytes': '16145'}, {'name': 'Python', 'bytes': '4047'}, {'name': 'Ruby', 'bytes': '17290'}, {'name': 'Shell', 'bytes': '2354'}]} |
var empty = {};
assert (Object.isExtensible(empty) === true);
// ...but that can be changed.
Object.preventExtensions(empty);
assert(Object.isExtensible(empty) === false);
// Call on undefined should throw TypeError.
try
{
Object.isExtensible(undefined);
assert (false);
} catch (e) {
assert (e instanceof TypeError);
}
try
{
Object.preventExtensions(undefined);
assert (false);
} catch (e) {
assert (e instanceof TypeError);
}
// Sealed objects are by definition non-extensible.
var sealed = Object.seal({});
assert (Object.isExtensible(sealed) === false);
// Frozen objects are also by definition non-extensible.
var frozen = Object.freeze({});
assert(Object.isExtensible(frozen) === false);
| {'content_hash': '54da1b6c48455f458693365aa22e7204', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 56, 'avg_line_length': 23.322580645161292, 'alnum_prop': 0.6970954356846473, 'repo_name': 'bsdelf/jerryscript', 'id': 'f3e96b5eed8f1df9c87a7b1ab7f063f48831d333', 'size': '1384', 'binary': False, 'copies': '31', 'ref': 'refs/heads/master', 'path': 'tests/jerry/object-is-extensible.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '6566'}, {'name': 'Batchfile', 'bytes': '1692'}, {'name': 'C', 'bytes': '3206895'}, {'name': 'C++', 'bytes': '275660'}, {'name': 'CMake', 'bytes': '50629'}, {'name': 'HTML', 'bytes': '35334'}, {'name': 'JavaScript', 'bytes': '1649329'}, {'name': 'Makefile', 'bytes': '17977'}, {'name': 'Python', 'bytes': '154866'}, {'name': 'Shell', 'bytes': '65021'}, {'name': 'Tcl', 'bytes': '45226'}]} |
'use strict';
function unescape(html, $sanitize) {
if (!html) return '';
html = html.replace(/>/g, '>').replace(/</g, '<').replace(/&/g, '&').replace();
return $sanitize ? $sanitize(html) : html;
}
// Declare app level module which depends on filters, and services
angular.module('gistofit', [
'onsen',
'gistofit.filters',
'gistofit.services',
'gistofit.directives',
'angular-embedly',
'ngSanitize',
'ngAnimate',
'ngTouch',
'ui.comments',
'mgcrea.pullToRefresh'
])
//.directive('slider', sliderDirective)
.directive('commenter', commenterDirective)
.directive('gistCard', gistCardDirective)
.directive('articleCard', articleCardDirective)
.directive('article', articleDirective)
.directive('openExternal', openExternalDirective)
.config(function(embedlyServiceProvider){
embedlyServiceProvider.setKey('42f4925174814d68b90d0758d932fe14');
})
.config(function(commentsConfigProvider) {
commentsConfigProvider.set({
containerTemplate: 'views/comments.html',
commentTemplate: 'views/comment.html',
commentController: 'CommentCtrl',
depthLimit: 10
});
})
.controller('CommentCtrl', function($scope, $element, $timeout) {
var children;
$scope.collapsed = true;
$scope.$on('$filledNestedComments', function(nodes) {
$scope.collapsed = true;
$timeout(function() {
children = nodes;
children.addClass('collapse').removeClass('in');
children.collapse({
toggle: false
});
// Stupid hack to wait for DOM insertion prior to setting up plugin
}, 1);
});
$scope.$on('$emptiedNestedComments', function(nodes) {
children = undefined;
});
$scope.collapse = function() {
$scope.collapsed = children.hasClass('in');
children.collapse('toggle');
};
$scope.addChildComment = function(comment) {
var childComment = angular.extend(comment, {
name: '@'+comment.name,
date: new Date(),
profileUrl: 'https://github.com/' + comment.name
});
if(!$scope.comment.children) {
$scope.comment.children = [];
}
$scope.comment.children.push(childComment);
};
$scope.addParentComment = function(comment) {
var parentComment = angular.extend(comment, {
name: '@'+comment.name,
date: new Date(),
profileUrl: 'https://github.com/' + comment.name
});
$scope.comments.push(parentComment);
};
});
document.addEventListener("deviceready", onDeviceReady, false);
var show_welcome;
function onDeviceReady() {
angular.bootstrap(document, ['gistofit']);
// var gaPlugin;
// gaPlugin = window.plugins.gaPlugin;
// gaPlugin.init(successHandler, errorHandler, "UA-53420229-1", 10);
var applaunchCount = window.localStorage.getItem('launchCount');
show_welcome = applaunchCount ? 0 : 1;
window.localStorage.setItem('launchCount',1);
console.log(window.localStorage);
}
| {'content_hash': 'd4fb7b26e01a369295a81ed671fadf67', 'timestamp': '', 'source': 'github', 'line_count': 98, 'max_line_length': 91, 'avg_line_length': 29.408163265306122, 'alnum_prop': 0.6731436502428869, 'repo_name': 'lyonsrob/gistofit', 'id': '064b164b35ede39c17ccb89a3de2a56db8444493', 'size': '3476', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'gistofit-mobile/www/js/app.js', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'AppleScript', 'bytes': '3624'}, {'name': 'C', 'bytes': '7871'}, {'name': 'C#', 'bytes': '18839'}, {'name': 'C++', 'bytes': '8501'}, {'name': 'CSS', 'bytes': '262901'}, {'name': 'CoffeeScript', 'bytes': '2812'}, {'name': 'Erlang', 'bytes': '163'}, {'name': 'Java', 'bytes': '1998484'}, {'name': 'JavaScript', 'bytes': '2252304'}, {'name': 'Objective-C', 'bytes': '2152252'}, {'name': 'PHP', 'bytes': '4937'}, {'name': 'Perl', 'bytes': '891'}, {'name': 'Ruby', 'bytes': '2378'}, {'name': 'Shell', 'bytes': '101129'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<Export generator="Cache" version="25">
<Class name="Demo.Extractor.Extractor.Regexp">
<Abstract>1</Abstract>
<Super>Abstract</Super>
<TimeCreated>63712,42799.093717</TimeCreated>
<Parameter name="TRACKENTITIES">
<Default>0</Default>
</Parameter>
<Property name="DictionaryId">
<Type>%Integer</Type>
</Property>
<Method name="GetRegularExpressions">
<Description>
Return the regexps this extractor should take care of:
pRegexps(ID) = $lb(regexp, replace, element, eval)</Description>
<ClassMethod>1</ClassMethod>
<FormalSpec>*pRegexps</FormalSpec>
<Private>1</Private>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[ quit $$$OK
]]></Implementation>
</Method>
<Method name="Register">
<Description>
Registers this extractor with the domain, preparing any required domain artifacts such as
dictionary items and formats.</Description>
<Final>1</Final>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
set tSC = $$$OK
try {
// check if this dictionary already exists
set ..DictionaryId = ##class(%iKnow.Matching.DictionaryAPI).GetDictionaryId(..DomainId, $classname())
quit:..DictionaryId>0
set ..DictionaryId = ##class(%iKnow.Matching.DictionaryAPI).CreateDictionary(..DomainId, $classname(), "Extractor dictionary for "_$classname(),,, .tSC)
quit:$$$ISERR(tSC)
do ..GetRegularExpressions(.tRegexp)
set id = ""
for {
set id = $order(tRegexp(id), 1, tData)
quit:id=""
set tItemURI = $classname()_":"_id
set tDictItemId = ##class(%iKnow.Matching.DictionaryAPI).CreateDictionaryItem(..DomainId, ..DictionaryId, $classname()_" #"_id, $classname()_":"_id,, .tSC)
quit:$$$ISERR(tSC)
set tDictTermId = ##class(%iKnow.Matching.DictionaryAPI).CreateRegularExpression(..DomainId, tDictItemId, $$$LOWER($lg(tData,1)), $lg(tData,2), .tSC)
quit:$$$ISERR(tSC)
}
} catch (ex) {
set tSC = ex.AsStatus()
}
quit tSC
]]></Implementation>
</Method>
<Method name="Unregister">
<ClassMethod>1</ClassMethod>
<FormalSpec>pDomainId:%Integer</FormalSpec>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
set tDictId = ##class(%iKnow.Matching.DictionaryAPI).GetDictionaryId(pDomainId, $classname())
quit:tDictId<=0 $$$OK
quit ##class(%iKnow.Matching.DictionaryAPI).DropDictionary(pDomainId, tDictId)
]]></Implementation>
</Method>
<Method name="Extract">
<Description><![CDATA[
Extracts item values from <var>pSourceId</var> and appends them to <var>pResults</var>
pResults(ITEM, n) = $lb(value, score, classname, highlightspec, entities, negation)]]></Description>
<FormalSpec><![CDATA[pSourceId:%Integer,&pResults]]></FormalSpec>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
set tSC = $$$OK
try {
do ..GetRegularExpressions(.tRegexps)
set tSC = ##class(%iKnow.Matching.MatchingAPI).GetMatchesBySourceId(.tMatches, ..DomainId, pSourceId, $lb(..DictionaryId), 0, 0)
quit:$$$ISERR(tSC)
set i = ""
for {
set i = $order(tMatches(i), 1, tData)
quit:i=""
set tMatchId = $lg(tData,1), tItemURI = $lg(tData,4), tItemId = $lg(tData,3)
set tREInfo = $g(tRegexps($piece(tItemURI,":",2)))
continue:tREInfo=""
set tREElementPos = $lg(tREInfo,3,1), tREExecute = $lg(tREInfo,4,0)
// retrieve format results
set tSC = ##class(%iKnow.Matching.MatchingAPI).GetMatchElements(.tElements, ..DomainId, tMatchId, $s(pSourceId<0:pSourceId, 1:0))
quit:$$$ISERR(tSC)
// walk through elements
set j = "", tEntities = "", tValue=""
for {
set j = $order(tElements(j), 1, tElementData)
quit:j=""
//set tEntities = tEntities_$lb(##class(%iKnow.Queries.EntityAPI).GetValueInternal(..DomainId, $lg(tElementData,3), $s(pSourceId<0:pSourceId, 1:0)))
set:..#TRACKENTITIES tEntities = tEntities_$lb($lg(tElementData,3))
continue:j'=tREElementPos
// if this is the element of interest, calculate values
set tValue = $lg(tElementData,11), tScore = $lg(tElementData,6)
// check if this needs evaluation
if tREExecute {
xecute ("(v) set v = "_tValue, .tEvaluatedValue)
set tValue = tEvaluatedValue
}
}
do ..AddResult(.pResults, tValue, tScore, "MATCH:"_..DictionaryId_":"_tMatchId, tEntities)
}
quit:$$$ISERR(tSC)
} catch (ex) {
set tSC = ex.AsStatus()
}
quit tSC
]]></Implementation>
</Method>
<Method name="Test">
<ClassMethod>1</ClassMethod>
<FormalSpec>pDomainId:%Integer,pString:%String</FormalSpec>
<ReturnType>%Status</ReturnType>
<Implementation><![CDATA[
do ..GetRegularExpressions(.tRegexps)
for i = 1:1:$g(tRegexps) {
write !,"Testing #",i
set tSC = ##class(%iKnow.Matching.Formats.RegularExpression).%New(pDomainId).MatchSingle(pString,$li(tRegexps(i),1,2),.tScore,.tWordBits,,.tOutput)
quit:$$$ISERR(tSC)
if 'tScore {
write " NO MATCH: "_tScore
continue
}
write " MATCH: "_tScore
if $lg(tRegexps(i),4) {
xecute ("(v) set v = "_tOutput, .tEvaluatedValue)
set tOutput = tEvaluatedValue
}
write !," output: '"_tOutput_"'"
}
quit tSC
]]></Implementation>
</Method>
</Class>
</Export>
| {'content_hash': '9eb3653ea64d4179184cc6ae023aadf0', 'timestamp': '', 'source': 'github', 'line_count': 163, 'max_line_length': 158, 'avg_line_length': 31.171779141104295, 'alnum_prop': 0.6831332414878961, 'repo_name': 'bdeboe/isc-iknow-extractor', 'id': '20d47aa26cb84edf5bf537a6e3b73ffdd8f11f6c', 'size': '5081', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Demo/Extractor/Extractor/Regexp.cls.xml', 'mode': '33188', 'license': 'mit', 'language': []} |
//
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Hyak.Common;
using Microsoft.Azure.Search.Models;
using Microsoft.Azure.Search.Tests.Utilities;
using Microsoft.Azure.Test.TestCategories;
using Xunit;
namespace Microsoft.Azure.Search.Tests
{
public sealed class SearchTests : SearchTestBase<DocumentsFixture>
{
[Fact]
public void CanSearchStaticallyTypedDocuments()
{
Run(() =>
{
SearchIndexClient client = Data.GetSearchIndexClientForQuery();
DocumentSearchResponse<Hotel> response = client.Documents.Search<Hotel>("*");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Null(response.ContinuationToken);
Assert.Null(response.Count);
Assert.Null(response.Coverage);
Assert.Null(response.Facets);
Assert.NotNull(response.Results);
Assert.Equal(Data.TestDocuments.Length, response.Results.Count);
for (int i = 0; i < response.Results.Count; i++)
{
Assert.Equal(1, response.Results[i].Score);
Assert.Null(response.Results[i].Highlights);
}
SearchAssert.SequenceEqual(response.Results.Select(r => r.Document), Data.TestDocuments);
});
}
[Fact]
public void CanSearchDynamicDocuments()
{
Run(() =>
{
SearchIndexClient client = Data.GetSearchIndexClientForQuery();
DocumentSearchResponse response = client.Documents.Search("*");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Null(response.ContinuationToken);
Assert.Null(response.Count);
Assert.Null(response.Coverage);
Assert.Null(response.Facets);
Assert.NotNull(response.Results);
Assert.Equal(Data.TestDocuments.Length, response.Results.Count);
for (int i = 0; i < response.Results.Count; i++)
{
Assert.Equal(1, response.Results[i].Score);
Assert.Null(response.Results[i].Highlights);
SearchAssert.DocumentsEqual(Data.TestDocuments[i].AsDocument(), response.Results[i].Document);
}
});
}
[Fact]
public void SearchThrowsWhenRequestIsMalformed()
{
Run(() =>
{
SearchIndexClient client = Data.GetSearchIndexClient();
var invalidParameters = new SearchParameters() { Filter = "This is not a valid filter." };
CloudException e =
Assert.Throws<CloudException>(() => client.Documents.Search("*", invalidParameters));
Assert.Equal(HttpStatusCode.BadRequest, e.Response.StatusCode);
Assert.Contains(
"Invalid expression: Syntax error at position 7 in 'This is not a valid filter.'",
e.Message);
});
}
[Fact]
public void DefaultSearchModeIsAny()
{
Run(() =>
{
SearchIndexClient client = Data.GetSearchIndexClientForQuery();
DocumentSearchResponse<Hotel> response =
client.Documents.Search<Hotel>("Cheapest hotel");
AssertContainsKeys(response, "1", "2", "3");
});
}
[Fact]
public void CanSearchWithSearchModeAll()
{
Run(() =>
{
SearchIndexClient client = Data.GetSearchIndexClientForQuery();
var searchParameters = new SearchParameters() { SearchMode = SearchMode.All };
DocumentSearchResponse<Hotel> response =
client.Documents.Search<Hotel>("Cheapest hotel", searchParameters);
AssertKeySequenceEqual(response, "2");
});
}
[Fact]
public void CanGetResultCountInSearch()
{
Run(() =>
{
SearchIndexClient client = Data.GetSearchIndexClientForQuery();
var searchParameters = new SearchParameters() { IncludeTotalResultCount = true };
DocumentSearchResponse<Hotel> response =
client.Documents.Search<Hotel>("*", searchParameters);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Results);
Assert.Equal(Data.TestDocuments.Length, response.Count);
});
}
[Fact]
public void CanFilter()
{
Run(() =>
{
SearchIndexClient client = Data.GetSearchIndexClientForQuery();
var searchParameters =
new SearchParameters() { Filter = "rating gt 3 and lastRenovationDate gt 2000-01-01T00:00:00Z" };
// Also test that searchText can be null.
DocumentSearchResponse<Hotel> response =
client.Documents.Search<Hotel>(null, searchParameters);
AssertKeySequenceEqual(response, "1", "5");
});
}
[Fact]
public void CanUseHitHighlighting()
{
const string Description = "description";
const string Category = "category";
Run(() =>
{
SearchIndexClient client = Data.GetSearchIndexClientForQuery();
var searchParameters =
new SearchParameters()
{
Filter = "rating eq 5",
HighlightPreTag = "<b>",
HighlightPostTag = "</b>"
};
// Try using the collection without initializing it to make sure it is lazily initialized.
searchParameters.HighlightFields.Add(Description);
searchParameters.HighlightFields.Add(Category);
DocumentSearchResponse<Hotel> response =
client.Documents.Search<Hotel>("luxury hotel", searchParameters);
AssertKeySequenceEqual(response, "1");
HitHighlights highlights = response.Results[0].Highlights;
Assert.NotNull(highlights);
SearchAssert.SequenceEqual(new[] { Description, Category }, highlights.Keys);
string categoryHighlight = highlights[Category].Single();
Assert.Equal("<b>Luxury</b>", categoryHighlight);
string[] expectedDescriptionHighlights =
new[]
{
"Best <b>hotel</b> in town if you like <b>luxury</b> hotels.",
"We highly recommend this <b>hotel</b>."
};
SearchAssert.SequenceEqual(expectedDescriptionHighlights, highlights[Description]);
});
}
[Fact]
public void OrderByProgressivelyBreaksTies()
{
Run(() =>
{
SearchIndexClient client = Data.GetSearchIndexClientForQuery();
var searchParameters =
new SearchParameters()
{
OrderBy = new string[]
{
"rating desc",
"lastRenovationDate asc",
"geo.distance(location, geography'POINT(-122.0 49.0)')"
}
};
DocumentSearchResponse<Hotel> response =
client.Documents.Search<Hotel>("*", searchParameters);
AssertKeySequenceEqual(response, "1", "4", "3", "5", "2", "6");
});
}
[Fact]
public void SearchWithoutOrderBySortsByScore()
{
Run(() =>
{
SearchIndexClient client = Data.GetSearchIndexClientForQuery();
var searchParameters = new SearchParameters() { Filter = "baseRate gt 190" };
DocumentSearchResponse<Hotel> response =
client.Documents.Search<Hotel>("surprisingly expensive hotel", searchParameters);
AssertKeySequenceEqual(response, "6", "1");
Assert.True(response.Results[0].Score > response.Results[1].Score);
});
}
[Fact]
public void CanSearchWithSelectedFields()
{
Run(() =>
{
SearchIndexClient client = Data.GetSearchIndexClientForQuery();
var searchParameters =
new SearchParameters()
{
SearchFields = new[] { "category", "hotelName" },
Select = new[] { "hotelName", "baseRate" }
};
DocumentSearchResponse<Hotel> response =
client.Documents.Search<Hotel>("fancy luxury", searchParameters);
var expectedDoc = new Hotel() { HotelName = "Fancy Stay", BaseRate = 199.0 };
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Results);
Assert.Equal(1, response.Results.Count);
Assert.Equal(expectedDoc, response.Results.First().Document);
});
}
[Fact]
public void CanUseTopAndSkipForClientSidePaging()
{
Run(() =>
{
SearchIndexClient client = Data.GetSearchIndexClientForQuery();
var searchParameters = new SearchParameters() { Top = 3, Skip = 0, OrderBy = new[] { "hotelId" } };
DocumentSearchResponse<Hotel> response = client.Documents.Search<Hotel>("*", searchParameters);
AssertKeySequenceEqual(response, "1", "2", "3");
searchParameters.Skip = 3;
response = client.Documents.Search<Hotel>("*", searchParameters);
AssertKeySequenceEqual(response, "4", "5", "6");
});
}
[Fact]
public void SearchWithScoringProfileBoostsScore()
{
Run(() =>
{
SearchIndexClient client = Data.GetSearchIndexClientForQuery();
var searchParameters =
new SearchParameters()
{
ScoringProfile = "nearest",
ScoringParameters = new[] { "myloc:-122,49" },
Filter = "rating eq 5 or rating eq 1"
};
DocumentSearchResponse<Hotel> response =
client.Documents.Search<Hotel>("hotel", searchParameters);
AssertKeySequenceEqual(response, "2", "1");
});
}
[Fact]
public void CanSearchWithRangeFacets()
{
Run(() =>
{
SearchIndexClient client = Data.GetSearchIndexClientForQuery();
var searchParameters =
new SearchParameters()
{
Facets = new[]
{
"baseRate,values:80|150|200",
"lastRenovationDate,values:2000-01-01T00:00:00Z"
}
};
DocumentSearchResponse<Hotel> response = client.Documents.Search<Hotel>("*", searchParameters);
AssertContainsKeys(response, Data.TestDocuments.Select(d => d.HotelId).ToArray());
Assert.NotNull(response.Facets);
RangeFacetResult<double>[] baseRateFacets = GetRangeFacetsForField<double>(response.Facets, "baseRate", 4);
Assert.False(baseRateFacets[0].From.HasValue);
Assert.Equal(80.0, baseRateFacets[0].To);
Assert.Equal(80.0, baseRateFacets[1].From);
Assert.Equal(150.0, baseRateFacets[1].To);
Assert.Equal(150.0, baseRateFacets[2].From);
Assert.Equal(200.0, baseRateFacets[2].To);
Assert.Equal(200.0, baseRateFacets[3].From);
Assert.False(baseRateFacets[3].To.HasValue);
Assert.Equal(1, baseRateFacets[0].Count);
Assert.Equal(3, baseRateFacets[1].Count);
Assert.Equal(1, baseRateFacets[2].Count);
Assert.Equal(1, baseRateFacets[3].Count);
RangeFacetResult<DateTimeOffset>[] lastRenovationDateFacets =
GetRangeFacetsForField<DateTimeOffset>(response.Facets, "lastRenovationDate", 2);
Assert.False(lastRenovationDateFacets[0].From.HasValue);
Assert.Equal(new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero), lastRenovationDateFacets[0].To);
Assert.Equal(new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero), lastRenovationDateFacets[1].From);
Assert.False(lastRenovationDateFacets[1].To.HasValue);
Assert.Equal(3, lastRenovationDateFacets[0].Count);
Assert.Equal(2, lastRenovationDateFacets[1].Count);
});
}
[Fact]
public void CanSearchWithValueFacets()
{
Run(() =>
{
SearchIndexClient client = Data.GetSearchIndexClientForQuery();
var searchParameters =
new SearchParameters()
{
Facets = new[]
{
"rating,count:2,sort:-value",
"smokingAllowed,sort:count",
"category",
"lastRenovationDate,interval:year",
"baseRate,sort:value",
"tags,sort:value"
}
};
DocumentSearchResponse<Hotel> response = client.Documents.Search<Hotel>("*", searchParameters);
AssertContainsKeys(response, Data.TestDocuments.Select(d => d.HotelId).ToArray());
Assert.NotNull(response.Facets);
AssertValueFacetsEqual(
GetValueFacetsForField<long>(response.Facets, "rating", 2),
new ValueFacetResult<long>(1, 5),
new ValueFacetResult<long>(3, 4));
AssertValueFacetsEqual(
GetValueFacetsForField<bool>(response.Facets, "smokingAllowed", 2),
new ValueFacetResult<bool>(4, false),
new ValueFacetResult<bool>(1, true));
AssertValueFacetsEqual(
GetValueFacetsForField<string>(response.Facets, "category", 2),
new ValueFacetResult<string>(4, "Budget"),
new ValueFacetResult<string>(1, "Luxury"));
AssertValueFacetsEqual(
GetValueFacetsForField<DateTimeOffset>(response.Facets, "lastRenovationDate", 4),
new ValueFacetResult<DateTimeOffset>(1, new DateTimeOffset(1982, 1, 1, 0, 0, 0, TimeSpan.Zero)),
new ValueFacetResult<DateTimeOffset>(2, new DateTimeOffset(1995, 1, 1, 0, 0, 0, TimeSpan.Zero)),
new ValueFacetResult<DateTimeOffset>(1, new DateTimeOffset(2010, 1, 1, 0, 0, 0, TimeSpan.Zero)),
new ValueFacetResult<DateTimeOffset>(1, new DateTimeOffset(2012, 1, 1, 0, 0, 0, TimeSpan.Zero)));
AssertValueFacetsEqual(
GetValueFacetsForField<double>(response.Facets, "baseRate", 4),
new ValueFacetResult<double>(1, 79.99),
new ValueFacetResult<double>(3, 129.99),
new ValueFacetResult<double>(1, 199.0),
new ValueFacetResult<double>(1, 279.99));
AssertValueFacetsEqual(
GetValueFacetsForField<string>(response.Facets, "tags", 6),
new ValueFacetResult<string>(4, "budget"),
new ValueFacetResult<string>(1, "concierge"),
new ValueFacetResult<string>(1, "motel"),
new ValueFacetResult<string>(1, "pool"),
new ValueFacetResult<string>(1, "view"),
new ValueFacetResult<string>(4, "wifi"));
});
}
[Fact]
[Trait(TestTraits.AcceptanceType, TestTraits.LiveBVT)]
public void CanContinueSearchForStaticallyTypedDocuments()
{
Run(() =>
{
SearchIndexClient client = Data.GetSearchIndexClient();
IEnumerable<string> hotelIds = IndexDocuments(client, 2001);
var searchParameters =
new SearchParameters()
{
Top = 3000,
OrderBy = new[] { "hotelId asc" },
Select = new[] { "hotelId" }
};
IEnumerable<string> expectedIds =
Data.TestDocuments.Select(d => d.HotelId).Concat(hotelIds).OrderBy(id => id);
DocumentSearchResponse<Hotel> response = client.Documents.Search<Hotel>("*", searchParameters);
AssertKeySequenceEqual(response, expectedIds.Take(1000).ToArray());
Assert.NotNull(response.ContinuationToken);
response = client.Documents.ContinueSearch<Hotel>(response.ContinuationToken);
AssertKeySequenceEqual(response, expectedIds.Skip(1000).Take(1000).ToArray());
Assert.NotNull(response.ContinuationToken);
response = client.Documents.ContinueSearch<Hotel>(response.ContinuationToken);
AssertKeySequenceEqual(response, expectedIds.Last());
Assert.Null(response.ContinuationToken);
});
}
[Fact]
[Trait(TestTraits.AcceptanceType, TestTraits.LiveBVT)]
public void CanContinueSearchForDynamicDocuments()
{
Run(() =>
{
SearchIndexClient client = Data.GetSearchIndexClient();
IEnumerable<string> hotelIds = IndexDocuments(client, 2001);
var searchParameters =
new SearchParameters()
{
Top = 3000,
OrderBy = new[] { "hotelId asc" },
Select = new[] { "hotelId" }
};
IEnumerable<string> expectedIds =
Data.TestDocuments.Select(d => d.HotelId).Concat(hotelIds).OrderBy(id => id);
DocumentSearchResponse response = client.Documents.Search("*", searchParameters);
AssertKeySequenceEqual(response, expectedIds.Take(1000).ToArray());
Assert.NotNull(response.ContinuationToken);
response = client.Documents.ContinueSearch(response.ContinuationToken);
AssertKeySequenceEqual(response, expectedIds.Skip(1000).Take(1000).ToArray());
Assert.NotNull(response.ContinuationToken);
response = client.Documents.ContinueSearch(response.ContinuationToken);
AssertKeySequenceEqual(response, expectedIds.Last());
Assert.Null(response.ContinuationToken);
});
}
[Fact]
[Trait(TestTraits.AcceptanceType, TestTraits.LiveBVT)]
public void CanContinueSearchWithoutTop()
{
Run(() =>
{
SearchIndexClient client = Data.GetSearchIndexClient();
IEnumerable<string> hotelIds = IndexDocuments(client, 167);
var searchParameters =
new SearchParameters()
{
OrderBy = new[] { "hotelId asc" },
Select = new[] { "hotelId" }
};
IEnumerable<string> expectedIds =
Data.TestDocuments.Select(d => d.HotelId).Concat(hotelIds).OrderBy(id => id);
DocumentSearchResponse<Hotel> response = client.Documents.Search<Hotel>("*", searchParameters);
AssertKeySequenceEqual(response, expectedIds.Take(50).ToArray());
Assert.NotNull(response.ContinuationToken);
response = client.Documents.ContinueSearch<Hotel>(response.ContinuationToken);
AssertKeySequenceEqual(response, expectedIds.Skip(50).Take(50).ToArray());
Assert.NotNull(response.ContinuationToken);
response = client.Documents.ContinueSearch<Hotel>(response.ContinuationToken);
AssertKeySequenceEqual(response, expectedIds.Skip(100).Take(50).ToArray());
Assert.NotNull(response.ContinuationToken);
response = client.Documents.ContinueSearch<Hotel>(response.ContinuationToken);
AssertKeySequenceEqual(response, expectedIds.Skip(150).ToArray());
Assert.Null(response.ContinuationToken);
});
}
[Fact]
[Trait(TestTraits.AcceptanceType, TestTraits.LiveBVT)]
public void CanSearchWithMinimumCoverage()
{
Run(() =>
{
SearchIndexClient client = Data.GetSearchIndexClientForQuery();
var parameters = new SearchParameters() { MinimumCoverage = 50 };
DocumentSearchResponse<Hotel> response = client.Documents.Search<Hotel>("*", parameters);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(100, response.Coverage);
});
}
private IEnumerable<string> IndexDocuments(SearchIndexClient client, int totalDocCount)
{
int existingDocumentCount = Data.TestDocuments.Length;
IEnumerable<string> hotelIds =
Enumerable.Range(existingDocumentCount + 1, totalDocCount - existingDocumentCount)
.Select(id => id.ToString());
IEnumerable<Hotel> hotels = hotelIds.Select(id => new Hotel() { HotelId = id });
List<IndexAction<Hotel>> actions = hotels.Select(h => IndexAction.Create(h)).ToList();
for (int i = 0; i < actions.Count; i += 1000)
{
IEnumerable<IndexAction<Hotel>> nextActions = actions.Skip(i).Take(1000);
if (!nextActions.Any())
{
break;
}
var batch = IndexBatch.Create(nextActions);
client.Documents.Index(batch);
SearchTestUtilities.WaitForIndexing();
}
return hotelIds;
}
private void AssertKeySequenceEqual(DocumentSearchResponse<Hotel> response, params string[] expectedKeys)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Results);
IEnumerable<string> actualKeys = response.Results.Select(r => r.Document.HotelId);
SearchAssert.SequenceEqual(expectedKeys, actualKeys);
}
private void AssertKeySequenceEqual(DocumentSearchResponse response, params string[] expectedKeys)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Results);
IEnumerable<string> actualKeys = response.Results.Select(r => (string)r.Document["hotelId"]);
SearchAssert.SequenceEqual(expectedKeys, actualKeys);
}
private void AssertContainsKeys(DocumentSearchResponse<Hotel> response, params string[] expectedKeys)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Results);
IEnumerable<string> actualKeys = response.Results.Select(r => r.Document.HotelId);
foreach (string expectedKey in expectedKeys)
{
Assert.Contains(expectedKey, actualKeys);
}
}
private void AssertContainsKeys(DocumentSearchResponse response, params string[] expectedKeys)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Results);
IEnumerable<string> actualKeys = response.Results.Select(r => (string)r.Document["hotelId"]);
foreach (string expectedKey in expectedKeys)
{
Assert.Contains(expectedKey, actualKeys);
}
}
private IList<FacetResult> GetFacetsForField(FacetResults facets, string expectedField, int expectedCount)
{
Assert.True(facets.ContainsKey(expectedField));
IList<FacetResult> facetCollection = facets[expectedField];
Assert.Equal(expectedCount, facetCollection.Count);
return facetCollection;
}
private RangeFacetResult<T>[] GetRangeFacetsForField<T>(FacetResults facets, string expectedField, int expectedCount)
where T : struct
{
IList<FacetResult> facetCollection = GetFacetsForField(facets, expectedField, expectedCount);
return facetCollection.Select(f => f.AsRangeFacetResult<T>()).ToArray();
}
private ValueFacetResult<T>[] GetValueFacetsForField<T>(FacetResults facets, string expectedField, int expectedCount)
{
IList<FacetResult> facetCollection = GetFacetsForField(facets, expectedField, expectedCount);
return facetCollection.Select(f => f.AsValueFacetResult<T>()).ToArray();
}
private void AssertValueFacetsEqual<T>(ValueFacetResult<T>[] actualFacets, params ValueFacetResult<T>[] expectedFacets)
{
Assert.Equal(actualFacets.Length, expectedFacets.Length);
for (int i = 0; i < actualFacets.Length; i++)
{
Assert.Equal(expectedFacets[i].Value, actualFacets[i].Value);
Assert.Equal(expectedFacets[i].Count, actualFacets[i].Count);
}
}
}
}
| {'content_hash': '2bb174c07856db2de1c1385dbe3a5ef6', 'timestamp': '', 'source': 'github', 'line_count': 667, 'max_line_length': 127, 'avg_line_length': 40.599700149925035, 'alnum_prop': 0.551698670605613, 'repo_name': 'tpeplow/azure-sdk-for-net', 'id': '2f3990a66a5ededdb46c58aab55e1a244cd4d5c2', 'size': '27082', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'src/Search/Search.Tests/Tests/SearchTests.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '118'}, {'name': 'Batchfile', 'bytes': '817'}, {'name': 'C#', 'bytes': '55681494'}, {'name': 'CSS', 'bytes': '685'}, {'name': 'Gherkin', 'bytes': '89597'}, {'name': 'JavaScript', 'bytes': '1719'}, {'name': 'PowerShell', 'bytes': '24329'}, {'name': 'Shell', 'bytes': '45'}]} |
import logging
import unittest
from concurrent import futures
import grpc
from apache_beam.portability.runners.api import beam_fn_api_pb2
from apache_beam.runners.worker import log_handler
class BeamFnLoggingServicer(beam_fn_api_pb2.BeamFnLoggingServicer):
def __init__(self):
self.log_records_received = []
def Logging(self, request_iterator, context):
for log_record in request_iterator:
self.log_records_received.append(log_record)
yield beam_fn_api_pb2.LogControl()
class FnApiLogRecordHandlerTest(unittest.TestCase):
def setUp(self):
self.test_logging_service = BeamFnLoggingServicer()
self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
beam_fn_api_pb2.add_BeamFnLoggingServicer_to_server(
self.test_logging_service, self.server)
self.test_port = self.server.add_insecure_port('[::]:0')
self.server.start()
self.logging_service_descriptor = beam_fn_api_pb2.ApiServiceDescriptor()
self.logging_service_descriptor.url = 'localhost:%s' % self.test_port
self.fn_log_handler = log_handler.FnApiLogRecordHandler(
self.logging_service_descriptor)
logging.getLogger().setLevel(logging.INFO)
logging.getLogger().addHandler(self.fn_log_handler)
def tearDown(self):
# wait upto 5 seconds.
self.server.stop(5)
def _verify_fn_log_handler(self, num_log_entries):
msg = 'Testing fn logging'
logging.debug('Debug Message 1')
for idx in range(num_log_entries):
logging.info('%s: %s', msg, idx)
logging.debug('Debug Message 2')
# Wait for logs to be sent to server.
self.fn_log_handler.close()
num_received_log_entries = 0
for outer in self.test_logging_service.log_records_received:
for log_entry in outer.log_entries:
self.assertEqual(beam_fn_api_pb2.LogEntry.INFO, log_entry.severity)
self.assertEqual('%s: %s' % (msg, num_received_log_entries),
log_entry.message)
self.assertEqual(u'log_handler_test._verify_fn_log_handler',
log_entry.log_location)
self.assertGreater(log_entry.timestamp.seconds, 0)
self.assertGreater(log_entry.timestamp.nanos, 0)
num_received_log_entries += 1
self.assertEqual(num_received_log_entries, num_log_entries)
# Test cases.
data = {
'one_batch': log_handler.FnApiLogRecordHandler._MAX_BATCH_SIZE - 47,
'exact_multiple': log_handler.FnApiLogRecordHandler._MAX_BATCH_SIZE,
'multi_batch': log_handler.FnApiLogRecordHandler._MAX_BATCH_SIZE * 3 + 47
}
def _create_test(name, num_logs):
setattr(FnApiLogRecordHandlerTest, 'test_%s' % name,
lambda self: self._verify_fn_log_handler(num_logs))
if __name__ == '__main__':
for test_name, num_logs_entries in data.iteritems():
_create_test(test_name, num_logs_entries)
unittest.main()
| {'content_hash': '6431e9ad91b2d0c3f08b8e60968c01ee', 'timestamp': '', 'source': 'github', 'line_count': 87, 'max_line_length': 77, 'avg_line_length': 32.839080459770116, 'alnum_prop': 0.6951347567378369, 'repo_name': 'manuzhang/incubator-beam', 'id': '6dd018f6ad457c2973e7e383c70aa9aa9d272e33', 'size': '3643', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'sdks/python/apache_beam/runners/worker/log_handler_test.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '9463722'}, {'name': 'Protocol Buffer', 'bytes': '1407'}, {'name': 'Shell', 'bytes': '6581'}]} |
var DEBUG = false; // `true` to print debugging info.
var TIMER = false; // `true` to time calls to `parse()` and print the results.
var debug = require('./debug')('parse');
var lex = require('./lexer');
exports = module.exports = parse;
var _comments; // Whether comments are allowed.
var _depth; // Current block nesting depth.
var _position; // Whether to include line/column position.
var _tokens; // Array of lexical tokens.
/**
* Convert a CSS string or array of lexical tokens into a `stringify`-able AST.
*
* @param {String} css CSS string or array of lexical token
* @param {Object} [options]
* @param {Boolean} [options.comments=false] allow comment nodes in the AST
* @returns {Object} `stringify`-able AST
*/
function parse(css, options) {
var start; // Debug timer start.
options || (options = {});
_comments = !!options.comments;
_position = !!options.position;
_depth = 0;
// Operate on a copy of the given tokens, or the lex()'d CSS string.
_tokens = Array.isArray(css) ? css.slice() : lex(css);
var rule;
var rules = [];
var token;
TIMER && (start = Date.now());
while ((token = next())) {
rule = parseToken(token);
rule && rules.push(rule);
}
TIMER && debug('ran in', (Date.now() - start) + 'ms');
return {
type: "stylesheet",
stylesheet: {
rules: rules
}
};
}
// -- Functions --------------------------------------------------------------
/**
* Build an AST node from a lexical token.
*
* @param {Object} token lexical token
* @param {Object} [override] object hash of properties that override those
* already in the token, or that will be added to the token.
* @returns {Object} AST node
*/
function astNode(token, override) {
override || (override = {});
var key;
var keys = ['type', 'name', 'value'];
var node = {};
// Avoiding [].forEach for performance reasons.
for (var i = 0; i < keys.length; ++i) {
key = keys[i];
if (token[key]) {
node[key] = override[key] || token[key];
}
}
keys = Object.keys(override);
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (!node[key]) {
node[key] = override[key];
}
}
if (_position) {
node.position = {
start: token.start,
end: token.end
};
}
DEBUG && debug('astNode:', JSON.stringify(node, null, 2));
return node;
}
/**
* Remove a lexical token from the stack and return the removed token.
*
* @returns {Object} lexical token
*/
function next() {
var token = _tokens.shift();
DEBUG && debug('next:', JSON.stringify(token, null, 2));
return token;
}
// -- Parse* Functions ---------------------------------------------------------
/**
* Convert an @-group lexical token to an AST node.
*
* @param {Object} token @-group lexical token
* @returns {Object} @-group AST node
*/
function parseAtGroup(token) {
_depth = _depth + 1;
// As the @-group token is assembled, relevant token values are captured here
// temporarily. They will later be used as `tokenize()` overrides.
var overrides = {};
switch (token.type) {
case 'font-face':
case 'viewport' :
overrides.declarations = parseDeclarations();
break;
case 'page':
overrides.prefix = token.prefix;
overrides.declarations = parseDeclarations();
break;
default:
overrides.prefix = token.prefix;
overrides.rules = parseRules();
}
return astNode(token, overrides);
}
/**
* Convert an @import lexical token to an AST node.
*
* @param {Object} token @import lexical token
* @returns {Object} @import AST node
*/
function parseAtImport(token) {
return astNode(token);
}
/**
* Convert an @charset token to an AST node.
*
* @param {Object} token @charset lexical token
* @returns {Object} @charset node
*/
function parseCharset(token) {
return astNode(token);
}
/**
* Convert a comment token to an AST Node.
*
* @param {Object} token comment lexical token
* @returns {Object} comment node
*/
function parseComment(token) {
return astNode(token, {text: token.text});
}
function parseNamespace(token) {
return astNode(token);
}
/**
* Convert a property lexical token to a property AST node.
*
* @returns {Object} property node
*/
function parseProperty(token) {
return astNode(token);
}
/**
* Convert a selector lexical token to a selector AST node.
*
* @param {Object} token selector lexical token
* @returns {Object} selector node
*/
function parseSelector(token) {
function trim(str) {
return str.trim();
}
return astNode(token, {
type: 'rule',
selectors: token.text.split(',').map(trim),
declarations: parseDeclarations(token)
});
}
/**
* Convert a lexical token to an AST node.
*
* @returns {Object|undefined} AST node
*/
function parseToken(token) {
switch (token.type) {
// Cases are listed in roughly descending order of probability.
case 'property': return parseProperty(token);
case 'selector': return parseSelector(token);
case 'at-group-end': _depth = _depth - 1; return;
case 'media' :
case 'keyframes' :return parseAtGroup(token);
case 'comment': if (_comments) { return parseComment(token); } break;
case 'charset': return parseCharset(token);
case 'import': return parseAtImport(token);
case 'namespace': return parseNamespace(token);
case 'font-face':
case 'supports' :
case 'viewport' :
case 'document' :
case 'page' : return parseAtGroup(token);
}
DEBUG && debug('parseToken: unexpected token:', JSON.stringify(token));
}
// -- Parse Helper Functions ---------------------------------------------------
/**
* Iteratively parses lexical tokens from the stack into AST nodes until a
* conditional function returns `false`, at which point iteration terminates
* and any AST nodes collected are returned.
*
* @param {Function} conditionFn
* @param {Object} token the lexical token being parsed
* @returns {Boolean} `true` if the token should be parsed, `false` otherwise
* @return {Array} AST nodes
*/
function parseTokensWhile(conditionFn) {
var node;
var nodes = [];
var token;
while ((token = next()) && (conditionFn && conditionFn(token))) {
node = parseToken(token);
node && nodes.push(node);
}
// Place an unused non-`end` lexical token back onto the stack.
if (token && token.type !== 'end') {
_tokens.unshift(token);
}
return nodes;
}
/**
* Convert a series of tokens into a sequence of declaration AST nodes.
*
* @returns {Array} declaration nodes
*/
function parseDeclarations() {
return parseTokensWhile(function (token) {
return (token.type === 'property' || token.type === 'comment');
});
}
/**
* Convert a series of tokens into a sequence of rule nodes.
*
* @returns {Array} rule nodes
*/
function parseRules() {
return parseTokensWhile(function () { return _depth; });
}
| {'content_hash': '31710b0030b4b5d12eda1c2ec1186aed', 'timestamp': '', 'source': 'github', 'line_count': 291, 'max_line_length': 80, 'avg_line_length': 23.584192439862544, 'alnum_prop': 0.6325222206032347, 'repo_name': 'brettstimmerman/mensch', 'id': '219dc6fb153c91c8a71c0a620441621256a1d497', 'size': '6863', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'lib/parser.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '48302'}, {'name': 'Makefile', 'bytes': '192'}]} |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Automation.Common;
using Microsoft.Azure.Commands.Automation.Properties;
using System.Management.Automation;
using System.Security.Permissions;
namespace Microsoft.Azure.Commands.Automation.Cmdlet
{
/// <summary>
/// Removes a Credential for automation.
/// </summary>
[Cmdlet(VerbsCommon.Remove, "AzureRmAutomationCredential", DefaultParameterSetName = AutomationCmdletParameterSets.ByName)]
public class RemoveAzureAutomationCredential : AzureAutomationBaseCmdlet
{
/// <summary>
/// Gets or sets the credential name.
/// </summary>
[Parameter(ParameterSetName = AutomationCmdletParameterSets.ByName, Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The credential name.")]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
[Parameter(ParameterSetName = AutomationCmdletParameterSets.ByName, Position = 3, HelpMessage = "Confirm the removal of the credential")]
public SwitchParameter Force { get; set; }
/// <summary>
/// Execute this cmdlet.
/// </summary>
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
protected override void AutomationProcessRecord()
{
ConfirmAction(
Force.IsPresent,
string.Format(Resources.RemovingAzureAutomationResourceWarning, "Credential"),
string.Format(Resources.RemoveAzureAutomationResourceDescription, "Credential"),
Name,
() =>
{
this.AutomationClient.DeleteCredential(this.ResourceGroupName, this.AutomationAccountName, Name);
});
}
}
}
| {'content_hash': '443ed8e6fc607717b568e9f948e7e93b', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 186, 'avg_line_length': 46.74545454545454, 'alnum_prop': 0.6281602489303773, 'repo_name': 'Matt-Westphal/azure-powershell', 'id': '474fc78bfbc0be2dfeb3d86fd74bcef150a48ddb', 'size': '2573', 'binary': False, 'copies': '2', 'ref': 'refs/heads/dev', 'path': 'src/ResourceManager/Automation/Commands.Automation/Cmdlet/RemoveAzureAutomationCredential.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '15822'}, {'name': 'C#', 'bytes': '25252191'}, {'name': 'HTML', 'bytes': '209'}, {'name': 'JavaScript', 'bytes': '4979'}, {'name': 'PHP', 'bytes': '41'}, {'name': 'PowerShell', 'bytes': '2173997'}, {'name': 'Shell', 'bytes': '50'}]} |
package org.jf.util;
import junit.framework.Assert;
import org.junit.Test;
public class NumberUtilsTest {
@Test
public void isLikelyFloatTest() {
Assert.assertTrue(NumberUtils.isLikelyFloat(Float.floatToRawIntBits(1.23f)));
Assert.assertTrue(NumberUtils.isLikelyFloat(Float.floatToRawIntBits(1.0f)));
Assert.assertTrue(NumberUtils.isLikelyFloat(Float.floatToRawIntBits(Float.NaN)));
Assert.assertTrue(NumberUtils.isLikelyFloat(Float.floatToRawIntBits(Float.NEGATIVE_INFINITY)));
Assert.assertTrue(NumberUtils.isLikelyFloat(Float.floatToRawIntBits(Float.POSITIVE_INFINITY)));
Assert.assertTrue(NumberUtils.isLikelyFloat(Float.floatToRawIntBits(1e-30f)));
Assert.assertTrue(NumberUtils.isLikelyFloat(Float.floatToRawIntBits(1000f)));
Assert.assertTrue(NumberUtils.isLikelyFloat(Float.floatToRawIntBits(1f)));
Assert.assertTrue(NumberUtils.isLikelyFloat(Float.floatToRawIntBits(-1f)));
Assert.assertTrue(NumberUtils.isLikelyFloat(Float.floatToRawIntBits(-5f)));
Assert.assertTrue(NumberUtils.isLikelyFloat(Float.floatToRawIntBits(1.3333f)));
Assert.assertTrue(NumberUtils.isLikelyFloat(Float.floatToRawIntBits(4.5f)));
Assert.assertTrue(NumberUtils.isLikelyFloat(Float.floatToRawIntBits(.1f)));
Assert.assertTrue(NumberUtils.isLikelyFloat(Float.floatToRawIntBits(50000f)));
Assert.assertTrue(NumberUtils.isLikelyFloat(Float.floatToRawIntBits(Float.MAX_VALUE)));
Assert.assertTrue(NumberUtils.isLikelyFloat(Float.floatToRawIntBits((float)Math.PI)));
Assert.assertTrue(NumberUtils.isLikelyFloat(Float.floatToRawIntBits((float)Math.E)));
Assert.assertTrue(NumberUtils.isLikelyFloat(2139095039));
// Float.MIN_VALUE is equivalent to integer value 1 - this should be detected as an integer
//Assert.assertTrue(NumberUtils.isLikelyFloat(Float.floatToRawIntBits(Float.MIN_VALUE)));
// This one doesn't quite work. It has a series of 2 0's, but that is probably not enough to strip off normally
//Assert.assertTrue(NumberUtils.isLikelyFloat(Float.floatToRawIntBits(1.33333f)));
Assert.assertFalse(NumberUtils.isLikelyFloat(0));
Assert.assertFalse(NumberUtils.isLikelyFloat(1));
Assert.assertFalse(NumberUtils.isLikelyFloat(10));
Assert.assertFalse(NumberUtils.isLikelyFloat(100));
Assert.assertFalse(NumberUtils.isLikelyFloat(1000));
Assert.assertFalse(NumberUtils.isLikelyFloat(1024));
Assert.assertFalse(NumberUtils.isLikelyFloat(1234));
Assert.assertFalse(NumberUtils.isLikelyFloat(-5));
Assert.assertFalse(NumberUtils.isLikelyFloat(-13));
Assert.assertFalse(NumberUtils.isLikelyFloat(-123));
Assert.assertFalse(NumberUtils.isLikelyFloat(20000000));
Assert.assertFalse(NumberUtils.isLikelyFloat(2000000000));
Assert.assertFalse(NumberUtils.isLikelyFloat(-2000000000));
Assert.assertFalse(NumberUtils.isLikelyFloat(Integer.MAX_VALUE));
Assert.assertFalse(NumberUtils.isLikelyFloat(Integer.MIN_VALUE));
Assert.assertFalse(NumberUtils.isLikelyFloat(Short.MIN_VALUE));
Assert.assertFalse(NumberUtils.isLikelyFloat(Short.MAX_VALUE));
}
@Test
public void isLikelyDoubleTest() {
Assert.assertTrue(NumberUtils.isLikelyDouble(Double.doubleToRawLongBits(1.23f)));
Assert.assertTrue(NumberUtils.isLikelyDouble(Double.doubleToRawLongBits(1.0f)));
Assert.assertTrue(NumberUtils.isLikelyDouble(Double.doubleToRawLongBits(Double.NaN)));
Assert.assertTrue(NumberUtils.isLikelyDouble(Double.doubleToRawLongBits(Double.NEGATIVE_INFINITY)));
Assert.assertTrue(NumberUtils.isLikelyDouble(Double.doubleToRawLongBits(Double.POSITIVE_INFINITY)));
Assert.assertTrue(NumberUtils.isLikelyDouble(Double.doubleToRawLongBits(1e-30f)));
Assert.assertTrue(NumberUtils.isLikelyDouble(Double.doubleToRawLongBits(1000f)));
Assert.assertTrue(NumberUtils.isLikelyDouble(Double.doubleToRawLongBits(1f)));
Assert.assertTrue(NumberUtils.isLikelyDouble(Double.doubleToRawLongBits(-1f)));
Assert.assertTrue(NumberUtils.isLikelyDouble(Double.doubleToRawLongBits(-5f)));
Assert.assertTrue(NumberUtils.isLikelyDouble(Double.doubleToRawLongBits(1.3333f)));
Assert.assertTrue(NumberUtils.isLikelyDouble(Double.doubleToRawLongBits(1.33333f)));
Assert.assertTrue(NumberUtils.isLikelyDouble(Double.doubleToRawLongBits(4.5f)));
Assert.assertTrue(NumberUtils.isLikelyDouble(Double.doubleToRawLongBits(.1f)));
Assert.assertTrue(NumberUtils.isLikelyDouble(Double.doubleToRawLongBits(50000f)));
Assert.assertTrue(NumberUtils.isLikelyDouble(Double.doubleToRawLongBits(Double.MAX_VALUE)));
Assert.assertTrue(NumberUtils.isLikelyDouble(Double.doubleToRawLongBits(Math.PI)));
Assert.assertTrue(NumberUtils.isLikelyDouble(Double.doubleToRawLongBits(Math.E)));
// Double.MIN_VALUE is equivalent to integer value 1 - this should be detected as an integer
//Assert.assertTrue(NumberUtils.isLikelyDouble(Double.doubleToRawLongBits(Double.MIN_VALUE)));
Assert.assertFalse(NumberUtils.isLikelyDouble(0));
Assert.assertFalse(NumberUtils.isLikelyDouble(1));
Assert.assertFalse(NumberUtils.isLikelyDouble(10));
Assert.assertFalse(NumberUtils.isLikelyDouble(100));
Assert.assertFalse(NumberUtils.isLikelyDouble(1000));
Assert.assertFalse(NumberUtils.isLikelyDouble(1024));
Assert.assertFalse(NumberUtils.isLikelyDouble(1234));
Assert.assertFalse(NumberUtils.isLikelyDouble(-5));
Assert.assertFalse(NumberUtils.isLikelyDouble(-13));
Assert.assertFalse(NumberUtils.isLikelyDouble(-123));
Assert.assertFalse(NumberUtils.isLikelyDouble(20000000));
Assert.assertFalse(NumberUtils.isLikelyDouble(2000000000));
Assert.assertFalse(NumberUtils.isLikelyDouble(-2000000000));
Assert.assertFalse(NumberUtils.isLikelyDouble(Integer.MAX_VALUE));
Assert.assertFalse(NumberUtils.isLikelyDouble(Integer.MIN_VALUE));
Assert.assertFalse(NumberUtils.isLikelyDouble(Short.MIN_VALUE));
Assert.assertFalse(NumberUtils.isLikelyDouble(Short.MAX_VALUE));
}
}
| {'content_hash': 'ceb5020081df8648b78b652304936490', 'timestamp': '', 'source': 'github', 'line_count': 99, 'max_line_length': 119, 'avg_line_length': 63.63636363636363, 'alnum_prop': 0.756984126984127, 'repo_name': 'admin-zhx/Apktool', 'id': 'a059c87d70d556c0e0d0dea53766c26be861b2a5', 'size': '7862', 'binary': False, 'copies': '47', 'ref': 'refs/heads/master', 'path': 'brut.apktool.smali/util/src/test/java/org/jf/util/NumberUtilsTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '161'}, {'name': 'GAP', 'bytes': '95305'}, {'name': 'Java', 'bytes': '3329733'}, {'name': 'Lex', 'bytes': '21679'}, {'name': 'Ragel in Ruby Host', 'bytes': '16584'}, {'name': 'Shell', 'bytes': '4706'}, {'name': 'Smali', 'bytes': '50376'}]} |
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using System.IO;
//-------------------------------------------------------------------------------------
// ***** OculusBuildDemo
//
// OculusBuild allows for command line building of the Oculus main demo (Tuscany).
//
[InitializeOnLoad]
class OVRShimLoader
{
static OVRShimLoader()
{
EditorApplication.update += Update;
}
static void Update()
{
#if !UNITY_EDITOR_OSX && !UNITY_STANDALONE_OSX
// Suppresses the resolution dialog and sets Rift-optimized launch settings.
if (_isEnabled)
{
PlayerSettings.displayResolutionDialog = ResolutionDialogSetting.HiddenByDefault;
PlayerSettings.defaultIsFullScreen = false;
PlayerSettings.defaultScreenWidth = 1920;
PlayerSettings.defaultScreenHeight = 1080;
}
#endif
}
[PreferenceItem("Oculus VR")]
static void PreferencesGUI()
{
// Load the preferences
if (!_prefsLoaded) {
_isEnabled = EditorPrefs.GetBool ("OculusBuild", false);
_prefsLoaded = true;
}
// Preferences GUI
_isEnabled = EditorGUILayout.Toggle ("Optimize Builds for Rift", _isEnabled);
// Save the preferences
if (GUI.changed)
EditorPrefs.SetBool ("OculusBuild", _isEnabled);
}
/// <summary>
/// Replaces the built standalone with an auto-patcher for the same architecture.
/// </summary>
[PostProcessBuild]
public static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject)
{
// Figure out which architecture we're building for.
int arch;
if (target == BuildTarget.StandaloneWindows)
arch = 32;
else if (target == BuildTarget.StandaloneWindows64)
arch = 64;
else
return;
// Rename the target to a .bin file for the auto-patcher to find later.
string autoPatcherPath = Application.dataPath + "/OVR/Editor/OculusUnityPatcher_" + arch.ToString() + ".exe";
string targetPath = pathToBuiltProject.Replace(".exe", "_DirectToRift.exe");
if (File.Exists(targetPath))
File.Delete(targetPath);
File.Copy(autoPatcherPath, targetPath);
Debug.Log ("Patched " + pathToBuiltProject + " for " + target.ToString() + ".");
}
static bool _isEnabled = true;
static bool _prefsLoaded = false;
} | {'content_hash': 'c73faab944bcaa638ed5796ce1c191cc', 'timestamp': '', 'source': 'github', 'line_count': 80, 'max_line_length': 111, 'avg_line_length': 27.3375, 'alnum_prop': 0.6904435299497028, 'repo_name': 'johnsietsma/eons', 'id': '7f03ce81cb0a96c338271af07cd8d110f168c22c', 'size': '3312', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'Assets/OVR/Editor/OVRShimLoader.cs', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '378552'}, {'name': 'C#', 'bytes': '636861'}, {'name': 'JavaScript', 'bytes': '231241'}, {'name': 'Smalltalk', 'bytes': '3621'}]} |
const _ = require('lodash');
const safeJSONParse = str => JSON.parse(str) || {};
const mergeWithDefaultJobsData = jobsData => {
let defaultJobsData = {
list: [],
filter: '',
filterFn: () => true // allow anything
};
return _.merge(defaultJobsData, jobsData);
}
export default function deserialize(localStorageValue$) {
return localStorageValue$
.map(safeJSONParse)
.map(mergeWithDefaultJobsData);
};
| {'content_hash': 'eda63e2beb3cf3bf63fabbf6597d7033', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 57, 'avg_line_length': 25.352941176470587, 'alnum_prop': 0.6728538283062645, 'repo_name': 'travenasty/orb.zone', 'id': '46b21f1bbe247d298b1ce993474adc85bec4a02f', 'size': '431', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/components/orb/job/source.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '3160'}, {'name': 'HTML', 'bytes': '1148'}, {'name': 'JavaScript', 'bytes': '1548376'}]} |
from ast import literal_eval
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from django.conf import settings
from rest_framework import authentication, permissions,\
viewsets, filters, response, status
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from bokeh.embed import autoload_server
from .forms import JobFilter
from .models import Job, Metric, Measurement, VersionedPackage
from .serializers import JobSerializer, MetricSerializer,\
RegressionSerializer
try:
bokeh_url = settings.BOKEH_URL
except AttributeError:
# if not specified use the default which is localhost:5006
bokeh_url = 'default'
class DefaultsMixin(object):
"""
Default settings for view authentication, permissions,
filtering and pagination.
"""
authentication_classes = (
authentication.BasicAuthentication,
authentication.TokenAuthentication,
)
permission_classes = (
permissions.IsAuthenticatedOrReadOnly,
)
paginate_by = 100
# list of available filter_backends, will enable these for all ViewSets
filter_backends = (
filters.DjangoFilterBackend,
filters.SearchFilter,
filters.OrderingFilter,
)
class JobViewSet(DefaultsMixin, CacheResponseMixin, viewsets.ModelViewSet):
"""API endpoint for listing and creating jobs"""
queryset = Job.objects.\
prefetch_related('packages', 'measurements').order_by('date')
serializer_class = JobSerializer
filter_class = JobFilter
search_fields = ('ci_id',)
ordering_fields = ('date',)
class MeasurementViewSet(DefaultsMixin, CacheResponseMixin,
viewsets.ModelViewSet):
"""API endpoint consumed by the monitor app"""
queryset = Measurement.objects.\
prefetch_related('job', 'metric').order_by('job__date')
serializer_class = RegressionSerializer
filter_fields = ('job__ci_dataset', 'metric')
class MetricViewSet(DefaultsMixin, CacheResponseMixin, viewsets.ModelViewSet):
"""API endpoint for listing and creating metrics"""
queryset = Metric.objects.order_by('metric')
serializer_class = MetricSerializer
def create(self, request, *args, **kwargs):
# many=True for adding multiple items at once
serializer = self.get_serializer(data=request.data,
many=isinstance(request.data, list))
serializer.is_valid(raise_exception=True)
serializer.save()
return response.Response(serializer.data,
status=status.HTTP_201_CREATED)
search_fields = ('metric', )
ordering_fields = ('metric',)
class DatasetViewSet(DefaultsMixin, viewsets.ViewSet):
"""API endpoint for listing datasets"""
def list(self, request):
datasets = Job.objects.values_list('ci_dataset', flat=True).distinct()
return response.Response(datasets)
class DefaultsViewSet(DefaultsMixin, viewsets.ViewSet):
"""
API endpoint for listing default values used by
the bokeh apps
"""
def get_defaults(self):
queryset = Job.objects.values('ci_id', 'ci_dataset').latest('pk')
ci_id = queryset['ci_id']
ci_dataset = queryset['ci_dataset']
queryset = Metric.objects.values_list('metric', flat=True)
if 'AM1' in queryset:
metric = 'AM1'
else:
metric = queryset.latest('pk')
snr_cut = '100'
window = 'months'
return {'ci_id': ci_id, 'ci_dataset': ci_dataset,
'metric': metric, 'snr_cut': snr_cut,
'window': window}
def list(self, request):
defaults = self.get_defaults()
return response.Response(defaults)
class BokehAppViewSet(DefaultsMixin, viewsets.ViewSet):
def get_app_data(self, ci_id, ci_dataset, metric):
data = {}
blobs = Job.objects.filter(ci_id=ci_id,
ci_dataset=ci_dataset).values('blobs')
metadata = Measurement.\
objects.filter(metric=metric, job__ci_id=ci_id,
job__ci_dataset=ci_dataset).values('metadata')
if metadata.exists():
# workaround for getting item from queryset
metadata = metadata[0]['metadata']
if metadata:
metadata = literal_eval(literal_eval(metadata))
blob_id = metadata.pop('blobs')
data['metadata'] = metadata
if blobs.exists():
# workaround for getting item from queryset
blobs = blobs[0]['blobs']
if blobs:
blobs = literal_eval(literal_eval(blobs))
for blob in blobs:
# Look up for data blobs
if blob['identifier'] == blob_id['matchedDataset']:
data['matchedDataset'] = blob['data']
elif blob['identifier'] == blob_id['photomModel']:
data['photomModel'] = blob['data']
elif blob['identifier'] == blob_id['astromModel']:
data['astromModel'] = blob['data']
return data
def list(self, request):
defaults = DefaultsViewSet().get_defaults()
ci_id = self.request.query_params.get('ci_id',
defaults['ci_id'])
ci_dataset = self.request.query_params.get('ci_dataset',
defaults['ci_dataset'])
metric = self.request.query_params.get('metric',
defaults['metric'])
data = self.get_app_data(ci_id, ci_dataset, metric)
return response.Response(data)
def embed_bokeh(request, bokeh_app):
"""Render the requested app from the bokeh server"""
# http://bokeh.pydata.org/en/0.12.3/docs/reference/embed.html
# TODO: test if bokeh server is reachable
bokeh_script = autoload_server(None, app_path="/{}".format(bokeh_app),
url=bokeh_url)
template = loader.get_template('dashboard/embed_bokeh.html')
context = {'bokeh_script': bokeh_script,
'bokeh_app': bokeh_app}
response = HttpResponse(template.render(context, request))
# Save full url path in the HTTP response, so that the bokeh
# app can use this info, e.g:
# http://localhost:8000/dashboard/AMx/?metric=AM1&ci_dataset=cfht&ci_id=452
response.set_cookie('django_full_path', request.get_full_path())
return response
def home(request):
"""Render the home page"""
n_metrics = len(Metric.objects.all())
job = Job.objects.latest('pk')
n_packages = len(VersionedPackage.objects.filter(job=job))
n_jobs = len(Job.objects.all())
n_meas = len(Measurement.objects.all())
datasets = Job.objects.values_list('ci_dataset', flat=True).distinct()
last = Job.objects.latest('pk').date
context = {"n_metrics": n_metrics,
"n_packages": n_packages,
"n_jobs": n_jobs,
"n_meas": n_meas,
"datasets": ", ".join(datasets),
"last": last}
return render(request, 'dashboard/index.html', context)
| {'content_hash': '476dec8550919494667d4e83d6e18c78', 'timestamp': '', 'source': 'github', 'line_count': 230, 'max_line_length': 79, 'avg_line_length': 32.208695652173915, 'alnum_prop': 0.6016468682505399, 'repo_name': 'lsst-sqre/qa-dashboard', 'id': '1a365153b01ada4fd2a611984db03b5bba9a04b0', 'size': '7408', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'squash/dashboard/views.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '133'}, {'name': 'HTML', 'bytes': '8535'}, {'name': 'Makefile', 'bytes': '98'}, {'name': 'Python', 'bytes': '75162'}, {'name': 'Shell', 'bytes': '338'}]} |
<?php
namespace Vmwarephp;
class Autoloader {
private $fileExtension = '.php';
private $namespace;
private $includePath;
private $namespaceSeparator = '\\';
public function __construct($ns = 'Vmwarephp', $includePath = null) {
$this->namespace = $ns;
$this->includePath = $includePath ? : $this->getLibraryPath();
}
public function setNamespaceSeparator($sep) {
$this->namespaceSeparator = $sep;
}
public function getNamespaceSeparator() {
return $this->namespaceSeparator;
}
public function setIncludePath($includePath) {
$this->includePath = $includePath;
}
public function getIncludePath() {
return $this->includePath;
}
public function setFileExtension($fileExtension) {
$this->fileExtension = $fileExtension;
}
public function getFileExtension() {
return $this->fileExtension;
}
public function register() {
spl_autoload_register(array($this, 'loadClass'));
}
public function unregister() {
spl_autoload_unregister(array($this, 'loadClass'));
}
public function loadClass($className) {
if (strpos($className, $this->namespace) === false) {
require_once 'TypeDefinitions.inc';
return;
}
if (is_null($this->namespace) || $this->namespace . $this->namespaceSeparator === substr($className, 0, strlen($this->namespace . $this->namespaceSeparator))) {
$fileDirectoryPath = '';
$lastNsPos = strripos($className, $this->namespaceSeparator);
if ($lastNsPos !== false) {
$namespace = $this->getNamespaceFromClassName($className, $lastNsPos);
$shortClassName = $this->getShortClassName($className, $lastNsPos);
$fileDirectoryPath .= $this->namespaceToPath($namespace);
}
$absolutePath = $this->makeAbsolutePath($fileDirectoryPath, $shortClassName);
if (file_exists($absolutePath)) {
return require_once $absolutePath;
}
}
}
private function namespaceToPath($namespace) {
return str_replace($this->namespaceSeparator, DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
private function getShortClassName($className, $lastNsPos) {
return substr($className, $lastNsPos + 1);
}
private function getNamespaceFromClassName($className, $lastNsPos) {
return substr($className, 0, $lastNsPos);
}
private function makeAbsolutePath($fileDirectory, $shortClassName) {
return $this->includePath . DIRECTORY_SEPARATOR . $fileDirectory . $shortClassName . $this->fileExtension;
}
private function getLibraryPath() {
return __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR;
}
} | {'content_hash': 'fc0b443f2405ba5655a37245043d9568', 'timestamp': '', 'source': 'github', 'line_count': 87, 'max_line_length': 162, 'avg_line_length': 28.7816091954023, 'alnum_prop': 0.7136581469648562, 'repo_name': 'arthurpro/vmwarephp', 'id': '605fffb83cd9b1ecb93ef9cc772b4b742395f4e0', 'size': '2504', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'library/Vmwarephp/Autoloader.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'PHP', 'bytes': '51616'}]} |
<?php
/**
* Posts List Table class.
*
* @package WordPress
* @subpackage List_Table
* @since 3.1.0
* @access private
*/
class WP_Posts_List_Table extends WP_List_Table {
/**
* Whether the items should be displayed hierarchically or linearly
*
* @since 3.1.0
* @var bool
* @access protected
*/
var $hierarchical_display;
/**
* Holds the number of pending comments for each post
*
* @since 3.1.0
* @var int
* @access protected
*/
var $comment_pending_count;
/**
* Holds the number of posts for this user
*
* @since 3.1.0
* @var int
* @access private
*/
var $user_posts_count;
/**
* Holds the number of posts which are sticky.
*
* @since 3.1.0
* @var int
* @access private
*/
var $sticky_posts_count = 0;
function __construct( $args = array() ) {
global $post_type_object, $wpdb;
parent::__construct( array(
'plural' => 'posts',
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
) );
$post_type = $this->screen->post_type;
$post_type_object = get_post_type_object( $post_type );
if ( !current_user_can( $post_type_object->cap->edit_others_posts ) ) {
$exclude_states = get_post_stati( array( 'show_in_admin_all_list' => false ) );
$this->user_posts_count = $wpdb->get_var( $wpdb->prepare( "
SELECT COUNT( 1 ) FROM $wpdb->posts
WHERE post_type = %s AND post_status NOT IN ( '" . implode( "','", $exclude_states ) . "' )
AND post_author = %d
", $post_type, get_current_user_id() ) );
if ( $this->user_posts_count && empty( $_REQUEST['post_status'] ) && empty( $_REQUEST['all_posts'] ) && empty( $_REQUEST['author'] ) && empty( $_REQUEST['show_sticky'] ) )
$_GET['author'] = get_current_user_id();
}
if ( 'post' == $post_type && $sticky_posts = get_option( 'sticky_posts' ) ) {
$sticky_posts = implode( ', ', array_map( 'absint', (array) $sticky_posts ) );
$this->sticky_posts_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT( 1 ) FROM $wpdb->posts WHERE post_type = %s AND post_status NOT IN ('trash', 'auto-draft') AND ID IN ($sticky_posts)", $post_type ) );
}
}
function ajax_user_can() {
return current_user_can( get_post_type_object( $this->screen->post_type )->cap->edit_posts );
}
function prepare_items() {
global $avail_post_stati, $wp_query, $per_page, $mode;
$avail_post_stati = wp_edit_posts_query();
$this->hierarchical_display = ( is_post_type_hierarchical( $this->screen->post_type ) && 'menu_order title' == $wp_query->query['orderby'] );
$total_items = $this->hierarchical_display ? $wp_query->post_count : $wp_query->found_posts;
$post_type = $this->screen->post_type;
$per_page = $this->get_items_per_page( 'edit_' . $post_type . '_per_page' );
/** This filter is documented in wp-admin/includes/post.php */
$per_page = apply_filters( 'edit_posts_per_page', $per_page, $post_type );
if ( $this->hierarchical_display )
$total_pages = ceil( $total_items / $per_page );
else
$total_pages = $wp_query->max_num_pages;
$mode = empty( $_REQUEST['mode'] ) ? 'list' : $_REQUEST['mode'];
$this->is_trash = isset( $_REQUEST['post_status'] ) && $_REQUEST['post_status'] == 'trash';
$this->set_pagination_args( array(
'total_items' => $total_items,
'total_pages' => $total_pages,
'per_page' => $per_page
) );
}
function has_items() {
return have_posts();
}
function no_items() {
if ( isset( $_REQUEST['post_status'] ) && 'trash' == $_REQUEST['post_status'] )
echo get_post_type_object( $this->screen->post_type )->labels->not_found_in_trash;
else
echo get_post_type_object( $this->screen->post_type )->labels->not_found;
}
function get_views() {
global $locked_post_status, $avail_post_stati;
$post_type = $this->screen->post_type;
if ( !empty($locked_post_status) )
return array();
$status_links = array();
$num_posts = wp_count_posts( $post_type, 'readable' );
$class = '';
$allposts = '';
$current_user_id = get_current_user_id();
if ( $this->user_posts_count ) {
if ( isset( $_GET['author'] ) && ( $_GET['author'] == $current_user_id ) )
$class = ' class="current"';
$status_links['mine'] = "<a href='edit.php?post_type=$post_type&author=$current_user_id'$class>" . sprintf( _nx( 'Mine <span class="count">(%s)</span>', 'Mine <span class="count">(%s)</span>', $this->user_posts_count, 'posts' ), number_format_i18n( $this->user_posts_count ) ) . '</a>';
$allposts = '&all_posts=1';
}
$total_posts = array_sum( (array) $num_posts );
// Subtract post types that are not included in the admin all list.
foreach ( get_post_stati( array('show_in_admin_all_list' => false) ) as $state )
$total_posts -= $num_posts->$state;
$class = empty( $class ) && empty( $_REQUEST['post_status'] ) && empty( $_REQUEST['show_sticky'] ) ? ' class="current"' : '';
$status_links['all'] = "<a href='edit.php?post_type=$post_type{$allposts}'$class>" . sprintf( _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $total_posts, 'posts' ), number_format_i18n( $total_posts ) ) . '</a>';
foreach ( get_post_stati(array('show_in_admin_status_list' => true), 'objects') as $status ) {
$class = '';
$status_name = $status->name;
if ( !in_array( $status_name, $avail_post_stati ) )
continue;
if ( empty( $num_posts->$status_name ) )
continue;
if ( isset($_REQUEST['post_status']) && $status_name == $_REQUEST['post_status'] )
$class = ' class="current"';
$status_links[$status_name] = "<a href='edit.php?post_status=$status_name&post_type=$post_type'$class>" . sprintf( translate_nooped_plural( $status->label_count, $num_posts->$status_name ), number_format_i18n( $num_posts->$status_name ) ) . '</a>';
}
if ( ! empty( $this->sticky_posts_count ) ) {
$class = ! empty( $_REQUEST['show_sticky'] ) ? ' class="current"' : '';
$sticky_link = array( 'sticky' => "<a href='edit.php?post_type=$post_type&show_sticky=1'$class>" . sprintf( _nx( 'Sticky <span class="count">(%s)</span>', 'Sticky <span class="count">(%s)</span>', $this->sticky_posts_count, 'posts' ), number_format_i18n( $this->sticky_posts_count ) ) . '</a>' );
// Sticky comes after Publish, or if not listed, after All.
$split = 1 + array_search( ( isset( $status_links['publish'] ) ? 'publish' : 'all' ), array_keys( $status_links ) );
$status_links = array_merge( array_slice( $status_links, 0, $split ), $sticky_link, array_slice( $status_links, $split ) );
}
return $status_links;
}
function get_bulk_actions() {
$actions = array();
if ( $this->is_trash )
$actions['untrash'] = __( 'Restore' );
else
$actions['edit'] = __( 'Edit' );
if ( $this->is_trash || !EMPTY_TRASH_DAYS )
$actions['delete'] = __( 'Delete Permanently' );
else
$actions['trash'] = __( 'Move to Trash' );
return $actions;
}
function extra_tablenav( $which ) {
global $cat;
?>
<div class="alignleft actions">
<?php
if ( 'top' == $which && !is_singular() ) {
$this->months_dropdown( $this->screen->post_type );
if ( is_object_in_taxonomy( $this->screen->post_type, 'category' ) ) {
$dropdown_options = array(
'show_option_all' => __( 'View all categories' ),
'hide_empty' => 0,
'hierarchical' => 1,
'show_count' => 0,
'orderby' => 'name',
'selected' => $cat
);
wp_dropdown_categories( $dropdown_options );
}
/**
* Fires before the Filter button on the Posts and Pages list tables.
*
* The Filter button allows sorting by date and/or category on the
* Posts list table, and sorting by date on the Pages list table.
*
* @since 2.1.0
*/
do_action( 'restrict_manage_posts' );
submit_button( __( 'Filter' ), 'button', false, false, array( 'id' => 'post-query-submit' ) );
}
if ( $this->is_trash && current_user_can( get_post_type_object( $this->screen->post_type )->cap->edit_others_posts ) ) {
submit_button( __( 'Empty Trash' ), 'apply', 'delete_all', false );
}
?>
</div>
<?php
}
function current_action() {
if ( isset( $_REQUEST['delete_all'] ) || isset( $_REQUEST['delete_all2'] ) )
return 'delete_all';
return parent::current_action();
}
function pagination( $which ) {
global $mode;
parent::pagination( $which );
if ( 'top' == $which && ! is_post_type_hierarchical( $this->screen->post_type ) )
$this->view_switcher( $mode );
}
function get_table_classes() {
return array( 'widefat', 'fixed', is_post_type_hierarchical( $this->screen->post_type ) ? 'pages' : 'posts' );
}
function get_columns() {
$post_type = $this->screen->post_type;
$posts_columns = array();
$posts_columns['cb'] = '<input type="checkbox" />';
/* translators: manage posts column name */
$posts_columns['title'] = _x( 'Title', 'column name' );
if ( post_type_supports( $post_type, 'author' ) )
$posts_columns['author'] = __( 'Author' );
$taxonomies = array();
$taxonomies = get_object_taxonomies( $post_type, 'objects' );
$taxonomies = wp_filter_object_list( $taxonomies, array( 'show_admin_column' => true ), 'and', 'name' );
/**
* Filter the taxonomy columns in the Posts list table.
*
* The dynamic portion of the hook name, $post_type, refers to the post
* type slug.
*
* @since 3.5.0
*
* @param array $taxonomies Array of taxonomies to show columns for.
* @param string $post_type The post type.
*/
$taxonomies = apply_filters( "manage_taxonomies_for_{$post_type}_columns", $taxonomies, $post_type );
$taxonomies = array_filter( $taxonomies, 'taxonomy_exists' );
foreach ( $taxonomies as $taxonomy ) {
if ( 'category' == $taxonomy )
$column_key = 'categories';
elseif ( 'post_tag' == $taxonomy )
$column_key = 'tags';
else
$column_key = 'taxonomy-' . $taxonomy;
$posts_columns[ $column_key ] = get_taxonomy( $taxonomy )->labels->name;
}
$post_status = !empty( $_REQUEST['post_status'] ) ? $_REQUEST['post_status'] : 'all';
if ( post_type_supports( $post_type, 'comments' ) && !in_array( $post_status, array( 'pending', 'draft', 'future' ) ) )
$posts_columns['comments'] = '<span class="vers"><span title="' . esc_attr__( 'Comments' ) . '" class="comment-grey-bubble"></span></span>';
$posts_columns['date'] = __( 'Date' );
if ( 'page' == $post_type ) {
/**
* Filter the columns displayed in the Pages list table.
*
* @since 2.5.0
*
* @param array $post_columns An array of column names.
*/
$posts_columns = apply_filters( 'manage_pages_columns', $posts_columns );
} else {
/**
* Filter the columns displayed in the Posts list table.
*
* @since 1.5.0
*
* @param array $posts_columns An array of column names.
* @param string $post_type The post type slug.
*/
$posts_columns = apply_filters( 'manage_posts_columns', $posts_columns, $post_type );
}
/**
* Filter the columns displayed in the Posts list table for a specific post type.
*
* The dynamic portion of the hook name, $post_type, refers to the post type slug.
*
* @since 3.0.0
*
* @param array $post_columns An array of column names.
*/
$posts_columns = apply_filters( "manage_{$post_type}_posts_columns", $posts_columns );
return $posts_columns;
}
function get_sortable_columns() {
return array(
'title' => 'title',
'parent' => 'parent',
'comments' => 'comment_count',
'date' => array( 'date', true )
);
}
function display_rows( $posts = array(), $level = 0 ) {
global $wp_query, $per_page;
if ( empty( $posts ) )
$posts = $wp_query->posts;
add_filter( 'the_title', 'esc_html' );
if ( $this->hierarchical_display ) {
$this->_display_rows_hierarchical( $posts, $this->get_pagenum(), $per_page );
} else {
$this->_display_rows( $posts, $level );
}
}
function _display_rows( $posts, $level = 0 ) {
global $mode;
// Create array of post IDs.
$post_ids = array();
foreach ( $posts as $a_post )
$post_ids[] = $a_post->ID;
$this->comment_pending_count = get_pending_comments_num( $post_ids );
foreach ( $posts as $post )
$this->single_row( $post, $level );
}
function _display_rows_hierarchical( $pages, $pagenum = 1, $per_page = 20 ) {
global $wpdb;
$level = 0;
if ( ! $pages ) {
$pages = get_pages( array( 'sort_column' => 'menu_order' ) );
if ( ! $pages )
return false;
}
/*
* Arrange pages into two parts: top level pages and children_pages
* children_pages is two dimensional array, eg.
* children_pages[10][] contains all sub-pages whose parent is 10.
* It only takes O( N ) to arrange this and it takes O( 1 ) for subsequent lookup operations
* If searching, ignore hierarchy and treat everything as top level
*/
if ( empty( $_REQUEST['s'] ) ) {
$top_level_pages = array();
$children_pages = array();
foreach ( $pages as $page ) {
// catch and repair bad pages
if ( $page->post_parent == $page->ID ) {
$page->post_parent = 0;
$wpdb->update( $wpdb->posts, array( 'post_parent' => 0 ), array( 'ID' => $page->ID ) );
clean_post_cache( $page );
}
if ( 0 == $page->post_parent )
$top_level_pages[] = $page;
else
$children_pages[ $page->post_parent ][] = $page;
}
$pages = &$top_level_pages;
}
$count = 0;
$start = ( $pagenum - 1 ) * $per_page;
$end = $start + $per_page;
foreach ( $pages as $page ) {
if ( $count >= $end )
break;
if ( $count >= $start ) {
echo "\t";
$this->single_row( $page, $level );
}
$count++;
if ( isset( $children_pages ) )
$this->_page_rows( $children_pages, $count, $page->ID, $level + 1, $pagenum, $per_page );
}
// if it is the last pagenum and there are orphaned pages, display them with paging as well
if ( isset( $children_pages ) && $count < $end ){
foreach ( $children_pages as $orphans ){
foreach ( $orphans as $op ) {
if ( $count >= $end )
break;
if ( $count >= $start ) {
echo "\t";
$this->single_row( $op, 0 );
}
$count++;
}
}
}
}
/**
* Given a top level page ID, display the nested hierarchy of sub-pages
* together with paging support
*
* @since 3.1.0 (Standalone function exists since 2.6.0)
*
* @param array $children_pages
* @param int $count
* @param int $parent
* @param int $level
* @param int $pagenum
* @param int $per_page
*/
function _page_rows( &$children_pages, &$count, $parent, $level, $pagenum, $per_page ) {
if ( ! isset( $children_pages[$parent] ) )
return;
$start = ( $pagenum - 1 ) * $per_page;
$end = $start + $per_page;
foreach ( $children_pages[$parent] as $page ) {
if ( $count >= $end )
break;
// If the page starts in a subtree, print the parents.
if ( $count == $start && $page->post_parent > 0 ) {
$my_parents = array();
$my_parent = $page->post_parent;
while ( $my_parent ) {
$my_parent = get_post( $my_parent );
$my_parents[] = $my_parent;
if ( !$my_parent->post_parent )
break;
$my_parent = $my_parent->post_parent;
}
$num_parents = count( $my_parents );
while ( $my_parent = array_pop( $my_parents ) ) {
echo "\t";
$this->single_row( $my_parent, $level - $num_parents );
$num_parents--;
}
}
if ( $count >= $start ) {
echo "\t";
$this->single_row( $page, $level );
}
$count++;
$this->_page_rows( $children_pages, $count, $page->ID, $level + 1, $pagenum, $per_page );
}
unset( $children_pages[$parent] ); //required in order to keep track of orphans
}
function single_row( $post, $level = 0 ) {
global $mode;
static $alternate;
$global_post = get_post();
$GLOBALS['post'] = $post;
setup_postdata( $post );
$edit_link = get_edit_post_link( $post->ID );
$title = _draft_or_post_title();
$post_type_object = get_post_type_object( $post->post_type );
$can_edit_post = current_user_can( 'edit_post', $post->ID );
$alternate = 'alternate' == $alternate ? '' : 'alternate';
$classes = $alternate . ' iedit author-' . ( get_current_user_id() == $post->post_author ? 'self' : 'other' );
$lock_holder = wp_check_post_lock( $post->ID );
if ( $lock_holder ) {
$classes .= ' wp-locked';
$lock_holder = get_userdata( $lock_holder );
}
if ( $post->post_parent ) {
$count = count( get_post_ancestors( $post->ID ) );
$classes .= ' level-'. $count;
} else {
$classes .= ' level-0';
}
?>
<tr id="post-<?php echo $post->ID; ?>" class="<?php echo implode( ' ', get_post_class( $classes, $post->ID ) ); ?>">
<?php
list( $columns, $hidden ) = $this->get_column_info();
foreach ( $columns as $column_name => $column_display_name ) {
$class = "class=\"$column_name column-$column_name\"";
$style = '';
if ( in_array( $column_name, $hidden ) )
$style = ' style="display:none;"';
$attributes = "$class$style";
switch ( $column_name ) {
case 'cb':
?>
<th scope="row" class="check-column">
<?php
if ( $can_edit_post ) {
?>
<label class="screen-reader-text" for="cb-select-<?php the_ID(); ?>"><?php printf( __( 'Select %s' ), $title ); ?></label>
<input id="cb-select-<?php the_ID(); ?>" type="checkbox" name="post[]" value="<?php the_ID(); ?>" />
<div class="locked-indicator"></div>
<?php
}
?>
</th>
<?php
break;
case 'title':
$attributes = 'class="post-title page-title column-title"' . $style;
if ( $this->hierarchical_display ) {
if ( 0 == $level && (int) $post->post_parent > 0 ) {
//sent level 0 by accident, by default, or because we don't know the actual level
$find_main_page = (int) $post->post_parent;
while ( $find_main_page > 0 ) {
$parent = get_post( $find_main_page );
if ( is_null( $parent ) )
break;
$level++;
$find_main_page = (int) $parent->post_parent;
if ( !isset( $parent_name ) ) {
/** This filter is documented in wp-includes/post-template.php */
$parent_name = apply_filters( 'the_title', $parent->post_title, $parent->ID );
}
}
}
}
$pad = str_repeat( '— ', $level );
echo "<td $attributes><strong>";
if ( $format = get_post_format( $post->ID ) ) {
$label = get_post_format_string( $format );
echo '<a href="' . esc_url( add_query_arg( array( 'post_format' => $format, 'post_type' => $post->post_type ), 'edit.php' ) ) . '" class="post-state-format post-format-icon post-format-' . $format . '" title="' . $label . '">' . $label . ":</a> ";
}
if ( $can_edit_post && $post->post_status != 'trash' ) {
echo '<a class="row-title" href="' . $edit_link . '" title="' . esc_attr( sprintf( __( 'Edit “%s”' ), $title ) ) . '">' . $pad . $title . '</a>';
} else {
echo $pad . $title;
}
_post_states( $post );
if ( isset( $parent_name ) )
echo ' | ' . $post_type_object->labels->parent_item_colon . ' ' . esc_html( $parent_name );
echo "</strong>\n";
if ( $can_edit_post && $post->post_status != 'trash' ) {
if ( $lock_holder ) {
$locked_avatar = get_avatar( $lock_holder->ID, 18 );
$locked_text = esc_html( sprintf( __( '%s is currently editing' ), $lock_holder->display_name ) );
} else {
$locked_avatar = $locked_text = '';
}
echo '<div class="locked-info"><span class="locked-avatar">' . $locked_avatar . '</span> <span class="locked-text">' . $locked_text . "</span></div>\n";
}
if ( ! $this->hierarchical_display && 'excerpt' == $mode && current_user_can( 'read_post', $post->ID ) )
the_excerpt();
$actions = array();
if ( $can_edit_post && 'trash' != $post->post_status ) {
$actions['edit'] = '<a href="' . get_edit_post_link( $post->ID, true ) . '" title="' . esc_attr( __( 'Edit this item' ) ) . '">' . __( 'Edit' ) . '</a>';
$actions['inline hide-if-no-js'] = '<a href="#" class="editinline" title="' . esc_attr( __( 'Edit this item inline' ) ) . '">' . __( 'Quick Edit' ) . '</a>';
}
if ( current_user_can( 'delete_post', $post->ID ) ) {
if ( 'trash' == $post->post_status )
$actions['untrash'] = "<a title='" . esc_attr( __( 'Restore this item from the Trash' ) ) . "' href='" . wp_nonce_url( admin_url( sprintf( $post_type_object->_edit_link . '&action=untrash', $post->ID ) ), 'untrash-post_' . $post->ID ) . "'>" . __( 'Restore' ) . "</a>";
elseif ( EMPTY_TRASH_DAYS )
$actions['trash'] = "<a class='submitdelete' title='" . esc_attr( __( 'Move this item to the Trash' ) ) . "' href='" . get_delete_post_link( $post->ID ) . "'>" . __( 'Trash' ) . "</a>";
if ( 'trash' == $post->post_status || !EMPTY_TRASH_DAYS )
$actions['delete'] = "<a class='submitdelete' title='" . esc_attr( __( 'Delete this item permanently' ) ) . "' href='" . get_delete_post_link( $post->ID, '', true ) . "'>" . __( 'Delete Permanently' ) . "</a>";
}
if ( $post_type_object->public ) {
if ( in_array( $post->post_status, array( 'pending', 'draft', 'future' ) ) ) {
if ( $can_edit_post ) {
/** This filter is documented in wp-admin/includes/meta-boxes.php */
$actions['view'] = '<a href="' . esc_url( apply_filters( 'preview_post_link', set_url_scheme( add_query_arg( 'preview', 'true', get_permalink( $post->ID ) ) ) ) ) . '" title="' . esc_attr( sprintf( __( 'Preview “%s”' ), $title ) ) . '" rel="permalink">' . __( 'Preview' ) . '</a>';
}
} elseif ( 'trash' != $post->post_status ) {
$actions['view'] = '<a href="' . get_permalink( $post->ID ) . '" title="' . esc_attr( sprintf( __( 'View “%s”' ), $title ) ) . '" rel="permalink">' . __( 'View' ) . '</a>';
}
}
if ( is_post_type_hierarchical( $post->post_type ) ) {
/**
* Filter the array of row action links on the Pages list table.
*
* The filter is evaluated only for hierarchical post types.
*
* @since 2.8.0
*
* @param array $actions An array of row action links. Defaults are
* 'Edit', 'Quick Edit', 'Restore, 'Trash',
* 'Delete Permanently', 'Preview', and 'View'.
* @param WP_Post $post The post object.
*/
$actions = apply_filters( 'page_row_actions', $actions, $post );
} else {
/**
* Filter the array of row action links on the Posts list table.
*
* The filter is evaluated only for non-hierarchical post types.
*
* @since 2.8.0
*
* @param array $actions An array of row action links. Defaults are
* 'Edit', 'Quick Edit', 'Restore, 'Trash',
* 'Delete Permanently', 'Preview', and 'View'.
* @param WP_Post $post The post object.
*/
$actions = apply_filters( 'post_row_actions', $actions, $post );
}
echo $this->row_actions( $actions );
get_inline_data( $post );
echo '</td>';
break;
case 'date':
if ( '0000-00-00 00:00:00' == $post->post_date ) {
$t_time = $h_time = __( 'Unpublished' );
$time_diff = 0;
} else {
$t_time = get_the_time( __( 'Y/m/d g:i:s A' ) );
$m_time = $post->post_date;
$time = get_post_time( 'G', true, $post );
$time_diff = time() - $time;
if ( $time_diff > 0 && $time_diff < DAY_IN_SECONDS )
$h_time = sprintf( __( '%s ago' ), human_time_diff( $time ) );
else
$h_time = mysql2date( __( 'Y/m/d' ), $m_time );
}
echo '<td ' . $attributes . '>';
if ( 'excerpt' == $mode ) {
/**
* Filter the published time of the post.
*
* If $mode equals 'excerpt', the published time and date are both displayed.
* If $mode equals 'list' (default), the publish date is displayed, with the
* time and date together available as an abbreviation definition.
*
* @since 2.5.1
*
* @param array $t_time The published time.
* @param WP_Post $post Post object.
* @param string $column_name The column name.
* @param string $mode The list display mode ('excerpt' or 'list').
*/
echo apply_filters( 'post_date_column_time', $t_time, $post, $column_name, $mode );
} else {
/** This filter is documented in wp-admin/includes/class-wp-posts-list-table.php */
echo '<abbr title="' . $t_time . '">' . apply_filters( 'post_date_column_time', $h_time, $post, $column_name, $mode ) . '</abbr>';
}
echo '<br />';
if ( 'publish' == $post->post_status ) {
_e( 'Published' );
} elseif ( 'future' == $post->post_status ) {
if ( $time_diff > 0 )
echo '<strong class="attention">' . __( 'Missed schedule' ) . '</strong>';
else
_e( 'Scheduled' );
} else {
_e( 'Last Modified' );
}
echo '</td>';
break;
case 'comments':
?>
<td <?php echo $attributes ?>><div class="post-com-count-wrapper">
<?php
$pending_comments = isset( $this->comment_pending_count[$post->ID] ) ? $this->comment_pending_count[$post->ID] : 0;
$this->comments_bubble( $post->ID, $pending_comments );
?>
</div></td>
<?php
break;
case 'author':
?>
<td <?php echo $attributes ?>><?php
printf( '<a href="%s">%s</a>',
esc_url( add_query_arg( array( 'post_type' => $post->post_type, 'author' => get_the_author_meta( 'ID' ) ), 'edit.php' )),
get_the_author()
);
?></td>
<?php
break;
default:
if ( 'categories' == $column_name )
$taxonomy = 'category';
elseif ( 'tags' == $column_name )
$taxonomy = 'post_tag';
elseif ( 0 === strpos( $column_name, 'taxonomy-' ) )
$taxonomy = substr( $column_name, 9 );
else
$taxonomy = false;
if ( $taxonomy ) {
$taxonomy_object = get_taxonomy( $taxonomy );
echo '<td ' . $attributes . '>';
if ( $terms = get_the_terms( $post->ID, $taxonomy ) ) {
$out = array();
foreach ( $terms as $t ) {
$posts_in_term_qv = array();
if ( 'post' != $post->post_type )
$posts_in_term_qv['post_type'] = $post->post_type;
if ( $taxonomy_object->query_var ) {
$posts_in_term_qv[ $taxonomy_object->query_var ] = $t->slug;
} else {
$posts_in_term_qv['taxonomy'] = $taxonomy;
$posts_in_term_qv['term'] = $t->slug;
}
$out[] = sprintf( '<a href="%s">%s</a>',
esc_url( add_query_arg( $posts_in_term_qv, 'edit.php' ) ),
esc_html( sanitize_term_field( 'name', $t->name, $t->term_id, $taxonomy, 'display' ) )
);
}
/* translators: used between list items, there is a space after the comma */
echo join( __( ', ' ), $out );
} else {
echo '—';
}
echo '</td>';
break;
}
?>
<td <?php echo $attributes ?>><?php
if ( is_post_type_hierarchical( $post->post_type ) ) {
/**
* Fires in each custom column on the Posts list table.
*
* This hook only fires if the current post type is hierarchical,
* such as pages.
*
* @since 2.5.0
*
* @param string $column_name The name of the column to display.
* @param int $post_id The current post ID.
*/
do_action( 'manage_pages_custom_column', $column_name, $post->ID );
} else {
/**
* Fires in each custom column in the Posts list table.
*
* This hook only fires if the current post type is non-hierarchical,
* such as posts.
*
* @since 1.5.0
*
* @param string $column_name The name of the column to display.
* @param int $post_id The current post ID.
*/
do_action( 'manage_posts_custom_column', $column_name, $post->ID );
}
/**
* Fires for each custom column of a specific post type in the Posts list table.
*
* The dynamic portion of the hook name, $post->post_type, refers to the post type.
*
* @since 3.1.0
*
* @param string $column_name The name of the column to display.
* @param int $post_id The current post ID.
*/
do_action( "manage_{$post->post_type}_posts_custom_column", $column_name, $post->ID );
?></td>
<?php
break;
}
}
?>
</tr>
<?php
$GLOBALS['post'] = $global_post;
}
/**
* Outputs the hidden row displayed when inline editing
*
* @since 3.1.0
*/
function inline_edit() {
global $mode;
$screen = $this->screen;
$post = get_default_post_to_edit( $screen->post_type );
$post_type_object = get_post_type_object( $screen->post_type );
$taxonomy_names = get_object_taxonomies( $screen->post_type );
$hierarchical_taxonomies = array();
$flat_taxonomies = array();
foreach ( $taxonomy_names as $taxonomy_name ) {
$taxonomy = get_taxonomy( $taxonomy_name );
if ( !$taxonomy->show_ui )
continue;
if ( $taxonomy->hierarchical )
$hierarchical_taxonomies[] = $taxonomy;
else
$flat_taxonomies[] = $taxonomy;
}
$m = ( isset( $mode ) && 'excerpt' == $mode ) ? 'excerpt' : 'list';
$can_publish = current_user_can( $post_type_object->cap->publish_posts );
$core_columns = array( 'cb' => true, 'date' => true, 'title' => true, 'categories' => true, 'tags' => true, 'comments' => true, 'author' => true );
?>
<form method="get" action=""><table style="display: none"><tbody id="inlineedit">
<?php
$hclass = count( $hierarchical_taxonomies ) ? 'post' : 'page';
$bulk = 0;
while ( $bulk < 2 ) { ?>
<tr id="<?php echo $bulk ? 'bulk-edit' : 'inline-edit'; ?>" class="inline-edit-row inline-edit-row-<?php echo "$hclass inline-edit-" . $screen->post_type;
echo $bulk ? " bulk-edit-row bulk-edit-row-$hclass bulk-edit-{$screen->post_type}" : " quick-edit-row quick-edit-row-$hclass inline-edit-{$screen->post_type}";
?>" style="display: none"><td colspan="<?php echo $this->get_column_count(); ?>" class="colspanchange">
<fieldset class="inline-edit-col-left"><div class="inline-edit-col">
<h4><?php echo $bulk ? __( 'Bulk Edit' ) : __( 'Quick Edit' ); ?></h4>
<?php
if ( post_type_supports( $screen->post_type, 'title' ) ) :
if ( $bulk ) : ?>
<div id="bulk-title-div">
<div id="bulk-titles"></div>
</div>
<?php else : // $bulk ?>
<label>
<span class="title"><?php _e( 'Title' ); ?></span>
<span class="input-text-wrap"><input type="text" name="post_title" class="ptitle" value="" /></span>
</label>
<label>
<span class="title"><?php _e( 'Slug' ); ?></span>
<span class="input-text-wrap"><input type="text" name="post_name" value="" /></span>
</label>
<?php endif; // $bulk
endif; // post_type_supports title ?>
<?php if ( !$bulk ) : ?>
<label><span class="title"><?php _e( 'Date' ); ?></span></label>
<div class="inline-edit-date">
<?php touch_time( 1, 1, 0, 1 ); ?>
</div>
<br class="clear" />
<?php endif; // $bulk
if ( post_type_supports( $screen->post_type, 'author' ) ) :
$authors_dropdown = '';
if ( is_super_admin() || current_user_can( $post_type_object->cap->edit_others_posts ) ) :
$users_opt = array(
'hide_if_only_one_author' => false,
'who' => 'authors',
'name' => 'post_author',
'class'=> 'authors',
'multi' => 1,
'echo' => 0
);
if ( $bulk )
$users_opt['show_option_none'] = __( '— No Change —' );
if ( $authors = wp_dropdown_users( $users_opt ) ) :
$authors_dropdown = '<label class="inline-edit-author">';
$authors_dropdown .= '<span class="title">' . __( 'Author' ) . '</span>';
$authors_dropdown .= $authors;
$authors_dropdown .= '</label>';
endif;
endif; // authors
?>
<?php if ( !$bulk ) echo $authors_dropdown;
endif; // post_type_supports author
if ( !$bulk && $can_publish ) :
?>
<div class="inline-edit-group">
<label class="alignleft">
<span class="title"><?php _e( 'Password' ); ?></span>
<span class="input-text-wrap"><input type="text" name="post_password" class="inline-edit-password-input" value="" /></span>
</label>
<em style="margin:5px 10px 0 0" class="alignleft">
<?php
/* translators: Between password field and private checkbox on post quick edit interface */
echo __( '–OR–' );
?>
</em>
<label class="alignleft inline-edit-private">
<input type="checkbox" name="keep_private" value="private" />
<span class="checkbox-title"><?php echo __( 'Private' ); ?></span>
</label>
</div>
<?php endif; ?>
</div></fieldset>
<?php if ( count( $hierarchical_taxonomies ) && !$bulk ) : ?>
<fieldset class="inline-edit-col-center inline-edit-categories"><div class="inline-edit-col">
<?php foreach ( $hierarchical_taxonomies as $taxonomy ) : ?>
<span class="title inline-edit-categories-label"><?php echo esc_html( $taxonomy->labels->name ) ?></span>
<input type="hidden" name="<?php echo ( $taxonomy->name == 'category' ) ? 'post_category[]' : 'tax_input[' . esc_attr( $taxonomy->name ) . '][]'; ?>" value="0" />
<ul class="cat-checklist <?php echo esc_attr( $taxonomy->name )?>-checklist">
<?php wp_terms_checklist( null, array( 'taxonomy' => $taxonomy->name ) ) ?>
</ul>
<?php endforeach; //$hierarchical_taxonomies as $taxonomy ?>
</div></fieldset>
<?php endif; // count( $hierarchical_taxonomies ) && !$bulk ?>
<fieldset class="inline-edit-col-right"><div class="inline-edit-col">
<?php
if ( post_type_supports( $screen->post_type, 'author' ) && $bulk )
echo $authors_dropdown;
if ( post_type_supports( $screen->post_type, 'page-attributes' ) ) :
if ( $post_type_object->hierarchical ) :
?>
<label>
<span class="title"><?php _e( 'Parent' ); ?></span>
<?php
$dropdown_args = array(
'post_type' => $post_type_object->name,
'selected' => $post->post_parent,
'name' => 'post_parent',
'show_option_none' => __( 'Main Page (no parent)' ),
'option_none_value' => 0,
'sort_column' => 'menu_order, post_title',
);
if ( $bulk )
$dropdown_args['show_option_no_change'] = __( '— No Change —' );
/**
* Filter the arguments used to generate the Quick Edit page-parent drop-down.
*
* @since 2.7.0
*
* @see wp_dropdown_pages()
*
* @param array $dropdown_args An array of arguments.
*/
$dropdown_args = apply_filters( 'quick_edit_dropdown_pages_args', $dropdown_args );
wp_dropdown_pages( $dropdown_args );
?>
</label>
<?php
endif; // hierarchical
if ( !$bulk ) : ?>
<label>
<span class="title"><?php _e( 'Order' ); ?></span>
<span class="input-text-wrap"><input type="text" name="menu_order" class="inline-edit-menu-order-input" value="<?php echo $post->menu_order ?>" /></span>
</label>
<?php endif; // !$bulk
if ( 'page' == $screen->post_type ) :
?>
<label>
<span class="title"><?php _e( 'Template' ); ?></span>
<select name="page_template">
<?php if ( $bulk ) : ?>
<option value="-1"><?php _e( '— No Change —' ); ?></option>
<?php endif; // $bulk ?>
<option value="default"><?php _e( 'Default Template' ); ?></option>
<?php page_template_dropdown() ?>
</select>
</label>
<?php
endif; // page post_type
endif; // page-attributes
?>
<?php if ( count( $flat_taxonomies ) && !$bulk ) : ?>
<?php foreach ( $flat_taxonomies as $taxonomy ) : ?>
<?php if ( current_user_can( $taxonomy->cap->assign_terms ) ) : ?>
<label class="inline-edit-tags">
<span class="title"><?php echo esc_html( $taxonomy->labels->name ) ?></span>
<textarea cols="22" rows="1" name="tax_input[<?php echo esc_attr( $taxonomy->name )?>]" class="tax_input_<?php echo esc_attr( $taxonomy->name )?>"></textarea>
</label>
<?php endif; ?>
<?php endforeach; //$flat_taxonomies as $taxonomy ?>
<?php endif; // count( $flat_taxonomies ) && !$bulk ?>
<?php if ( post_type_supports( $screen->post_type, 'comments' ) || post_type_supports( $screen->post_type, 'trackbacks' ) ) :
if ( $bulk ) : ?>
<div class="inline-edit-group">
<?php if ( post_type_supports( $screen->post_type, 'comments' ) ) : ?>
<label class="alignleft">
<span class="title"><?php _e( 'Comments' ); ?></span>
<select name="comment_status">
<option value=""><?php _e( '— No Change —' ); ?></option>
<option value="open"><?php _e( 'Allow' ); ?></option>
<option value="closed"><?php _e( 'Do not allow' ); ?></option>
</select>
</label>
<?php endif; if ( post_type_supports( $screen->post_type, 'trackbacks' ) ) : ?>
<label class="alignright">
<span class="title"><?php _e( 'Pings' ); ?></span>
<select name="ping_status">
<option value=""><?php _e( '— No Change —' ); ?></option>
<option value="open"><?php _e( 'Allow' ); ?></option>
<option value="closed"><?php _e( 'Do not allow' ); ?></option>
</select>
</label>
<?php endif; ?>
</div>
<?php else : // $bulk ?>
<div class="inline-edit-group">
<?php if ( post_type_supports( $screen->post_type, 'comments' ) ) : ?>
<label class="alignleft">
<input type="checkbox" name="comment_status" value="open" />
<span class="checkbox-title"><?php _e( 'Allow Comments' ); ?></span>
</label>
<?php endif; if ( post_type_supports( $screen->post_type, 'trackbacks' ) ) : ?>
<label class="alignleft">
<input type="checkbox" name="ping_status" value="open" />
<span class="checkbox-title"><?php _e( 'Allow Pings' ); ?></span>
</label>
<?php endif; ?>
</div>
<?php endif; // $bulk
endif; // post_type_supports comments or pings ?>
<div class="inline-edit-group">
<label class="inline-edit-status alignleft">
<span class="title"><?php _e( 'Status' ); ?></span>
<select name="_status">
<?php if ( $bulk ) : ?>
<option value="-1"><?php _e( '— No Change —' ); ?></option>
<?php endif; // $bulk ?>
<?php if ( $can_publish ) : // Contributors only get "Unpublished" and "Pending Review" ?>
<option value="publish"><?php _e( 'Published' ); ?></option>
<option value="future"><?php _e( 'Scheduled' ); ?></option>
<?php if ( $bulk ) : ?>
<option value="private"><?php _e( 'Private' ) ?></option>
<?php endif; // $bulk ?>
<?php endif; ?>
<option value="pending"><?php _e( 'Pending Review' ); ?></option>
<option value="draft"><?php _e( 'Draft' ); ?></option>
</select>
</label>
<?php if ( 'post' == $screen->post_type && $can_publish && current_user_can( $post_type_object->cap->edit_others_posts ) ) : ?>
<?php if ( $bulk ) : ?>
<label class="alignright">
<span class="title"><?php _e( 'Sticky' ); ?></span>
<select name="sticky">
<option value="-1"><?php _e( '— No Change —' ); ?></option>
<option value="sticky"><?php _e( 'Sticky' ); ?></option>
<option value="unsticky"><?php _e( 'Not Sticky' ); ?></option>
</select>
</label>
<?php else : // $bulk ?>
<label class="alignleft">
<input type="checkbox" name="sticky" value="sticky" />
<span class="checkbox-title"><?php _e( 'Make this post sticky' ); ?></span>
</label>
<?php endif; // $bulk ?>
<?php endif; // 'post' && $can_publish && current_user_can( 'edit_others_cap' ) ?>
</div>
<?php
if ( $bulk && current_theme_supports( 'post-formats' ) && post_type_supports( $screen->post_type, 'post-formats' ) ) {
$post_formats = get_theme_support( 'post-formats' );
?>
<label class="alignleft" for="post_format">
<span class="title"><?php _ex( 'Format', 'post format' ); ?></span>
<select name="post_format">
<option value="-1"><?php _e( '— No Change —' ); ?></option>
<option value="0"><?php echo get_post_format_string( 'standard' ); ?></option>
<?php
foreach ( $post_formats[0] as $format ) {
?>
<option value="<?php echo esc_attr( $format ); ?>"><?php echo esc_html( get_post_format_string( $format ) ); ?></option>
<?php
}
?>
</select></label>
<?php
}
?>
</div></fieldset>
<?php
list( $columns ) = $this->get_column_info();
foreach ( $columns as $column_name => $column_display_name ) {
if ( isset( $core_columns[$column_name] ) )
continue;
if ( $bulk ) {
/**
* Fires once for each column in Bulk Edit mode.
*
* @since 2.7.0
*
* @param string $column_name Name of the column to edit.
* @param WP_Post $post_type The post type slug.
*/
do_action( 'bulk_edit_custom_box', $column_name, $screen->post_type );
} else {
/**
* Fires once for each column in Quick Edit mode.
*
* @since 2.7.0
*
* @param string $column_name Name of the column to edit.
* @param WP_Post $post_type The post type slug.
*/
do_action( 'quick_edit_custom_box', $column_name, $screen->post_type );
}
}
?>
<p class="submit inline-edit-save">
<a accesskey="c" href="#inline-edit" class="button-secondary cancel alignleft"><?php _e( 'Cancel' ); ?></a>
<?php if ( ! $bulk ) {
wp_nonce_field( 'inlineeditnonce', '_inline_edit', false );
?>
<a accesskey="s" href="#inline-edit" class="button-primary save alignright"><?php _e( 'Update' ); ?></a>
<span class="spinner"></span>
<?php } else {
submit_button( __( 'Update' ), 'button-primary alignright', 'bulk_edit', false, array( 'accesskey' => 's' ) );
} ?>
<input type="hidden" name="post_view" value="<?php echo esc_attr( $m ); ?>" />
<input type="hidden" name="screen" value="<?php echo esc_attr( $screen->id ); ?>" />
<?php if ( ! $bulk && ! post_type_supports( $screen->post_type, 'author' ) ) { ?>
<input type="hidden" name="post_author" value="<?php echo esc_attr( $post->post_author ); ?>" />
<?php } ?>
<span class="error" style="display:none"></span>
<br class="clear" />
</p>
</td></tr>
<?php
$bulk++;
}
?>
</tbody></table></form>
<?php
}
}
| {'content_hash': '7970876487228d0258f6a52469205ea1', 'timestamp': '', 'source': 'github', 'line_count': 1286, 'max_line_length': 303, 'avg_line_length': 32.62597200622084, 'alnum_prop': 0.5677956002574064, 'repo_name': 'alpinelab/batispace', 'id': '1e763f2ff33ef32790b4d5262b43ff5c19be43af', 'size': '41957', 'binary': False, 'copies': '1310', 'ref': 'refs/heads/master', 'path': 'wp-admin/includes/class-wp-posts-list-table.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1459600'}, {'name': 'JavaScript', 'bytes': '1462197'}, {'name': 'PHP', 'bytes': '8237934'}]} |
package org.kaaproject.kaa.server.transport;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Represents a marker annotation for {@link TransportConfig}.
*
* @author Andrew Shvayka
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface KaaTransportConfig {
}
| {'content_hash': 'abc0fa74b88939dde5b5c3e62b68c963', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 62, 'avg_line_length': 22.0, 'alnum_prop': 0.784688995215311, 'repo_name': 'zofuthan/kaa', 'id': 'bc895a334ec65e47aadddb2a80e5938dadba2991', 'size': '1019', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'server/common/transport-shared/src/main/java/org/kaaproject/kaa/server/transport/KaaTransportConfig.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AMPL', 'bytes': '19815'}, {'name': 'Batchfile', 'bytes': '4577'}, {'name': 'C', 'bytes': '1334799'}, {'name': 'C++', 'bytes': '1142799'}, {'name': 'CMake', 'bytes': '65181'}, {'name': 'CSS', 'bytes': '10183'}, {'name': 'HTML', 'bytes': '3112'}, {'name': 'Java', 'bytes': '8175012'}, {'name': 'Makefile', 'bytes': '5316'}, {'name': 'Python', 'bytes': '128276'}, {'name': 'Shell', 'bytes': '130848'}, {'name': 'Thrift', 'bytes': '21163'}, {'name': 'XSLT', 'bytes': '4062'}]} |
baud=$2
if [ -z "$1" ]; then
echo "This script requires an argument: USB device port"
exit 1;
fi
if [ -z "$2" ]; then
echo "Setting baudrate to default: 115200"
baud=115200
#Default nodemcu 1.5+ baudrate
fi
nodemcu-tool upload server.lua --port $1 --compile --optimize --baud $baud
nodemcu-tool upload init.lua --port $1 --optimize --baud $baud
nodemcu-tool upload static/audi.jpg -k --port $1 --baud $baud
nodemcu-tool upload static/bmw.jpg -k --port $1 --baud $baud
nodemcu-tool upload static/cars.html -k --port $1 --baud $baud
nodemcu-tool upload static/chevrolet.jpg -k --port $1 --baud $baud
nodemcu-tool upload static/corvette.jpg -k --port $1 --baud $baud
nodemcu-tool upload static/favicon.ico -k --port $1 --baud $baud
nodemcu-tool upload static/honda.jpg -k --port $1 --baud $baud
nodemcu-tool upload static/mustang.jpg -k --port $1 --baud $baud
nodemcu-tool upload static/peugeot.jpg -k --port $1 --baud $baud
| {'content_hash': 'f40be0820327dca75822a4227c954560', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 74, 'avg_line_length': 42.22727272727273, 'alnum_prop': 0.7072120559741658, 'repo_name': 'loicortola/nodemcu-espress', 'id': '5a6c7d9849cd9c145a1837c9a94010528c92700d', 'size': '938', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'samples/heavy-website/upload.sh', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1717'}, {'name': 'Lua', 'bytes': '16880'}, {'name': 'Shell', 'bytes': '3620'}]} |
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class RepositoryServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind(\App\Repositories\TestEntityRepository::class, \App\Repositories\TestEntityRepositoryEloquent::class);
//:end-bindings:
}
}
| {'content_hash': '830546acc1d681a3b59d1dfaf89f2627', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 127, 'avg_line_length': 19.03448275862069, 'alnum_prop': 0.6195652173913043, 'repo_name': 'jocoonopa/lubri', 'id': '05e4e38b3e49540e08074ed571ee145e615afae6', 'size': '552', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/Providers/RepositoryServiceProvider.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '412'}, {'name': 'CSS', 'bytes': '32689'}, {'name': 'HTML', 'bytes': '327107'}, {'name': 'JavaScript', 'bytes': '672106'}, {'name': 'PHP', 'bytes': '687582'}, {'name': 'PLpgSQL', 'bytes': '1580'}, {'name': 'PowerShell', 'bytes': '860'}, {'name': 'Shell', 'bytes': '35'}]} |
PROG= pipe2
.include "../Makefile.cprog"
| {'content_hash': '68d3b9fdd071691c4573e28882a017e7', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 28, 'avg_line_length': 14.0, 'alnum_prop': 0.6904761904761905, 'repo_name': 'SumiTomohiko/fsyscall2', 'id': '76668bf6d4eac304aae921374f994266354c4504', 'size': '43', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/amd64/pipe2/Makefile', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '20301'}, {'name': 'C', 'bytes': '663318'}, {'name': 'C++', 'bytes': '3059'}, {'name': 'Groovy', 'bytes': '1472'}, {'name': 'Java', 'bytes': '398186'}, {'name': 'Makefile', 'bytes': '23866'}, {'name': 'Python', 'bytes': '1320'}, {'name': 'Shell', 'bytes': '32639'}]} |
@interface BeaconID : NSObject <NSCopying>
@property (nonatomic, readonly) NSUUID *proximityUUID;
@property (nonatomic, readonly) CLBeaconMajorValue major;
@property (nonatomic, readonly) CLBeaconMinorValue minor;
@property (nonatomic, readonly) NSString *asString;
@property (nonatomic, readonly) CLBeaconRegion *asBeaconRegion;
- (instancetype)new NS_UNAVAILABLE;
- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithProximityUUID:(NSUUID *)proximityUUID major:(CLBeaconMajorValue)major minor:(CLBeaconMinorValue)minor NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithUUIDString:(NSString *)UUIDString major:(CLBeaconMajorValue)major minor:(CLBeaconMinorValue)minor;
- (BOOL)isEqualToBeaconID:(BeaconID *)beaconID;
@end
@interface CLBeacon (BeaconID)
@property (nonatomic, readonly) BeaconID *beaconID;
@end
| {'content_hash': 'b8acf3916945afa40fda0c09c488255e', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 152, 'avg_line_length': 34.541666666666664, 'alnum_prop': 0.8069963811821471, 'repo_name': 'lanista-training/lanista-mobility', 'id': '67c1465c07451745a9a63471560020a3f8eb8658', 'size': '985', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'plugin/src/ios/BeaconID.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '22399'}, {'name': 'JavaScript', 'bytes': '56054'}, {'name': 'Objective-C', 'bytes': '825133'}]} |
<?php
namespace Hris\LeaveBundle\EventListener;
use Hris\LeaveBundle\Event\ConfigureMenuEvent;
class ConfigureMenuListener
{
/**
* @param \Hris\LeaveBundle\Event\ConfigureMenuEvent $event
*/
public function onMenuConfigure(ConfigureMenuEvent $event)
{
$menu = $event->getMenu();
$menu->addChild('Leave Module', array(
'uri'=>'#leavemodule',
'extras'=>array('tag'=>'div'),
'name'=>'Leave Module',
'attributes'=> array('class'=>'accordion-group'),
)
);
$leaveModule = $menu->getChild('Leave Module');
$leaveModule->addChild('Leave Settings',
array('route'=>'leave',
'extras'=>array('tag'=>'div'),
'name'=>'Leave Settings',
'attributes'=> array('class'=>'accordion-group'),
)
);
$leaveModule->addChild('Leave Management',
array('route'=>'record_form_list_leaverecords',
'extras'=>array('tag'=>'div'),
'name'=>'Leave Administration',
'attributes'=> array('class'=>'accordion-group'),
)
);
$leaveModule->addChild('Leave Reports',
array('route'=>'leave_report',
'extras'=>array('tag'=>'div'),
'name'=>'Leave Reports',
'attributes'=> array('class'=>'accordion-group'),
)
);
}
} | {'content_hash': 'c52172ce4b8c98d6cdcd63f4e7fa85ca', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 67, 'avg_line_length': 29.313725490196077, 'alnum_prop': 0.49698996655518396, 'repo_name': 'hrisproject/hris', 'id': 'd8192ae1a55abb5883edae9d0faf6f0ff6b384ff', 'size': '2351', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Hris/LeaveBundle/EventListener/ConfigureMenuListener.php', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '2489'}, {'name': 'C++', 'bytes': '40'}, {'name': 'CSS', 'bytes': '779969'}, {'name': 'Groff', 'bytes': '404296'}, {'name': 'HTML', 'bytes': '1282432'}, {'name': 'JavaScript', 'bytes': '2068831'}, {'name': 'PHP', 'bytes': '2814054'}, {'name': 'Ruby', 'bytes': '4928'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<size android:width="1dp" />
<solid android:color="@color/accent" />
</shape> | {'content_hash': 'f8cb0ba1bc58bec2ad5d41e19a4fc9c7', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 66, 'avg_line_length': 38.4, 'alnum_prop': 0.6614583333333334, 'repo_name': 'toggl/mobileapp', 'id': 'e5e75382fdf0a43246ae9cec62d60bae6e9f2c88', 'size': '194', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'Toggl.Droid/Resources/drawable/shape_edit_text_cursor.xml', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C#', 'bytes': '5733490'}, {'name': 'Makefile', 'bytes': '847'}, {'name': 'Objective-C', 'bytes': '41986'}, {'name': 'Shell', 'bytes': '3407'}]} |
/**
* @file MessageAlphaServiceImpl.java
* @brief 1팀에서 사용될 메시지 처리의 서비스
* @author 개발1팀 / 파트5
* @author 김연근 ( [email protected] )
* @date 생성: 2014-03-14
* @date 최종수정: 2014-03-14
*/
package com.juseyo.commons.lib.messages.packages;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import org.apache.commons.collections.ExtendedProperties;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.Assert;
import com.juseyo.commons.lib.messages.MessageService;
public class MessageAlphaServiceImpl implements MessageService, InitializingBean, DisposableBean, ResourceLoaderAware {
private ExtendedProperties extendedProperties = null;
private ResourceLoader resourceLoader = null;
private Set<?> extFileName;
private Map<?, ?> properties;
/**
* boolean 타입의 프로퍼티 값 얻기
*
* @param name
* 프로퍼티키
* @return boolean 타입의 값
*/
public boolean getBoolean(String name) {
return getConfiguration().getBoolean(name);
}
/**
* boolean 타입의 프로퍼티 값 얻기(디폴트값을 입력받음)
*
* @param name
* 프로퍼티키
* @param def
* 디폴트 값
* @return boolean 타입의 값
*/
public boolean getBoolean(String name, boolean def) {
return getConfiguration().getBoolean(name, def);
}
/**
* double 타입의 프로퍼티 값 얻기
*
* @param name
* 프로퍼티키
* @return double 타입의 값
*/
public double getDouble(String name) {
return getConfiguration().getDouble(name);
}
/**
* double 타입의 프로퍼티 값 얻기
*
* @param name
* 프로퍼티키
* @param def
* 디폴트 값
* @return double 타입의 값
*/
public double getDouble(String name, double def) {
return getConfiguration().getDouble(name, def);
}
/**
* float 타입의 프로퍼티 값 얻기
*
* @param name
* 프로퍼티키
* @return Float 타입의 값
*/
public float getFloat(String name) {
return getConfiguration().getFloat(name);
}
/**
* float 타입의 프로퍼티 값 얻기
*
* @param name
* 프로퍼티키
* @param def
* 디폴트 값
* @return float 타입의 값
*/
public float getFloat(String name, float def) {
return getConfiguration().getFloat(name, def);
}
/**
* int 타입의 프로퍼티 값 얻기
*
* @param name
* 프로퍼티키
* @return int 타입의 값
*/
public int getInt(String name) {
return getConfiguration().getInt(name);
}
/**
* int 타입의 프로퍼티 값 얻기
*
* @param name
* 프로퍼티키
* @param def
* 디폴트 값
* @return int 타입의 값
*/
public int getInt(String name, int def) {
return getConfiguration().getInt(name, def);
}
/**
* 프로퍼티 키 목록 읽기
*
* @return Key를 위한 Iterator
*/
public Iterator<?> getKeys() {
return getConfiguration().getKeys();
}
/**
* prefix를 이용한 키 목록 읽기
*
* @param prefix
* prefix
* @return prefix에 매칭되는 키목록
*/
public Iterator<?> getKeys(String prefix) {
// getConfiguration().values();
return getConfiguration().getKeys(prefix);
}
/**
* long 타입의 프로퍼티 값 얻기
*
* @param name
* 프로퍼티키
* @return long 타입의 값
*/
public long getLong(String name) {
return getConfiguration().getLong(name);
}
/**
* long 타입의 프로퍼티 값 얻기
*
* @param name
* 프로퍼티키
* @param def
* 디폴트 값
* @return long 타입의 값
*/
public long getLong(String name, long def) {
return getConfiguration().getLong(name, def);
}
/**
* String 타입의 프로퍼티 값 얻기
*
* @param name
* 프로퍼티키
* @return String 타입의 값
*/
public String getString(String name) {
return getConfiguration().getString(name);
}
/**
* String 타입의 프로퍼티 값 얻기
*
* @param name
* 프로퍼티키
* @param def
* 디폴트 값
* @return String 타입의 값
*/
public String getString(String name, String def) {
return getConfiguration().getString(name, def);
}
/**
* String[] 타입의 프로퍼티 값 얻기
*
* @param name
* 프로퍼티키
* @return String[] 타입의 값
*/
public String[] getStringArray(String name) {
// return getConfiguration().getStringArray(name);
String value = getConfiguration().getString(name);
String[] values = value.split("__");
if(values != null) {
return values;
}
return new String[0];
}
/**
* Vector 타입의 프로퍼티 값 얻기
*
* @param name
* 프로퍼티키
* @return Vector 타입의 값
*/
public Vector<?> getVector(String name) {
return getConfiguration().getVector(name);
}
/**
* Vector 타입의 프로퍼티 값 얻기
*
* @param name
* 프로퍼티키
* @param def
* 디폴트 값
* @return Vector 타입의 값
*/
public Vector<?> getVector(String name, Vector<?> def) {
return getConfiguration().getVector(name, def);
}
/**
* 전체 키/값 쌍 얻기
*
* @return Vector 타입의 값
*/
public Collection<?> getAllKeyValue() {
return getConfiguration().values();
}
/**
* egovProperties 얻기
*
* @return Properties of requested Service.
*/
private ExtendedProperties getConfiguration() {
return extendedProperties;
}
/**
* resource 변경시 refresh
*/
public void refreshPropertyFiles() throws Exception {
String fileName = null;
try {
Iterator<?> it = extFileName.iterator();
while (it != null && it.hasNext()) {
// Get element
Object element = it.next();
String enc = null;
if (element instanceof Map) {
Map<?, ?> ele = (Map<?, ?>) element;
enc = (String) ele.get("encoding");
fileName = (String) ele.get("filename");
} else {
fileName = (String) element;
}
loadPropertyResources(fileName, enc);
}
} catch (Exception e) {
throw e;
}
}
/**
* Bean 초기화 함수로 최초 생성시 필요한 Property 세티처리
*
* @throws Exception
* fail to initialize
*/
@SuppressWarnings("unchecked")
public void afterPropertiesSet() throws Exception {
try {
extendedProperties = new ExtendedProperties();
// 외부파일이 정의되었을때
if (extFileName != null) {
refreshPropertyFiles();
}
// ----------------------------------------------
// "properties" 속성이 없는 경우 처리 (2010-11-01)
// ----------------------------------------------
if (properties == null) {
return;
}
// //--------------------------------------------
Iterator<?> it = properties.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) it.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
if (key == null || key.equals("")) {
throw new Exception("error.properties.check.essential");
}
extendedProperties.put(key, value);
}
} catch (Exception e) {
throw e;
}
}
/**
* extFileName을 지정할 때 Attribute로 정의
*
* @param extFileName
*/
public void setExtFileName(Set<?> extFileName) {
this.extFileName = extFileName;
}
/**
* properties를 지정할 때 Attribute로 정의
*
* @param properties
*/
public void setProperties(Map<?, ?> properties) {
this.properties = properties;
}
/**
* 서비스 종료처리
*/
public void destroy() {
extendedProperties = null;
}
/**
* 리소스 로더 세팅
*/
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
/**
* 파일위치정보를 가지고 resources 정보 추출
*
* @param location
* 파일위치
* @param encoding
* Encoding 정보
* @throws Exception
*/
private void loadPropertyResources(String location, String encoding) throws Exception {
if (resourceLoader instanceof ResourcePatternResolver) {
try {
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
loadPropertyLoop(resources, encoding);
} catch (IOException ex) {
throw new BeanDefinitionStoreException("Could not resolve Properties resource pattern [" + location + "]", ex);
}
} else {
Resource resource = resourceLoader.getResource(location);
loadPropertyRes(resource, encoding);
}
}
/**
* 멀티로 지정된 경우 처리를 위해 LOOP 처리
*
* @param resources
* 리소스정보
* @param encoding
* 인코딩정보
* @throws Exception
*/
private void loadPropertyLoop(Resource[] resources, String encoding) throws Exception {
Assert.notNull(resources, "Resource array must not be null");
for (int i = 0; i < resources.length; i++) {
loadPropertyRes(resources[i], encoding);
}
}
/**
* 파일 정보를 읽어서 properties에 저장
*
* @param resources
* 리소스정보
* @param encoding
* 인코딩정보
* @throws Exception
*/
private void loadPropertyRes(Resource resource, String encoding) throws Exception {
ExtendedProperties property = new ExtendedProperties();
property.load(resource.getInputStream(), encoding);
extendedProperties.combine(property);
}
}
| {'content_hash': '88a89e146b5423a5580772819624a4b6', 'timestamp': '', 'source': 'github', 'line_count': 429, 'max_line_length': 119, 'avg_line_length': 21.974358974358974, 'alnum_prop': 0.5906438951946537, 'repo_name': 'zupper77/juseyo', 'id': 'a87e42d1182cb810ec91057463eedb6d66684ff1', 'size': '10487', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/juseyo/commons/lib/messages/packages/MessageAlphaServiceImpl.java', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '817885'}, {'name': 'Java', 'bytes': '380086'}, {'name': 'JavaScript', 'bytes': '1523717'}, {'name': 'PHP', 'bytes': '2980'}, {'name': 'Shell', 'bytes': '104327'}]} |
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
export default class MdFlightTakeoff extends React.Component<IconBaseProps> { }
| {'content_hash': '37b1af2d0060d0bb54a31e00ef66ffaa', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 79, 'avg_line_length': 53.666666666666664, 'alnum_prop': 0.7763975155279503, 'repo_name': 'zuzusik/DefinitelyTyped', 'id': 'c22f43d504d637284f90bde1d39e67a1ac34835a', 'size': '161', 'binary': False, 'copies': '82', 'ref': 'refs/heads/master', 'path': 'types/react-icons/md/flight-takeoff.d.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '308'}, {'name': 'JavaScript', 'bytes': '6204'}, {'name': 'Protocol Buffer', 'bytes': '678'}, {'name': 'TypeScript', 'bytes': '23936975'}]} |
package org.pentaho.di.trans.steps.execprocess;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
/**
* Execute a process *
*
* @author Samatar
* @since 03-11-2008
*
*/
public class ExecProcess extends BaseStep implements StepInterface {
private static Class<?> PKG = ExecProcessMeta.class; // for i18n purposes, needed by Translator2!!
private ExecProcessMeta meta;
private ExecProcessData data;
public ExecProcess( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta,
Trans trans ) {
super( stepMeta, stepDataInterface, copyNr, transMeta, trans );
}
@Override
public boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException {
meta = (ExecProcessMeta) smi;
data = (ExecProcessData) sdi;
Object[] r = getRow(); // Get row from input rowset & set row busy!
if ( r == null ) { // no more input to be expected...
setOutputDone();
return false;
}
if ( first ) {
first = false;
// get the RowMeta
data.previousRowMeta = getInputRowMeta().clone();
data.NrPrevFields = data.previousRowMeta.size();
data.outputRowMeta = data.previousRowMeta;
meta.getFields( data.outputRowMeta, getStepname(), null, null, this, repository, metaStore );
// Check is process field is provided
if ( Utils.isEmpty( meta.getProcessField() ) ) {
logError( BaseMessages.getString( PKG, "ExecProcess.Error.ProcessFieldMissing" ) );
throw new KettleException( BaseMessages.getString( PKG, "ExecProcess.Error.ProcessFieldMissing" ) );
}
// cache the position of the field
if ( data.indexOfProcess < 0 ) {
data.indexOfProcess = data.previousRowMeta.indexOfValue( meta.getProcessField() );
if ( data.indexOfProcess < 0 ) {
// The field is unreachable !
logError( BaseMessages.getString( PKG, "ExecProcess.Exception.CouldnotFindField" )
+ "[" + meta.getProcessField() + "]" );
throw new KettleException( BaseMessages.getString( PKG, "ExecProcess.Exception.CouldnotFindField", meta
.getProcessField() ) );
}
}
if ( meta.isArgumentsInFields() ) {
if ( data.indexOfArguments == null ) {
data.indexOfArguments = new int[meta.getArgumentFieldNames().length];
for ( int i = 0; i < data.indexOfArguments.length; i++ ) {
String fieldName = meta.getArgumentFieldNames()[i];
data.indexOfArguments[i] = data.previousRowMeta.indexOfValue( fieldName );
if ( data.indexOfArguments[i] < 0 ) {
logError( BaseMessages.getString( PKG, "ExecProcess.Exception.CouldnotFindField" )
+ "[" + fieldName + "]" );
throw new KettleException(
BaseMessages.getString( PKG, "ExecProcess.Exception.CouldnotFindField", fieldName ) );
}
}
}
}
} // End If first
Object[] outputRow = RowDataUtil.allocateRowData( data.outputRowMeta.size() );
for ( int i = 0; i < data.NrPrevFields; i++ ) {
outputRow[i] = r[i];
}
// get process to execute
String processString = data.previousRowMeta.getString( r, data.indexOfProcess );
ProcessResult processResult = new ProcessResult();
try {
if ( Utils.isEmpty( processString ) ) {
throw new KettleException( BaseMessages.getString( PKG, "ExecProcess.ProcessEmpty" ) );
}
// execute and return result
if ( meta.isArgumentsInFields() ) {
List<String> cmdArray = new ArrayList<>();
cmdArray.add( processString );
for ( int i = 0; i < data.indexOfArguments.length; i++ ) {
// Runtime.exec will fail on null array elements
// Convert to an empty string if value is null
String argString = data.previousRowMeta.getString( r, data.indexOfArguments[i] );
cmdArray.add( Const.NVL( argString, "" ) );
}
execProcess( cmdArray.toArray( new String[0] ), processResult );
} else {
execProcess( processString, processResult );
}
if ( meta.isFailWhenNotSuccess() ) {
if ( processResult.getExistStatus() != 0 ) {
String errorString = processResult.getErrorStream();
if ( Utils.isEmpty( errorString ) ) {
errorString = processResult.getOutputStream();
}
throw new KettleException( errorString );
}
}
// Add result field to input stream
int rowIndex = data.NrPrevFields;
outputRow[rowIndex++] = processResult.getOutputStream();
// Add result field to input stream
outputRow[rowIndex++] = processResult.getErrorStream();
// Add result field to input stream
outputRow[rowIndex++] = processResult.getExistStatus();
// add new values to the row.
putRow( data.outputRowMeta, outputRow ); // copy row to output rowset(s);
if ( log.isRowLevel() ) {
logRowlevel( BaseMessages.getString( PKG, "ExecProcess.LineNumber", getLinesRead()
+ " : " + getInputRowMeta().getString( r ) ) );
}
} catch ( KettleException e ) {
boolean sendToErrorRow = false;
String errorMessage = null;
if ( getStepMeta().isDoingErrorHandling() ) {
sendToErrorRow = true;
errorMessage = e.toString();
} else {
logError( BaseMessages.getString( PKG, "ExecProcess.ErrorInStepRunning" ) + e.getMessage() );
setErrors( 1 );
stopAll();
setOutputDone(); // signal end to receiver(s)
return false;
}
if ( sendToErrorRow ) {
// Simply add this row to the error row
putError( getInputRowMeta(), r, 1, errorMessage, meta.getResultFieldName(), "ExecProcess001" );
}
}
return true;
}
private void execProcess( String process, ProcessResult processresult ) throws KettleException {
execProcess( new String[]{ process }, processresult );
}
private void execProcess( String[] process, ProcessResult processresult ) throws KettleException {
Process p = null;
try {
String errorMsg = null;
// execute process
try {
if ( !meta.isArgumentsInFields() ) {
p = data.runtime.exec( process[0] );
} else {
p = data.runtime.exec( process );
}
} catch ( Exception e ) {
errorMsg = e.getMessage();
}
if ( p == null ) {
processresult.setErrorStream( errorMsg );
} else {
// get output stream
processresult.setOutputStream( getOutputString( new BufferedReader( new InputStreamReader( p
.getInputStream() ) ) ) );
// get error message
processresult.setErrorStream( getOutputString( new BufferedReader( new InputStreamReader( p
.getErrorStream() ) ) ) );
// Wait until end
p.waitFor();
// get exit status
processresult.setExistStatus( p.exitValue() );
}
} catch ( IOException ioe ) {
throw new KettleException( "IO exception while running the process " + process + "!", ioe );
} catch ( InterruptedException ie ) {
throw new KettleException( "Interrupted exception while running the process " + process + "!", ie );
} catch ( Exception e ) {
throw new KettleException( e );
} finally {
if ( p != null ) {
p.destroy();
}
}
}
private String getOutputString( BufferedReader b ) throws IOException {
StringBuilder retvalBuff = new StringBuilder();
String line;
String delim = meta.getOutputLineDelimiter();
if ( delim == null ) {
delim = "";
} else {
delim = environmentSubstitute( delim );
}
while ( ( line = b.readLine() ) != null ) {
if ( retvalBuff.length() > 0 ) {
retvalBuff.append( delim );
}
retvalBuff.append( line );
}
return retvalBuff.toString();
}
@Override
public boolean init( StepMetaInterface smi, StepDataInterface sdi ) {
meta = (ExecProcessMeta) smi;
data = (ExecProcessData) sdi;
if ( super.init( smi, sdi ) ) {
if ( Utils.isEmpty( meta.getResultFieldName() ) ) {
logError( BaseMessages.getString( PKG, "ExecProcess.Error.ResultFieldMissing" ) );
return false;
}
data.runtime = Runtime.getRuntime();
return true;
}
return false;
}
@Override
public void dispose( StepMetaInterface smi, StepDataInterface sdi ) {
meta = (ExecProcessMeta) smi;
data = (ExecProcessData) sdi;
super.dispose( smi, sdi );
}
}
| {'content_hash': '7ebe1f22201e71624ef1de82d74f14b4', 'timestamp': '', 'source': 'github', 'line_count': 271, 'max_line_length': 113, 'avg_line_length': 34.0, 'alnum_prop': 0.63425222487519, 'repo_name': 'hudak/pentaho-kettle', 'id': '64f93a93714d4ba0f6e08d53eb3b33c97c1eaa45', 'size': '10118', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'engine/src/org/pentaho/di/trans/steps/execprocess/ExecProcess.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '14382'}, {'name': 'CSS', 'bytes': '30418'}, {'name': 'GAP', 'bytes': '4005'}, {'name': 'HTML', 'bytes': '55153'}, {'name': 'Java', 'bytes': '40046715'}, {'name': 'JavaScript', 'bytes': '49292'}, {'name': 'Shell', 'bytes': '19927'}, {'name': 'XSLT', 'bytes': '5600'}]} |
package pro.chukai.web.exception;
import org.springframework.http.HttpStatus;
import java.util.HashMap;
import java.util.Map;
/**
* Created by chukai on 2017/3/29.
*/
public class HttpStatusException extends RuntimeException {
private static final long serialVersionUID = -5604578012991146390L;
private HttpStatus status;
private Map<Object, Object> body;
protected HttpStatusException(HttpStatus status) {
this.status = status;
}
protected HttpStatusException(HttpStatus status, String message) {
super(message);
this.status = status;
}
public static HttpStatusException of(HttpStatus status) {
return new HttpStatusException(status);
}
public static HttpStatusException of(HttpStatus status, String message) {
return new HttpStatusException(status, message);
}
public HttpStatus getStatus() {
return status;
}
public void setStatus(HttpStatus status) {
this.status = status;
}
public Map<Object, Object> getBody() {
return body;
}
public void setBody(Map<Object, Object> body) {
this.body = body;
}
public HttpStatusException addAttribute(Object key, Object value) {
this.body = this.body == null ? new HashMap<>() : body;
this.body.put(key, value);
return this;
}
}
| {'content_hash': '7dbe08ad830a39e450e2428e60b2aeb6', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 77, 'avg_line_length': 23.56896551724138, 'alnum_prop': 0.667885881492319, 'repo_name': 'wchukai/wchukai.com', 'id': '01236caf9b8a0c5b4e0b11f980c7b4ae81d01cc2', 'size': '1367', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'service/webapp/src/main/java/pro/chukai/web/exception/HttpStatusException.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '82803'}, {'name': 'HTML', 'bytes': '4530'}, {'name': 'Java', 'bytes': '221948'}, {'name': 'JavaScript', 'bytes': '5126'}, {'name': 'Vue', 'bytes': '45264'}]} |
"""
Copyright 2015 SmartBear Software
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.
Ref: https://github.com/swagger-api/swagger-codegen
"""
from datetime import datetime
from pprint import pformat
from six import iteritems
class RepositoryConfiguration(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
RepositoryConfiguration - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'id': 'int',
'internal_url': 'str',
'internal_url_normalized': 'str',
'external_url': 'str',
'external_url_normalized': 'str',
'pre_build_sync_enabled': 'bool',
'build_configurations': 'list[BuildConfiguration]',
'field_handler': 'FieldHandler'
}
self.attribute_map = {
'id': 'id',
'internal_url': 'internalUrl',
'internal_url_normalized': 'internalUrlNormalized',
'external_url': 'externalUrl',
'external_url_normalized': 'externalUrlNormalized',
'pre_build_sync_enabled': 'preBuildSyncEnabled',
'build_configurations': 'buildConfigurations',
'field_handler': 'fieldHandler'
}
self._id = None
self._internal_url = None
self._internal_url_normalized = None
self._external_url = None
self._external_url_normalized = None
self._pre_build_sync_enabled = None
self._build_configurations = None
self._field_handler = None
@property
def id(self):
"""
Gets the id of this RepositoryConfiguration.
:return: The id of this RepositoryConfiguration.
:rtype: int
"""
return self._id
@id.setter
def id(self, id):
"""
Sets the id of this RepositoryConfiguration.
:param id: The id of this RepositoryConfiguration.
:type: int
"""
self._id = id
@property
def internal_url(self):
"""
Gets the internal_url of this RepositoryConfiguration.
:return: The internal_url of this RepositoryConfiguration.
:rtype: str
"""
return self._internal_url
@internal_url.setter
def internal_url(self, internal_url):
"""
Sets the internal_url of this RepositoryConfiguration.
:param internal_url: The internal_url of this RepositoryConfiguration.
:type: str
"""
self._internal_url = internal_url
@property
def internal_url_normalized(self):
"""
Gets the internal_url_normalized of this RepositoryConfiguration.
:return: The internal_url_normalized of this RepositoryConfiguration.
:rtype: str
"""
return self._internal_url_normalized
@internal_url_normalized.setter
def internal_url_normalized(self, internal_url_normalized):
"""
Sets the internal_url_normalized of this RepositoryConfiguration.
:param internal_url_normalized: The internal_url_normalized of this RepositoryConfiguration.
:type: str
"""
self._internal_url_normalized = internal_url_normalized
@property
def external_url(self):
"""
Gets the external_url of this RepositoryConfiguration.
:return: The external_url of this RepositoryConfiguration.
:rtype: str
"""
return self._external_url
@external_url.setter
def external_url(self, external_url):
"""
Sets the external_url of this RepositoryConfiguration.
:param external_url: The external_url of this RepositoryConfiguration.
:type: str
"""
self._external_url = external_url
@property
def external_url_normalized(self):
"""
Gets the external_url_normalized of this RepositoryConfiguration.
:return: The external_url_normalized of this RepositoryConfiguration.
:rtype: str
"""
return self._external_url_normalized
@external_url_normalized.setter
def external_url_normalized(self, external_url_normalized):
"""
Sets the external_url_normalized of this RepositoryConfiguration.
:param external_url_normalized: The external_url_normalized of this RepositoryConfiguration.
:type: str
"""
self._external_url_normalized = external_url_normalized
@property
def pre_build_sync_enabled(self):
"""
Gets the pre_build_sync_enabled of this RepositoryConfiguration.
:return: The pre_build_sync_enabled of this RepositoryConfiguration.
:rtype: bool
"""
return self._pre_build_sync_enabled
@pre_build_sync_enabled.setter
def pre_build_sync_enabled(self, pre_build_sync_enabled):
"""
Sets the pre_build_sync_enabled of this RepositoryConfiguration.
:param pre_build_sync_enabled: The pre_build_sync_enabled of this RepositoryConfiguration.
:type: bool
"""
self._pre_build_sync_enabled = pre_build_sync_enabled
@property
def build_configurations(self):
"""
Gets the build_configurations of this RepositoryConfiguration.
:return: The build_configurations of this RepositoryConfiguration.
:rtype: list[BuildConfiguration]
"""
return self._build_configurations
@build_configurations.setter
def build_configurations(self, build_configurations):
"""
Sets the build_configurations of this RepositoryConfiguration.
:param build_configurations: The build_configurations of this RepositoryConfiguration.
:type: list[BuildConfiguration]
"""
self._build_configurations = build_configurations
@property
def field_handler(self):
"""
Gets the field_handler of this RepositoryConfiguration.
:return: The field_handler of this RepositoryConfiguration.
:rtype: FieldHandler
"""
return self._field_handler
@field_handler.setter
def field_handler(self, field_handler):
"""
Sets the field_handler of this RepositoryConfiguration.
:param field_handler: The field_handler of this RepositoryConfiguration.
:type: FieldHandler
"""
self._field_handler = field_handler
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, datetime):
result[attr] = str(value.date())
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
| {'content_hash': '0a48ffbebfb23114fabe629f75267ace', 'timestamp': '', 'source': 'github', 'line_count': 277, 'max_line_length': 100, 'avg_line_length': 29.447653429602887, 'alnum_prop': 0.6122348902782886, 'repo_name': 'thauser/pnc-cli', 'id': 'efc2aff5f4062d433ffeb45f8c695cfce361c6a3', 'size': '8174', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'pnc_cli/swagger_client/models/repository_configuration.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '44313'}, {'name': 'Python', 'bytes': '1688077'}, {'name': 'Shell', 'bytes': '720'}]} |
FROM balenalib/blackboard-tx2-fedora:33-build
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
RUN dnf install -y \
python-pip \
python-dbus \
&& dnf clean all
# install "virtualenv", since the vast majority of users of this image will want it
RUN pip install -U --no-cache-dir --ignore-installed pip setuptools \
&& pip install --no-cache-dir virtualenv
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'As of January 1st, 2020, Python 2 was end-of-life, we will change the latest tag for Balenalib Python base image to Python 3.x and drop support for Python 2 soon. So after 1st July, 2020, all the balenalib Python latest tag will point to the latest Python 3 version and no changes, or fixes will be made to balenalib Python 2 base image. If you are using Python 2 for your application, please upgrade to Python 3 before 1st July.' > /.balena/messages/python-deprecation-warning
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 curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@python" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
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: Fedora 33 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v2.7.18, Pip v21.0.1, Setuptools v56.0.0 \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': 'dd1dfd6b8069691e886ac4c03f72d000', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 708, 'avg_line_length': 77.96774193548387, 'alnum_prop': 0.7335539925527513, 'repo_name': 'nghiant2710/base-images', 'id': 'cc65359406b2f32692ba4f41fe3cdb2ec4a67bc2', 'size': '2438', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'balena-base-images/python/blackboard-tx2/fedora/33/2.7.18/build/Dockerfile', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '144558581'}, {'name': 'JavaScript', 'bytes': '16316'}, {'name': 'Shell', 'bytes': '368690'}]} |
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE xliff PUBLIC "-//XLIFF//DTD XLIFF//EN" "http://www.oasis-open.org/committees/xliff/documents/xliff.dtd" >
<xliff version="1.0">
<file original="global" source-language="en" target-language="pl" datatype="plaintext">
<header />
<body>
<trans-unit id="1">
<source>Author name</source>
<target>Autor</target>
</trans-unit>
<trans-unit id="2">
<source>Body</source>
<target>Treść</target>
</trans-unit>
<trans-unit id="3">
<source>Edition</source>
<target>Edycja</target>
</trans-unit>
<trans-unit id="4">
<source>Email</source>
<target>Adres email</target>
</trans-unit>
<trans-unit id="4">
<source>Message</source>
<target>Wiadomość</target>
</trans-unit>
<trans-unit id="5">
<source>Posted the</source>
<target>Utworzono</target>
</trans-unit>
<trans-unit id="6">
<source>Deleted</source>
<target>Usunięto</target>
</trans-unit>
<trans-unit id="7">
<source>yes or no</source>
<target>tak lub nie</target>
</trans-unit>
<trans-unit id="8">
<source>yes</source>
<target>tak</target>
</trans-unit>
<trans-unit id="9">
<source>no</source>
<target>nie</target>
</trans-unit>
<trans-unit id="10">
<source>Author email</source>
<target>Email autora</target>
</trans-unit>
<trans-unit id="11">
<source>Author website</source>
<target>Strona autora</target>
</trans-unit>
<trans-unit id="12">
<source>is empty</source>
<target>puste</target>
</trans-unit>
<trans-unit id="13">
<source>State</source>
<target>Status</target>
</trans-unit>
<trans-unit id="14">
<source>Reason</source>
<target>Powód</target>
</trans-unit>
<trans-unit id="15">
<source>Send the</source>
<target>Zgłoszony</target>
</trans-unit>
<trans-unit id="16">
<source>Edit the comment</source>
<target>Edytuj komentarz</target>
</trans-unit>
<trans-unit id="17">
<source>Remove the comment</source>
<target>Usuń komentarz</target>
</trans-unit>
<trans-unit id="18">
<source>Validate</source>
<target>Zatwierdź</target>
</trans-unit>
<trans-unit id="19">
<source>Invalidate</source>
<target>Unieważnij</target>
</trans-unit>
<trans-unit id="20">
<source>Comment's Reports list</source>
<target>Lista zgłoszeń komentarzy</target>
</trans-unit>
<trans-unit id="21">
<source>Comments list</source>
<target>Lista komentarzy</target>
</trans-unit>
<trans-unit id="22">
<source>from %from_date%<br />to %to_date%</source>
<target>od %from_date%<br />do %to_date% </target>
</trans-unit>
</body>
</file>
</xliff>
| {'content_hash': 'a050a2f91eabac6caa1ec81b78b5794b', 'timestamp': '', 'source': 'github', 'line_count': 101, 'max_line_length': 115, 'avg_line_length': 30.554455445544555, 'alnum_prop': 0.550550874918989, 'repo_name': 'iampersistent/vjCommentPlugin', 'id': 'd4b9f3ca46f8799459385a8197d1394665bd4f02', 'size': '3098', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'i18n/pl/messages.xml', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '1305'}, {'name': 'PHP', 'bytes': '54095'}]} |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/recommender/v1beta1/recommendation.proto
package com.google.cloud.recommender.v1beta1;
public interface OperationGroupOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.recommender.v1beta1.OperationGroup)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* List of operations across one or more resources that belong to this group.
* Loosely based on RFC6902 and should be performed in the order they appear.
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.Operation operations = 1;</code>
*/
java.util.List<com.google.cloud.recommender.v1beta1.Operation> getOperationsList();
/**
*
*
* <pre>
* List of operations across one or more resources that belong to this group.
* Loosely based on RFC6902 and should be performed in the order they appear.
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.Operation operations = 1;</code>
*/
com.google.cloud.recommender.v1beta1.Operation getOperations(int index);
/**
*
*
* <pre>
* List of operations across one or more resources that belong to this group.
* Loosely based on RFC6902 and should be performed in the order they appear.
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.Operation operations = 1;</code>
*/
int getOperationsCount();
/**
*
*
* <pre>
* List of operations across one or more resources that belong to this group.
* Loosely based on RFC6902 and should be performed in the order they appear.
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.Operation operations = 1;</code>
*/
java.util.List<? extends com.google.cloud.recommender.v1beta1.OperationOrBuilder>
getOperationsOrBuilderList();
/**
*
*
* <pre>
* List of operations across one or more resources that belong to this group.
* Loosely based on RFC6902 and should be performed in the order they appear.
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.Operation operations = 1;</code>
*/
com.google.cloud.recommender.v1beta1.OperationOrBuilder getOperationsOrBuilder(int index);
}
| {'content_hash': '6037b3a838dd5ca6f49c9f6d92fd0885', 'timestamp': '', 'source': 'github', 'line_count': 68, 'max_line_length': 98, 'avg_line_length': 33.220588235294116, 'alnum_prop': 0.7029659141212926, 'repo_name': 'googleapis/java-recommender', 'id': 'febed843be67bad710ee37cf0c11cb7872dda8e9', 'size': '2853', 'binary': False, 'copies': '2', 'ref': 'refs/heads/main', 'path': 'proto-google-cloud-recommender-v1beta1/src/main/java/com/google/cloud/recommender/v1beta1/OperationGroupOrBuilder.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '801'}, {'name': 'Java', 'bytes': '4241598'}, {'name': 'Python', 'bytes': '788'}, {'name': 'Shell', 'bytes': '22891'}]} |
var scene, camera, renderer, controls;
var detector = {'Collections':{}};
var objloader = new THREE.OBJLoader();
var mtlloader = new THREE.MTLLoader();
var jsonloader = new THREE.JSONLoader();
var event_style = {
'EBRecHits_V2': {
color: 'rgb(10%, 100%, 10%)', opacity: 0.5
},
'EERecHits_V2': {
color: 'rgb(10%, 100%, 10%)', opacity: 0.5
},
'HBRecHits_V2': {
color: 'rgb(20%, 70%, 100%)', opacity: 0.5
},
'HERecHits_V2': {
color: 'rgb(20%, 70%, 100%)', opacity: 0.5
},
'Tracks_V3': {
color: 'rgb(100%, 100%, 0%)', opacity: 0.9
}
};
function importOBJ(name, obj, type) {
objloader.load(obj, function(object){
object.name = name;
object.visible = false;
var style = event_style[name];
var material;
if ( type === 'box' ) {
material = new THREE.MeshBasicMaterial({color:style.color});
material.transparent = true;
material.opacity = 0.5;
material.side = THREE.DoubleSide;
}
if ( type === 'line' ) {
material = new THREE.LineBasicMaterial({color:style.color});
}
object.children.forEach(function(c) {
c.material = material;
});
scene.add(object);
});
}
function importOBJMTL(obj, name) {
objloader.load(obj, function(object) {
object.name = name;
object.visible = true;
object.children.forEach(function(c) {
c.material.transparent = true;
c.material.shininess = 30;
c.material.side = THREE.DoubleSide;
if ( name === 'EB' ) {
c.material.color = new THREE.Color(0.0,0.0,0.0);
c.material.emissive = new THREE.Color(0.5,0.8,1.0);
c.material.specular = new THREE.Color(0.3,0.3,0.3);
c.material.opacity = 0.5;
} else if ( name === 'BeamPipe') {
c.material.color = new THREE.Color(0.0,0.0,0.0);
c.material.emissive = new THREE.Color(0.3,0.3,0.3);
c.material.specular = new THREE.Color(0.3,0.3,0.3);
c.material.opacity = 0.75;
}
})
scene.add(object);
});
}
function showEvent() {
scene.getObjectByName('BeamPipe').visible = false;
scene.getObjectByName('EB').visible = false;
scene.getObjectByName('EBRecHits_V2').visible = true;
scene.getObjectByName('EERecHits_V2').visible = true;
scene.getObjectByName('HBRecHits_V2').visible = true;
scene.getObjectByName('HERecHits_V2').visible = true;
scene.getObjectByName('Tracks_V3').visible = true;
}
function hideEvent() {
scene.getObjectByName('BeamPipe').visible = true;
scene.getObjectByName('EB').visible = true;
scene.getObjectByName('EBRecHits_V2').visible = false;
scene.getObjectByName('EERecHits_V2').visible = false;
scene.getObjectByName('HBRecHits_V2').visible = false;
scene.getObjectByName('HERecHits_V2').visible = false;
scene.getObjectByName('Tracks_V3').visible = false;
}
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(90, window.innerWidth / window.innerHeight, 0.001, 700);
camera.position.set(10, 0, 20);
//camera.position.set(3, 0, 1);
camera.up = new THREE.Vector3(0,1,0);
camera.lookAt(new THREE.Vector3(0,0,0));
scene.add(camera);
renderer = new THREE.WebGLRenderer({antialias:true, alpha:true});
renderer.setPixelRatio(window.devicePixelRatio ? window.devicePixelRatio : 1);
renderer.setClearColor(0x000000,1);
element = renderer.domElement;
container = document.getElementById('cms');
container.appendChild(element);
effect = new THREE.StereoEffect(renderer);
importOBJ('EBRecHits_V2', './data/EBRecHits_V2.obj', 'box');
importOBJ('EERecHits_V2', './data/EERecHits_V2.obj', 'box');
importOBJ('HBRecHits_V2', './data/HBRecHits_V2.obj', 'box');
importOBJ('HERecHits_V2', './data/HERecHits_V2.obj', 'box');
importOBJ('Tracks_V3', './data/Tracks_V3.obj', 'line');
importOBJMTL('./geometry/beampipe.obj', 'BeamPipe');
importOBJMTL('./geometry/EB.obj', 'EB');
controls = new THREE.OrbitControls(camera, element);
controls.enablePan = false;
controls.enableZoom = false;
var intensity = 1.0;
var length = 15.0;
var light1 = new THREE.DirectionalLight(0xcccccc, intensity);
light1.position.set(-length, length, length);
scene.add(light1);
var light2 = new THREE.DirectionalLight(0xcccccc, intensity);
light2.position.set(length, -length, -length);
scene.add(light2);
var bgeometry = new THREE.SphereGeometry(0.1,32,32);
var bmaterial = new THREE.MeshBasicMaterial({color: 0xffff00});
var bunch1 = new THREE.Mesh(bgeometry, bmaterial);
bunch1.position.x = 0;
bunch1.position.y = 0;
bunch1.position.z = 200;
bunch1.name = 'bunch1';
bunch1.visible = true;
var bunch2 = new THREE.Mesh(bgeometry, bmaterial);
bunch2.position.x = 0;
bunch2.position.y = 0;
bunch2.position.z = -200;
bunch2.name = 'bunch2';
bunch2.visible = true;
scene.add(bunch1);
scene.add(bunch2);
var cgeometry = new THREE.SphereGeometry(0.01, 32, 32);
var cmaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0.75,
color: 0xffff00
});
cmaterial.depthWrite = false;
var collision = new THREE.Mesh(cgeometry, cmaterial);
collision.position.set(0,0,0);
collision.name = 'Collision';
collision.visible = true;
scene.add(collision);
var scale = 500;
var ctime = 250;
var c1 = new TWEEN.Tween(collision.scale)
.to({x: scale, y: scale, z: scale}, ctime)
.onStart(function(){
})
.onComplete(function(){
collision.scale.set(1/scale, 1/scale, 1/scale);
});
var t1 = new TWEEN.Tween(bunch1.position)
.to({z:0.0}, 2500)
.onComplete(function(){
c1.start();
showEvent();
})
.easing(TWEEN.Easing.Back.In);
var t2 = new TWEEN.Tween(bunch2.position)
.to({z:0.0}, 2500)
.onComplete(function(){
})
.easing(TWEEN.Easing.Back.In);
var t3 = new TWEEN.Tween(bunch1.position)
.to({z:-200}, 2500)
.onStart(function(){
})
.onComplete(function(){
bunch1.position.z = 200;
hideEvent();
}).easing(TWEEN.Easing.Back.Out);
var t4 = new TWEEN.Tween(bunch2.position)
.to({z:200}, 2500)
.onComplete(function(){
bunch2.position.z = -200;
}).easing(TWEEN.Easing.Back.Out);
t1.chain(t3);
t3.chain(t1);
t2.chain(t4);
t4.chain(t2);
t1.start();
t2.start();
}
function run() {
requestAnimationFrame(run);
var width = container.offsetWidth;
var height = container.offsetHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
effect.setSize(width, height);
camera.updateProjectionMatrix();
controls.update();
effect.render(scene, camera);
TWEEN.update();
}
//--
// This is right from https://github.com/sitepoint-editors/VRWeatherParticles
function setOrientationControls(e) {
if ( !e.alpha ) {
return;
}
controls = new THREE.DeviceOrientationControls(camera, true);
controls.connect();
controls.update();
element.addEventListener('click', fullscreen, false);
window.removeEventListener('deviceorientation', setOrientationControls, true);
}
window.addEventListener('deviceorientation', setOrientationControls, true);
function fullscreen() {
if (container.requestFullscreen) {
container.requestFullscreen();
} else if (container.msRequestFullscreen) {
container.msRequestFullscreen();
} else if (container.mozRequestFullScreen) {
container.mozRequestFullScreen();
} else if (container.webkitRequestFullscreen) {
container.webkitRequestFullscreen();
}
}
//--
var tracker_style = {
color: "rgb(30%, 30%, 30%)",
emissive: "rgb(75%, 75%, 0%)",
specular: "rgb(30%, 30%, 30%)",
opacity: 0.5,
linewidth: 1
};
var detector_description = {
/*
"SiStripTECMinus3D_V1": {
name: "Tracker", methodA: solidFace, methodB: wireframeFace, style: tracker_style
},
"SiStripTECPlus3D_V1": {
name: "Tracker", methodA: solidFace, methodB: wireframeFace, style: tracker_style
},
"SiStripTOB3D_V1": {
name: "Tracker", methodA: solidFace, methodB: wireframeFace, style: tracker_style
},
*/
"CSC3D_V1": {
name: "CSC", methodA: solidBox, methodB: wireframeBox,
style: {color: "rgb(30%, 30%, 30%)", emissive: "rgb(50%, 50%, 50%)", specular: "rgb(30%, 30%, 30%)", opacity: 0.5, linewidth: 1}
},
"DTs3D_V1": {
name: "DT", methodA: solidBox, methodB: wireframeBox,
style: {color: "rgb(30%, 30%, 30%)", emissive: "rgb(75%, 0%, 0%)", specular: "rgb(30%, 30%, 30%)", opacity: 0.5, linewidth: 1}
}
};
function wireframeFace(data, ci) {
var f1 = new THREE.Vector3(data[ci][0], data[ci][1], data[ci][2]);
var f2 = new THREE.Vector3(data[ci+1][0], data[ci+1][1], data[ci+1][2]);
var f3 = new THREE.Vector3(data[ci+2][0], data[ci+2][1], data[ci+2][2]);
var f4 = new THREE.Vector3(data[ci+3][0], data[ci+3][1], data[ci+3][2]);
var face = new THREE.Geometry();
face.vertices.push(f1,f2);
face.vertices.push(f2,f3);
face.vertices.push(f3,f4);
face.vertices.push(f4,f1);
return face;
};
function solidFace(data, ci) {
var f1 = new THREE.Vector3(data[ci][0], data[ci][1], data[ci][2]);
var f2 = new THREE.Vector3(data[ci+1][0], data[ci+1][1], data[ci+1][2]);
var f3 = new THREE.Vector3(data[ci+2][0], data[ci+2][1], data[ci+2][2]);
var f4 = new THREE.Vector3(data[ci+3][0], data[ci+3][1], data[ci+3][2]);
var face = new THREE.Geometry();
face.vertices = [f1,f2,f3,f4];
face.faces.push(new THREE.Face3(0,1,2));
face.faces.push(new THREE.Face3(0,2,3));
return face;
};
function wireframeBox(data, ci) {
var f1 = new THREE.Vector3(data[ci][0], data[ci][1], data[ci][2]);
var f2 = new THREE.Vector3(data[ci+1][0], data[ci+1][1], data[ci+1][2]);
var f3 = new THREE.Vector3(data[ci+2][0], data[ci+2][1], data[ci+2][2]);
var f4 = new THREE.Vector3(data[ci+3][0], data[ci+3][1], data[ci+3][2]);
var b1 = new THREE.Vector3(data[ci+4][0], data[ci+4][1], data[ci+4][2]);
var b2 = new THREE.Vector3(data[ci+5][0], data[ci+5][1], data[ci+5][2]);
var b3 = new THREE.Vector3(data[ci+6][0], data[ci+6][1], data[ci+6][2]);
var b4 = new THREE.Vector3(data[ci+7][0], data[ci+7][1], data[ci+7][2]);
var box = new THREE.Geometry();
box.vertices.push(f1,f2);
box.vertices.push(f2,f3);
box.vertices.push(f3,f4);
box.vertices.push(f4,f1);
box.vertices.push(b1,b2);
box.vertices.push(b2,b3);
box.vertices.push(b3,b4);
box.vertices.push(b4,b1);
box.vertices.push(b1,f1);
box.vertices.push(b3,f3);
box.vertices.push(b2,f2);
box.vertices.push(b4,f4);
return box;
}
function solidBox(data, ci) {
var f1 = new THREE.Vector3(data[ci][0], data[ci][1], data[ci][2]);
var f2 = new THREE.Vector3(data[ci+1][0], data[ci+1][1], data[ci+1][2]);
var f3 = new THREE.Vector3(data[ci+2][0], data[ci+2][1], data[ci+2][2]);
var f4 = new THREE.Vector3(data[ci+3][0], data[ci+3][1], data[ci+3][2]);
var b1 = new THREE.Vector3(data[ci+4][0], data[ci+4][1], data[ci+4][2]);
var b2 = new THREE.Vector3(data[ci+5][0], data[ci+5][1], data[ci+5][2]);
var b3 = new THREE.Vector3(data[ci+6][0], data[ci+6][1], data[ci+6][2]);
var b4 = new THREE.Vector3(data[ci+7][0], data[ci+7][1], data[ci+7][2]);
var box = new THREE.Geometry();
box.vertices = [f1,f2,f3,f4,b1,b2,b3,b4];
// front
box.faces.push(new THREE.Face3(0,1,2));
box.faces.push(new THREE.Face3(0,2,3));
// back
box.faces.push(new THREE.Face3(4,5,6));
box.faces.push(new THREE.Face3(4,6,7));
// top
box.faces.push(new THREE.Face3(4,5,1));
box.faces.push(new THREE.Face3(4,1,0));
// bottom
box.faces.push(new THREE.Face3(2,6,7));
box.faces.push(new THREE.Face3(2,3,7));
// left
box.faces.push(new THREE.Face3(1,5,7));
box.faces.push(new THREE.Face3(1,3,7));
// right
box.faces.push(new THREE.Face3(4,6,2));
box.faces.push(new THREE.Face3(4,0,2));
box.computeFaceNormals();
box.computeVertexNormals();
return box;
}
function draw() {
for ( var key in detector_description ) {
var data = detector.Collections[key];
if ( ! data || data.length === 0 ) {
console.log(key);
continue;
}
var descr = detector_description[key];
var color = new THREE.Color(descr.style.color);
var transp = false;
if ( descr.style.opacity < 1.0 ) {
transp = true;
}
var geometry = new THREE.Geometry();
var lines = new THREE.Geometry();
var emissive = new THREE.Color(descr.style.emissive);
var specular = new THREE.Color(descr.style.specular);
var material = new THREE.MeshPhongMaterial({
color:color,
emissive:emissive,
shininess: 30,
transparent: transp,
opacity:descr.style.opacity});
material.side = THREE.DoubleSide;
for ( var i = 0; i < data.length; i++ ) {
geometry.merge(descr.methodA(data[i],1));
lines.merge(descr.methodB(data[i],1));
}
var mesh = new THREE.Mesh(geometry, material);
mesh.name = descr.name;
mesh.visible = true;
scene.add(mesh);
var line_material = new THREE.LineBasicMaterial({
color:color,
transparent: transp,
linewidth:descr.style.linewidth,
depthWrite: false,
opacity:descr.style.opacity
});
var line_mesh = new THREE.LineSegments(lines, line_material);
line_mesh.name = descr.name;
line_mesh.visible = true;
scene.add(line_mesh);
}
}
| {'content_hash': '301f38950ed9bf150fde7b362aa2b75f', 'timestamp': '', 'source': 'github', 'line_count': 479, 'max_line_length': 132, 'avg_line_length': 27.977035490605427, 'alnum_prop': 0.6361465562271472, 'repo_name': 'tpmccauley/cms-cardboard', 'id': 'ab647fcf92372d6bcf018a3c2435ee3ae8e1a0e9', 'size': '13401', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'js/cms-cardboard.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '1318'}, {'name': 'JavaScript', 'bytes': '1028084'}]} |
/**
* GRAPPELLI AUTOCOMPLETE FK
* foreign-key lookup with autocomplete
*/
(function($){
var methods = {
init: function(options) {
options = $.extend({}, $.fn.grp_autocomplete_fk.defaults, options);
return this.each(function() {
var $this = $(this);
// assign attributes
$this.attr({
"tabindex": "-1",
"readonly": "readonly"
}).addClass("grp-autocomplete-hidden-field");
// remove djangos object representation (if given)
if ($this.next().next() && $this.next().next().attr("class") != "errorlist" && $this.next().next().attr("class") != "grp-help") $this.next().next().remove();
// build autocomplete wrapper
$this.next().after(loader).after(remove_link($this.attr('id')));
$this.parent().wrapInner("<div class='grp-autocomplete-wrapper-fk'></div>");
$this.parent().prepend("<input id='" + $this.attr("id") + "-autocomplete' type='text' class='vTextField' value='' />");
// extend options
options = $.extend({
wrapper_autocomplete: $this.parent(),
input_field: $this.prev(),
remove_link: $this.next().next().hide(),
loader: $this.next().next().next().hide()
}, $.fn.grp_autocomplete_fk.defaults, options);
// lookup
lookup_id($this, options); // lookup when loading page
lookup_autocomplete($this, options); // autocomplete-handler
$this.bind("change focus keyup", function() { // id-handler
lookup_id($this, options);
});
// labels
$("label[for='"+$this.attr('id')+"']").each(function() {
$(this).attr("for", $this.attr("id")+"-autocomplete");
});
});
}
};
$.fn.grp_autocomplete_fk = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || ! method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.grp_autocomplete_fk');
}
return false;
};
var loader = function() {
var loader = $('<div class="grp-loader">loader</div>');
return loader;
};
var remove_link = function(id) {
var removelink = $('<a class="grp-related-remove"></a>');
removelink.attr('id', 'remove_'+id);
removelink.attr('href', 'javascript://');
removelink.attr('onClick', 'return removeRelatedObject(this);');
removelink.hover(function() {
$(this).parent().toggleClass("grp-autocomplete-preremove");
});
return removelink;
};
var lookup_autocomplete = function(elem, options) {
options.wrapper_autocomplete.find("input:first")
.bind("focus", function() {
options.wrapper_autocomplete.addClass("grp-state-focus");
})
.bind("blur", function() {
options.wrapper_autocomplete.removeClass("grp-state-focus");
})
.autocomplete({
minLength: 1,
delay: 1000,
source: function(request, response) {
$.ajax({
url: options.autocomplete_lookup_url,
dataType: 'json',
data: "term=" + encodeURIComponent(request.term) + "&app_label=" + grappelli.get_app_label(elem) + "&model_name=" + grappelli.get_model_name(elem) + "&query_string=" + grappelli.get_query_string(elem),
beforeSend: function (XMLHttpRequest) {
options.loader.show();
},
success: function(data){
response($.map(data, function(item) {
return {label: item.label, value: item.value};
}));
},
complete: function (XMLHttpRequest, textStatus) {
options.loader.hide();
}
});
},
focus: function() { // prevent value inserted on focus
return false;
},
select: function(event, ui) {
options.input_field.val(ui.item.label);
elem.val(ui.item.value);
elem.val() ? $(options.remove_link).show() : $(options.remove_link).hide();
return false;
}
})
.data("ui-autocomplete")._renderItem = function(ul,item) {
if (!item.value) {
return $("<li></li>")
.data( "item.autocomplete", item )
.append( "<span class='error'>" + item.label)
.appendTo(ul);
} else {
return $("<li></li>")
.data( "item.autocomplete", item )
.append( "<a>" + item.label)
.appendTo(ul);
}
};
};
var lookup_id = function(elem, options) {
$.getJSON(options.lookup_url, {
object_id: elem.val(),
app_label: grappelli.get_app_label(elem),
model_name: grappelli.get_model_name(elem)
}, function(data) {
$.each(data, function(index) {
options.input_field.val(data[index].label);
elem.val() ? $(options.remove_link).show() : $(options.remove_link).hide();
});
});
};
$.fn.grp_autocomplete_fk.defaults = {
autocomplete_lookup_url: '',
lookup_url: ''
};
})(grp.jQuery);
| {'content_hash': '88feb29191fd6dd2ed3f3a9e6c65f3be', 'timestamp': '', 'source': 'github', 'line_count': 144, 'max_line_length': 225, 'avg_line_length': 42.59027777777778, 'alnum_prop': 0.46404695907386273, 'repo_name': 'ngpitt/wrpi-web', 'id': '86274ca8beb57cb9725b82ca116f1d9a56f3e7cc', 'size': '6133', 'binary': False, 'copies': '21', 'ref': 'refs/heads/master', 'path': 'static/grappelli/js/jquery.grp_autocomplete_fk.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '46790'}, {'name': 'JavaScript', 'bytes': '110425'}, {'name': 'Python', 'bytes': '45707'}]} |
"""Holds the constants for pretty printing actions.xml."""
import os
import sys
# Import the metrics/common module for pretty print xml.
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'common'))
import pretty_print_xml
# Desired order for tag and tag attributes.
# { tag_name: [attribute_name, ...] }
ATTRIBUTE_ORDER = {
'action': ['name', 'not_user_triggered'],
'owner': [],
'description': [],
'obsolete': [],
}
# Tag names for top-level nodes whose children we don't want to indent.
TAGS_THAT_DONT_INDENT = ['actions']
# Extra vertical spacing rules for special tag names.
# {tag_name: (newlines_after_open, newlines_before_close, newlines_after_close)}
TAGS_THAT_HAVE_EXTRA_NEWLINE = {
'actions': (2, 1, 1),
'action': (1, 1, 1),
}
# Tags that we allow to be squished into a single line for brevity.
TAGS_THAT_ALLOW_SINGLE_LINE = ['owner', 'description', 'obsolete']
def GetPrintStyle():
"""Returns an XmlStyle object for pretty printing actions."""
return pretty_print_xml.XmlStyle(ATTRIBUTE_ORDER,
TAGS_THAT_HAVE_EXTRA_NEWLINE,
TAGS_THAT_DONT_INDENT,
TAGS_THAT_ALLOW_SINGLE_LINE)
| {'content_hash': '038d2460dd65badc318edfa375bea651', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 80, 'avg_line_length': 33.486486486486484, 'alnum_prop': 0.6343825665859564, 'repo_name': 'js0701/chromium-crosswalk', 'id': 'a2d4ff7cabbfb64bf534d621ee3e6c9cab5b3cdd', 'size': '1402', 'binary': False, 'copies': '19', 'ref': 'refs/heads/master', 'path': 'tools/metrics/actions/print_style.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []} |
import Debug from "debug";
import React, { PureComponent } from "react";
import { Redirect } from "react-router";
const log = Debug("my-app:components:NotFound");
class NotFound extends PureComponent<void> {
render() {
log("Route not found. Redirecting to /");
return <Redirect to="/" />;
}
}
export default NotFound;
| {'content_hash': '2014293b9ff6589b3b3aa89dceda6f14', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 48, 'avg_line_length': 23.785714285714285, 'alnum_prop': 0.6816816816816816, 'repo_name': 'tribou/react-template', 'id': 'ff8d4eb75bcbb98625f2cf2afee0332d750da7bc', 'size': '342', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/components/routes/NotFound/NotFound.ios.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '9594'}, {'name': 'Dockerfile', 'bytes': '770'}, {'name': 'HTML', 'bytes': '276'}, {'name': 'Java', 'bytes': '1760'}, {'name': 'JavaScript', 'bytes': '4290644'}, {'name': 'Makefile', 'bytes': '1618'}, {'name': 'Objective-C', 'bytes': '3966'}, {'name': 'Python', 'bytes': '1736'}, {'name': 'Shell', 'bytes': '1671'}]} |
package org.apache.aries.blueprint.plugin;
import java.io.File;
import java.io.FileOutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.aries.blueprint.plugin.model.Context;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.xbean.finder.ClassFinder;
/**
* Generates blueprint from spring annotations
* @goal blueprint-generate
* @phase process-classes
* @requiresDependencyResolution compile
* @inheritByDefault false
* @description Generates blueprint file from spring annotations @Component, @Autowire and @Value
*/
public class GenerateMojo extends AbstractMojo {
/**
* The maven project.
*
* @parameter default-value="${project}"
* @required
*/
protected MavenProject project;
/**
* @parameter
* @required
*/
protected List<String> scanPaths;
/**
* true: Purely annotated mode (needs jpa 2.1.0 and transaction-blueprint 1.1.0)
* false: XML based mode for JPA 1.x and transaction-blueprint < 1.1.0
* @parameter default-value="true"
* @required
*/
protected boolean persistenceAnnotated;
public void execute() throws MojoExecutionException, MojoFailureException {
try {
String buildDir = project.getBuild().getDirectory();
String generatedDir = buildDir + "/generated-resources";
Resource resource = new Resource();
resource.setDirectory(generatedDir);
project.addResource(resource);
ClassFinder finder = createProjectScopeFinder();
File file = new File(generatedDir, "OSGI-INF/blueprint/autowire.xml");
file.getParentFile().mkdirs();
System.out.println("Generating blueprint to " + file);
Set<Class<?>> classes = FilteredClassFinder.findClasses(finder, scanPaths);
Context context = new Context(classes);
context.resolve();
new Generator(context, new FileOutputStream(file), persistenceAnnotated).generate();
} catch (Exception e) {
throw new MojoExecutionException("Error building commands help", e);
}
}
private ClassFinder createProjectScopeFinder() throws MalformedURLException {
List<URL> urls = new ArrayList<URL>();
urls.add( new File(project.getBuild().getOutputDirectory()).toURI().toURL() );
for ( Object artifactO : project.getArtifacts() ) {
Artifact artifact = (Artifact)artifactO;
File file = artifact.getFile();
if ( file != null ) {
urls.add( file.toURI().toURL() );
}
}
ClassLoader loader = new URLClassLoader(urls.toArray(new URL[urls.size()]), getClass().getClassLoader());
return new ClassFinder(loader, urls);
}
}
| {'content_hash': 'd8f4a3846cb75fc67df570114896f46f', 'timestamp': '', 'source': 'github', 'line_count': 90, 'max_line_length': 113, 'avg_line_length': 35.28888888888889, 'alnum_prop': 0.6703400503778337, 'repo_name': 'metatechbe/aries', 'id': 'ed22653f3364c4c5d72248b04eba067171452104', 'size': '3984', 'binary': False, 'copies': '4', 'ref': 'refs/heads/trunk', 'path': 'blueprint/blueprint-maven-plugin/src/main/java/org/apache/aries/blueprint/plugin/GenerateMojo.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '488'}, {'name': 'CSS', 'bytes': '32833'}, {'name': 'Groff', 'bytes': '2338'}, {'name': 'HTML', 'bytes': '83923'}, {'name': 'Java', 'bytes': '8301134'}, {'name': 'JavaScript', 'bytes': '189672'}, {'name': 'Shell', 'bytes': '4200'}]} |
package de.codecentric.boot.admin.server.domain.entities;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
import org.springframework.util.Assert;
import de.codecentric.boot.admin.server.domain.values.BuildVersion;
import de.codecentric.boot.admin.server.domain.values.StatusInfo;
@lombok.Data
public final class Application {
private final String name;
@Nullable
private final BuildVersion buildVersion;
private final String status;
private final Instant statusTimestamp;
private final List<Instance> instances;
@lombok.Builder(builderClassName = "Builder", toBuilder = true)
private Application(String name, @Nullable BuildVersion buildVersion, @Nullable String status,
@Nullable Instant statusTimestamp, List<Instance> instances) {
Assert.notNull(name, "'name' must not be null");
this.name = name;
this.buildVersion = buildVersion;
this.status = (status != null) ? status : StatusInfo.STATUS_UNKNOWN;
this.statusTimestamp = (statusTimestamp != null) ? statusTimestamp : Instant.now();
if (instances.isEmpty()) {
this.instances = Collections.emptyList();
}
else {
this.instances = new ArrayList<>(instances);
}
}
public static Application.Builder create(String name) {
return builder().name(name);
}
public static class Builder {
// Will be generated by lombok
}
}
| {'content_hash': 'd16bebf583f34f557420962911dfd067', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 95, 'avg_line_length': 24.53448275862069, 'alnum_prop': 0.7561489810260014, 'repo_name': 'codecentric/spring-boot-admin', 'id': 'b47c38c55edd3ba2bc87debccdc5e036e4bf7d9e', 'size': '2043', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spring-boot-admin-server/src/main/java/de/codecentric/boot/admin/server/domain/entities/Application.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '620'}, {'name': 'Dockerfile', 'bytes': '159'}, {'name': 'HTML', 'bytes': '10958'}, {'name': 'Java', 'bytes': '1151898'}, {'name': 'JavaScript', 'bytes': '246625'}, {'name': 'SCSS', 'bytes': '4803'}, {'name': 'Vue', 'bytes': '384062'}]} |
<?php
namespace osCommerce\OM\Core\Site\Shop\Application\Products\Action;
use osCommerce\OM\Core\ApplicationAbstract;
use osCommerce\OM\Core\Registry;
use osCommerce\OM\Core\OSCOM;
class Specials {
public static function execute(ApplicationAbstract $application) {
$OSCOM_Service = Registry::get('Service');
$OSCOM_Breadcrumb = Registry::get('Breadcrumb');
$application->setPageTitle(OSCOM::getDef('specials_heading'));
$application->setPageContent('specials.php');
if ( $OSCOM_Service->isStarted('Breadcrumb') ) {
$OSCOM_Breadcrumb->add(OSCOM::getDef('breadcrumb_specials'), OSCOM::getLink(null, null, 'Specials'));
}
}
}
?>
| {'content_hash': '6704e7ed222ac3c03fc47ff48176d1cd', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 109, 'avg_line_length': 30.26086956521739, 'alnum_prop': 0.6882183908045977, 'repo_name': 'osCommerce/oscommerce', 'id': '659e682f74d32a3d72417bbfb853b6abee71a95a', 'size': '874', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'osCommerce/OM/Core/Site/Shop/Application/Products/Action/Specials.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'JavaScript', 'bytes': '82863'}, {'name': 'PHP', 'bytes': '2667400'}]} |
layout: page
title: Exquisite Zone Logistics Executive Retreat
date: 2016-05-24
author: Julie Orozco
tags: weekly links, java
status: published
summary: Integer aliquam lectus sit amet metus volutpat.
banner: images/banner/office-01.jpg
booking:
startDate: 03/11/2018
endDate: 03/16/2018
ctyhocn: MSYMTHX
groupCode: EZLER
published: true
---
Nulla a eleifend turpis, nec bibendum tortor. Pellentesque tempus laoreet ex eu pulvinar. Proin in tempor nunc. Maecenas et auctor nunc. Donec vel nunc nec felis cursus porta. Proin facilisis augue sed magna accumsan, a congue ligula volutpat. Ut ac mauris efficitur eros porta ornare. Duis fermentum est lacus, consectetur hendrerit metus lobortis ac.
* Sed rhoncus risus eu elit volutpat malesuada
* Nunc pellentesque ipsum ut lacus tempus, eu iaculis ligula auctor.
Mauris blandit turpis ac orci tincidunt laoreet nec nec dolor. Aenean vel tellus ante. Nunc varius libero vel magna congue cursus. Praesent ut suscipit risus. Maecenas nec consectetur augue, vel interdum diam. Curabitur a velit quam. Donec rutrum semper nunc sed congue. Mauris eget consequat urna.
Nulla malesuada ante at sapien tempor pellentesque. Phasellus dignissim arcu ac malesuada eleifend. Curabitur non volutpat sem. Sed faucibus, dui at dapibus tempus, tellus justo ullamcorper erat, iaculis suscipit ligula mi vitae libero. Praesent eu orci eget massa sodales molestie ac a arcu. Nulla rhoncus est sit amet augue dignissim hendrerit. Sed massa eros, maximus in felis ut, tincidunt lacinia ligula. Morbi eros est, sollicitudin et tortor ut, iaculis vulputate sapien. Fusce rhoncus, orci a rutrum auctor, nisi neque hendrerit sem, bibendum elementum turpis mi ac sapien. Quisque nec consectetur felis. Etiam auctor faucibus velit ac imperdiet. Phasellus quis rhoncus sem. Donec quis tincidunt nisl, nec facilisis risus.
| {'content_hash': '2180269a45d28879f87f8ca37f74cd90', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 730, 'avg_line_length': 84.13636363636364, 'alnum_prop': 0.8082117774176121, 'repo_name': 'KlishGroup/prose-pogs', 'id': '4fcaff37f2b60b2a214c8511add7bd241b3c864a', 'size': '1855', 'binary': False, 'copies': '1', 'ref': 'refs/heads/gh-pages', 'path': 'pogs/M/MSYMTHX/EZLER/index.md', 'mode': '33188', 'license': 'mit', 'language': []} |
"use strict";
define([
'backbone'
], function(
Backbone
) {
var Router = Backbone.Router.extend({
routes: {
//"media-gallery/:id": "mediaGalleryIdRedirect",
"media-gallery/:id/:pos": "mediaGallery",
"media-gallery-branded/:id/:pos": "mediaGalleryBranded",
//"_bb_": "clearState",
"*other": "defaultRoute"
},
initialize: function() {
/*
* Wiews without link
*/
backboneApp.poll = {};
$('.w__poll--left').each(function(i, o) {
require(['poll'], function(poll) {
var pollId = $(o).data('poll-id');
var poll = new poll({
pollId: pollId,
$elem: $(o),
thumbor: {
resizeWidth: '342',
resizeHeight: '230'
}
});
backboneApp.poll["asside-" + i] = {};
backboneApp.poll["asside-" + i].view = poll;
});
});
$('.w__poll--right').each(function(i, o) {
require(['poll'], function(poll) {
var pollId = $(o).data('poll-id');
var poll = new poll({
pollId: pollId,
$elem: $(o),
thumbor: {
resizeWidth: '468',
resizeHeight: '340'
}
});
backboneApp.poll["all-" + i] = {};
backboneApp.poll["all-" + i].view = poll;
});
});
},
mediaGallery: function(id, currentItem) {
currentItem = currentItem || 1;
require(['mediaGallery'], function(mediaGalleryView) {
if (backboneApp.mediaGallery) {
backboneApp.mediaGallery.afterMoveUnhashedOnce = true;
backboneApp.mediaGallery.owlSliderGoTo(currentItem);
return;
}
var $elem = $('.media-gallery-' + id);
backboneApp.mediaGallery = new mediaGalleryView({$elem: $elem, currentItem: currentItem, id: id});
if (backboneApp.set.device === 'desktop') {
backboneApp.mediaGallery.parse();
backboneApp.mediaGallery.render();
} else if (backboneApp.set.device === 'tablet') {
backboneApp.mediaGallery.viewportRollBack = $('meta[name=viewport]').attr("content");
backboneApp.mediaGallery.parse();
backboneApp.mediaGallery.renderTab();
} else {
backboneApp.mediaGallery.parse();
backboneApp.mediaGallery.renderMob();
}
});
},
mediaGalleryBranded: function (id, currentItem) {
currentItem = currentItem || 1;
require(['mediaGalleryBranded'], function (mediaGalleryBrandedView) {
var $elem = $('.media-gallery-branded' + id);
backboneApp.mediaGalleryBranded = new mediaGalleryBrandedView({$elem: $elem, currentItem: currentItem, id: id});
});
},
defaultRoute: function() {
if (backboneApp.mediaGallery) {
if(backboneApp.mediaGallery.viewportRollBack){
$('meta[name=viewport]').attr("content", backboneApp.mediaGallery.viewportRollBack);
location = window.location.protocol + '//' + window.location.host + location.pathname;
return;
}
backboneApp.mediaGallery.undelegateEvents();
backboneApp.mediaGallery.close();
delete backboneApp.mediaGallery;
}
if (backboneApp.mediaGalleryBranded) {
backboneApp.mediaGalleryBranded.close();
delete backboneApp.mediaGalleryBranded;
}
}
});
return {
initialize: function() {
var router = new Router();
Backbone.history.start();
//Backbone.history.start({ pushState: true });
return {router: router};
}
};
}); | {'content_hash': 'f186ea07934b48955f45ed25a134232d', 'timestamp': '', 'source': 'github', 'line_count': 120, 'max_line_length': 120, 'avg_line_length': 30.716666666666665, 'alnum_prop': 0.5499186109603906, 'repo_name': 'biosonic/yasmina-backbone-app', 'id': '0a26709abc131d923fde5308bb20897ccb17b2f1', 'size': '3686', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/router.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '263997'}, {'name': 'HTML', 'bytes': '42873'}, {'name': 'JavaScript', 'bytes': '116505'}, {'name': 'Smarty', 'bytes': '5205'}]} |
#ifndef THIRD_PARTY_TENSORFLOW_CORE_KERNELS_REMOTE_FUSED_GRAPH_EXECUTE_UTILS_H_
#define THIRD_PARTY_TENSORFLOW_CORE_KERNELS_REMOTE_FUSED_GRAPH_EXECUTE_UTILS_H_
#include <unordered_map>
#include <unordered_set>
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/remote_fused_graph_execute_info.pb.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/graph/graph_constructor.h"
#include "tensorflow/core/kernels/i_remote_fused_graph_executor.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/macros.h"
namespace tensorflow {
// RemoteFusedGraphExecuteUtils provides APIs to register and get builder
// functions for IRemoteFusedGraphExecutor.
class RemoteFusedGraphExecuteUtils {
public:
// TODO(satok): Use "_output_data_types" to share a spec with other ops
static constexpr const char* const ATTR_OUTPUT_DATA_TYPES =
"_default_remote_graph_output_data_types";
// TODO(satok): Use "_output_shapes" to share a spec with other ops
static constexpr const char* const ATTR_OUTPUT_SHAPES =
"_default_remote_output_shapes";
static constexpr const char* const
ATTR_SERIALIZED_REMOTE_FUSED_GRAPH_EXECUTE_INFO =
"serialized_remote_fused_graph_execute_info";
static constexpr const char* const ATTR_NODE_TYPE =
"_remote_fused_graph_node_type";
// Argument key strings to fuse a subgraph into RemoteFusedGraphExecuteOp.
static constexpr const char* const
TRANSFORM_ARG_REMOTE_FUSED_GRAPH_EXECUTOR_NAME =
"remote_fused_graph_executor_name";
static constexpr const char* const
TRANSFORM_ARG_REMOTE_FUSED_GRAPH_NODE_NAME =
"remote_fused_graph_node_name";
static constexpr const char* const TRANSFORM_ARG_FUSED_NODES = "fused_nodes";
static constexpr const char* const TRANSFORM_ARG_BORDER_INPUTS =
"border_inputs";
static constexpr const char* const TRANSFORM_ARG_BORDER_OUTPUTS =
"border_outputs";
static constexpr const char* const TRANSFORM_ARG_FUSED_OP_TYPES =
"fused_op_types";
static constexpr const char* const TRANSFORM_ARG_INPUT_TYPES = "input_types";
static constexpr const char* const TRANSFORM_ARG_INPUT_SHAPES =
"input_shapes";
using ExecutorBuildFunc = std::function<Status(
std::unique_ptr<IRemoteFusedGraphExecutor>* executor)>;
// Registrar class for IRemoteFusedGraphExecutor.
class ExecutorBuildRegistrar {
public:
ExecutorBuildRegistrar(const string& name, ExecutorBuildFunc func);
private:
TF_DISALLOW_COPY_AND_ASSIGN(ExecutorBuildRegistrar);
};
using ExecutorBuildRegistry = std::map<string, ExecutorBuildFunc>;
using TensorShapeType = std::pair<DataType, TensorShape>;
using TensorShapeMap = std::unordered_multimap<string, // node name
std::pair<int, // port
TensorShapeType>>;
using ClusterInfo = std::tuple<std::unordered_set<string>, // node names
std::vector<string>, // border inputs
std::vector<string>>; // border outputs
// Return registered ExecutorBuildFunc for given name.
static const ExecutorBuildFunc* GetExecutorBuildFunc(const string& name);
// To determine shapes of output tensors of all nodes, dryrun the graph.
// This function supplies memory allocation information when loading
// the graph. This function is used to verify shape inference and actual
// output shape.
static Status DryRunInference(
const GraphDef& graph_def,
const std::vector<std::pair<string, Tensor>>& input_node_info_list,
const std::vector<string>& output_node_names,
const bool initialize_by_zero,
std::vector<tensorflow::Tensor>* output_tensors);
// Dry run inference to obtain shapes for all nodes.
// CAVEAT: Do not add or modify output_tensors in output_tensor_info
// otherwise, address map may be broken by re-allocation inside
// std::vector.
static Status DryRunInferenceForAllNode(
const GraphDef& graph_def,
const std::vector<std::pair<string, Tensor>>& input_node_info_list,
const bool initialize_by_zero, TensorShapeMap* tensor_shape_map);
static bool IsInputNode(
const std::vector<std::pair<string, Tensor>>& input_node_info_list,
const string& node_name);
static void ConvertToTensorShapeMap(
const std::vector<std::pair<string, Tensor>>& input_node_info_list,
const std::vector<string>& output_node_names,
const std::vector<tensorflow::Tensor>& output_tensors,
TensorShapeMap* tensor_shape_map);
static Status MakeTensorFromProto(const TensorProto& tensor_proto,
Tensor* tensor);
static bool AddOutputTensorShapeType(const std::vector<DataType>& data_types,
const std::vector<TensorShape>& shapes,
NodeDef* node_def);
static Status AddOutputTensorShapeTypeByTensorShapeMap(
const TensorShapeMap& tensor_shape_map, NodeDef* node_def);
static Status GetOutputTensorShapeType(AttrSlice attrs,
std::vector<DataType>* data_types,
std::vector<TensorShape>* shapes);
static bool GetOutputTensorShapeType(const GraphDef& graph_def,
const string& name_and_port,
DataType* data_type, TensorShape* shape);
static Status PropagateShapeInference(
const GraphDef& graph_def,
const std::vector<std::pair<string, Tensor>>& input_node_info_list,
Graph* graph, ShapeRefiner* shape_refiner);
static Status BuildTensorShapeMapFromGraph(const Graph& graph,
const ShapeRefiner& shape_refiner,
TensorShapeMap* tensor_shape_map);
static const TensorShapeType* GetTensorShapeType(
const TensorShapeMap& tensor_shape_map, const string& node_name);
static const TensorShapeType* GetTensorShapeType(
const TensorShapeMap& tensor_shape_map, const string& node_name,
const int port);
static void BuildRemoteGraphInputsAndOutputsFromProto(
const RemoteFusedGraphExecuteInfo& proto,
std::vector<std::pair<string, Tensor>>* inputs,
std::vector<string>* outputs);
static Status BuildAndAddTensorShapes(
const std::vector<std::pair<string, Tensor>>& input_tensors,
const bool dry_run_inference, GraphDef* graph_def);
// Build remote fused graph execute info.
static Status BuildRemoteFusedGraphExecuteInfo(
const string& executor_name, const GraphDef& subgraph_def,
const std::vector<string>& inputs, const std::vector<string>& outputs,
const bool require_shape_type, RemoteFusedGraphExecuteInfo* execute_info,
DataTypeVector* input_types, DataTypeVector* output_types);
// Build remote fused graph execute op node by fusing specified subgraph
// as remote fused graph execute info.
static Status BuildRemoteFusedGraphExecuteOpNode(
const string& node_name, const string& executor_name,
const GraphDef& subgraph_def, const std::vector<string>& inputs,
const std::vector<string>& outputs, const bool require_shape_type,
Graph* graph, Node** created_node);
// Build Identity node to forward remote graph node output.
static Status BuildIdentityOpNode(const string& node_name,
const string& input_node_name,
const int input_node_port,
const DataType dt, Graph* graph,
Node** created_node);
// Create clusters of given nodes.
static Status ClusterizeNodes(const std::unordered_set<string>& node_names,
const GraphDef& graph_def,
std::vector<ClusterInfo>* cluster_infos);
// Build GraphDef of a given cluster.
static Status BuildClusterSubgraphDef(const ClusterInfo& cluster,
const GraphDef& graph_def,
GraphDef* subgraph_def);
// Build a cluster by given border.
// CAVEAT: The border must be consistent for one cluster.
static Status BuildClusterByBorder(const std::vector<string>& border_inputs,
const std::vector<string>& border_outputs,
const GraphDef& graph_def,
ClusterInfo* cluster);
// Fuse one cluster into a newly created RemoteFusedGraphExecuteOp node.
// The subgraph is stored as a graph in RemoteFusedGraphExecuteInfo.
// CAVEAT1: This transform strips unvisited nodes with given outputs.
// CAVEAT2: If you want to use a graph output as a border output,
// that graph output node is replaced by an identity node. Therefore,
// the number of output of the node must be 1.
static Status FuseCluster(const GraphDef& input_graph_def,
const std::vector<string>& inputs,
const std::vector<string>& outputs,
const string& remote_fused_graph_node_name,
const ClusterInfo& cluster,
const string& remote_graph_executor_name,
const bool require_shape_type,
GraphDef* output_graph_def);
// Fuse subgraph of specified nodes.
static Status FuseRemoteGraphByNodeNames(
const GraphDef& input_graph_def, const std::vector<string>& inputs,
const std::vector<string>& outputs,
const string& remote_fused_graph_node_name_prefix,
const std::unordered_set<string>& subgraph_nodes,
const string& remote_fused_graph_executor_name,
const bool require_shape_type, GraphDef* output_graph_def);
// Fuse subgraph of specified border.
static Status FuseRemoteGraphByBorder(
const GraphDef& input_graph_def, const std::vector<string>& inputs,
const std::vector<string>& outputs,
const string& remote_fused_graph_node_name,
const std::vector<string>& border_inputs,
const std::vector<string>& border_outputs,
const string& remote_graph_executor_name, const bool require_shape_type,
GraphDef* output_graph_def);
// Fuse subgraph of specified op types.
static Status FuseRemoteGraphByOpTypes(
const GraphDef& input_graph_def, const std::vector<string>& inputs,
const std::vector<string>& outputs,
const string& remote_fused_graph_node_name_prefix,
const std::unordered_set<string>& fused_op_types,
const string& remote_fused_graph_executor_name,
const bool require_shape_type, GraphDef* output_graph_def);
// Place arguments to fuse remote graph.
static Status PlaceRemoteGraphArguments(
const std::vector<string>& inputs, const std::vector<string>& outputs,
const std::unordered_set<string>& fused_node_names,
const std::vector<string>& border_inputs,
const std::vector<string>& border_outputs,
const std::unordered_set<string>& fused_op_types,
const string& remote_fused_graph_node_name,
const string& remote_graph_executor_name, GraphDef* graph_def);
// Fuse remote graph by placed arguments.
static Status FuseRemoteGraphByPlacedArguments(
const GraphDef& input_graph_def,
const std::vector<std::pair<string, Tensor>>& input_tensors,
GraphDef* output_graph_def);
static bool IsFuseReady(
const GraphDef& input_graph_def,
const std::vector<std::pair<string, Tensor>>& input_tensors);
// Copy a byte array to a tensor data. Though tensor data must be
// updated with typed information in general, we can't guarantee that
// returned values from a remote processor has typed information because
// a logic running in the remote processor possibly be in a separate binary
// which may not link tensorflow libraries. To deal with this situation,
// remote fused graph needs to overwrite the tensor data by a byte array.
static Status CopyByteArrayToTensor(const void* src_ptr, const int src_size,
Tensor* tensor);
static std::unordered_set<string> BuildNodeMapFromOpTypes(
const GraphDef& graph_def, const std::unordered_set<string>& op_types);
private:
static void EmplaceTensorShapeType(const string& name, const Tensor& tensor,
TensorShapeMap* tensor_shape_map);
static Status ReplaceInputNodeByPlaceHolder(const string& input,
const DataType type,
const TensorShape& shape,
GraphDef* graph_def);
static ExecutorBuildRegistry* GetExecutorBuildRegistry();
static string BuildNodeTypeAttr(
const RemoteFusedGraphExecuteInfo::NodeType node_type, const int port,
const int index, const string& executor_name, const string& node_name);
static string BuildNodeTypeAttr(
const RemoteFusedGraphExecuteInfo::NodeType node_type, const int port,
const int index);
static string BuildNodeTypeAttr(
const RemoteFusedGraphExecuteInfo::NodeType node_type);
TF_DISALLOW_COPY_AND_ASSIGN(RemoteFusedGraphExecuteUtils);
};
} // namespace tensorflow
#endif // THIRD_PARTY_TENSORFLOW_CORE_KERNELS_REMOTE_FUSED_GRAPH_EXECUTE_UTILS_H_
| {'content_hash': '83e55d23d8d5748cd400ca09ebcb7656', 'timestamp': '', 'source': 'github', 'line_count': 289, 'max_line_length': 82, 'avg_line_length': 47.1038062283737, 'alnum_prop': 0.6693601704253287, 'repo_name': 'npuichigo/ttsflow', 'id': '28d170d98255e703cc1549fff04e4837242d74ea', 'size': '14281', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'third_party/tensorflow/tensorflow/core/kernels/remote_fused_graph_execute_utils.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '18829'}, {'name': 'C++', 'bytes': '90117'}, {'name': 'Makefile', 'bytes': '7954'}, {'name': 'Python', 'bytes': '5824'}]} |
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('nl2br', 'helper:nl2br', {
integration: true
});
test('It formats the input text with `nl2br` format', function(assert) {
assert.expect(7);
this.set('input', 'This is some text');
this.render(hbs`{{nl2br input}}`);
assert.equal(this.$().html(), 'This is some text');
this.set('input', 'This is some text\rwith a line break');
assert.equal(this.$().html(), 'This is some text<br>with a line break');
this.set('input', 'This is some text\nwith a line break');
assert.equal(this.$().html(), 'This is some text<br>with a line break');
this.set('input', 'This is some text\r\nwith a line break');
assert.equal(this.$().html(), 'This is some text<br>with a line break');
this.set('input', 'This is some text\r\r\rwith many line breaks');
assert.equal(this.$().html(), 'This is some text<br><br><br>with a line break');
this.set('input', 'This is some text\n\n\nwith many line breaks');
assert.equal(this.$().html(), 'This is some text<br><br><br>with a line break');
this.set('input', 'This is some text\r\n\r\n\r\nwith many line breaks');
assert.equal(this.$().html(), 'This is some text<br><br><br>with a line break');
});
| {'content_hash': 'e4a9b557e71f258445da7328a9b63c3f', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 81, 'avg_line_length': 50.36, 'alnum_prop': 0.675933280381255, 'repo_name': 'abcum/ember-helpers', 'id': '492ad307b59a15e6f08525651b86a3d8463177ce', 'size': '1259', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/integration/helpers/nl2br.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '310'}, {'name': 'HTML', 'bytes': '2360'}, {'name': 'JavaScript', 'bytes': '149249'}, {'name': 'Makefile', 'bytes': '1090'}]} |
var Express = require('express')
var webpack = require('webpack')
var path = require('path')
var serveStatic = require('serve-static')
var webpackConfig = require('./dev.config')
var compiler = webpack(webpackConfig)
var host = process.env.HOST || 'localhost'
var port = 3030
var serverOptions = {
quiet: true,
noInfo: true,
hot: true,
inline: true,
lazy: false,
publicPath: webpackConfig.output.publicPath,
stats: {colors: true}
}
var app = new Express()
app.use(require('webpack-dev-middleware')(compiler, serverOptions))
app.use(require('webpack-hot-middleware')(compiler))
app.use(serveStatic(path.join(__dirname, '..')))
app.listen(port, function onAppListening(err) {
if (err) {
console.error(err)
} else {
console.info('==> 🚧 Webpack development server listening on port %s', port)
}
})
| {'content_hash': '343f954034db6954a0f46b03938ac66a', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 80, 'avg_line_length': 25.09090909090909, 'alnum_prop': 0.6968599033816425, 'repo_name': 'erikras/redux-form-docs', 'id': 'dbe31f7d8cb6b6c01dc3991a5b524e126dfbad0c', 'size': '831', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': '5.1.3/webpack/webpack-dev-server.js', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1987357'}, {'name': 'HTML', 'bytes': '31146010'}, {'name': 'JavaScript', 'bytes': '1316710'}]} |
TEST_NO_CREATE_REPO=NoThanks
. ./test-lib.sh
if ! test_have_prereq PYTHON; then
skip_all='skipping git p4 tests; python not available'
test_done
fi
( p4 -h && p4d -h ) >/dev/null 2>&1 || {
skip_all='skipping git p4 tests; no p4 or p4d'
test_done
}
# Try to pick a unique port: guess a large number, then hope
# no more than one of each test is running.
#
# This does not handle the case where somebody else is running the
# same tests and has chosen the same ports.
testid=${this_test#t}
git_p4_test_start=9800
P4DPORT=$((10669 + ($testid - $git_p4_test_start)))
P4PORT=localhost:$P4DPORT
P4CLIENT=client
P4EDITOR=:
export P4PORT P4CLIENT P4EDITOR
db="$TRASH_DIRECTORY/db"
cli=$(test-path-utils real_path "$TRASH_DIRECTORY/cli")
git="$TRASH_DIRECTORY/git"
pidfile="$TRASH_DIRECTORY/p4d.pid"
start_p4d() {
mkdir -p "$db" "$cli" "$git" &&
rm -f "$pidfile" &&
(
p4d -q -r "$db" -p $P4DPORT &
echo $! >"$pidfile"
) &&
# This gives p4d a long time to start up, as it can be
# quite slow depending on the machine. Set this environment
# variable to something smaller to fail faster in, say,
# an automated test setup. If the p4d process dies, that
# will be caught with the "kill -0" check below.
i=${P4D_START_PATIENCE:-300}
pid=$(cat "$pidfile")
ready=
while test $i -gt 0
do
# succeed when p4 client commands start to work
if p4 info >/dev/null 2>&1
then
ready=true
break
fi
# fail if p4d died
kill -0 $pid 2>/dev/null || break
echo waiting for p4d to start
sleep 1
i=$(( $i - 1 ))
done
if test -z "$ready"
then
# p4d failed to start
return 1
fi
# build a client
(
cd "$cli" &&
p4 client -i <<-EOF
Client: client
Description: client
Root: $cli
View: //depot/... //client/...
EOF
)
return 0
}
kill_p4d() {
pid=$(cat "$pidfile")
# it had better exist for the first kill
kill $pid &&
for i in 1 2 3 4 5 ; do
kill $pid >/dev/null 2>&1 || break
sleep 1
done &&
# complain if it would not die
test_must_fail kill $pid >/dev/null 2>&1 &&
rm -rf "$db" "$cli" "$pidfile"
}
cleanup_git() {
rm -rf "$git" &&
mkdir "$git"
}
marshal_dump() {
what=$1 &&
line=${2:-1} &&
cat >"$TRASH_DIRECTORY/marshal-dump.py" <<-EOF &&
import marshal
import sys
for i in range($line):
d = marshal.load(sys.stdin)
print d['$what']
EOF
"$PYTHON_PATH" "$TRASH_DIRECTORY/marshal-dump.py"
}
#
# Construct a client with this list of View lines
#
client_view() {
(
cat <<-EOF &&
Client: client
Description: client
Root: $cli
View:
EOF
for arg ; do
printf "\t$arg\n"
done
) | p4 client -i
}
| {'content_hash': 'a28385b20b5fe57433f6c966e21ef8dc', 'timestamp': '', 'source': 'github', 'line_count': 129, 'max_line_length': 66, 'avg_line_length': 20.046511627906977, 'alnum_prop': 0.6407579273008507, 'repo_name': 'anatm/administrator', 'id': '7061dce7e5de2f67e60fe6c42c40519f29cad4a1', 'size': '2719', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'git-1.8.1/t/lib-git-p4.sh', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '6064'}, {'name': 'Assembly', 'bytes': '7443'}, {'name': 'C', 'bytes': '4510704'}, {'name': 'C++', 'bytes': '225575'}, {'name': 'CSS', 'bytes': '12784'}, {'name': 'Emacs Lisp', 'bytes': '86984'}, {'name': 'Go', 'bytes': '15064'}, {'name': 'JavaScript', 'bytes': '49702'}, {'name': 'Makefile', 'bytes': '123973'}, {'name': 'Objective-C', 'bytes': '504'}, {'name': 'PHP', 'bytes': '170335'}, {'name': 'Perl', 'bytes': '1036241'}, {'name': 'Python', 'bytes': '258210'}, {'name': 'Shell', 'bytes': '3482375'}, {'name': 'Tcl', 'bytes': '642985'}]} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ECALL.CPP -
//
// Handles our private native calling interface.
//
#include "common.h"
#include "ecall.h"
#include "comdelegate.h"
#ifndef DACCESS_COMPILE
#ifdef CROSSGEN_COMPILE
namespace CrossGenMscorlib
{
extern const ECClass c_rgECClasses[];
extern const int c_nECClasses;
};
using namespace CrossGenMscorlib;
#else // CROSSGEN_COMPILE
extern const ECClass c_rgECClasses[];
extern const int c_nECClasses;
#endif // CROSSGEN_COMPILE
/**********
The constructors of string-like types (String, Utf8String) are special since the JIT will
replace newobj instructions with calls to the corresponding 'Ctor' method. Depending on the
CLR in use, the ctor methods may be instance methods (with a null 'this' parameter) or
static methods. See the managed definitions of String.Ctor and Utf8String.Ctor for more
information.
To add a new ctor overload, in addition to defining the constructor and Ctor methods on
the managed side, make changes to the following files. (These instructions are for
Utf8String, but String is similar.)
- src/vm/ecall.cpp (this file), update the definition of "NumberOfUtf8StringConstructors"
and add the appropriate static asserts immediately above the definition.
- src/vm/ecall.h, search for "Utf8StringCtor" and add the DYNAMICALLY_ASSIGNED_FCALL_IMPL
definitions corresponding to the new overloads.
- src/vm/ecalllist.h, search for "FCFuncStart(gUtf8StringFuncs)" and add the overloads
within that block.
- src/vm/metasig.h, add the new Utf8String-returning metasig declarations; and, if necessary,
add any void-returning metasig declarations if they haven't already been defined elsewhere.
search "String_RetUtf8Str" for an example of how to do this.
- src/vm/mscorlib.h, search "DEFINE_CLASS(UTF8_STRING" and add the new DEFINE_METHOD
declarations for the Utf8String-returning Ctor methods, referencing the new metasig declarations.
**********/
// METHOD__STRING__CTORF_XXX has to be in same order as ECall::CtorCharXxx
#define METHOD__STRING__CTORF_FIRST METHOD__STRING__CTORF_CHARARRAY
static_assert_no_msg(METHOD__STRING__CTORF_FIRST + 0 == METHOD__STRING__CTORF_CHARARRAY);
static_assert_no_msg(METHOD__STRING__CTORF_FIRST + 1 == METHOD__STRING__CTORF_CHARARRAY_START_LEN);
static_assert_no_msg(METHOD__STRING__CTORF_FIRST + 2 == METHOD__STRING__CTORF_CHAR_COUNT);
static_assert_no_msg(METHOD__STRING__CTORF_FIRST + 3 == METHOD__STRING__CTORF_CHARPTR);
static_assert_no_msg(METHOD__STRING__CTORF_FIRST + 4 == METHOD__STRING__CTORF_CHARPTR_START_LEN);
static_assert_no_msg(METHOD__STRING__CTORF_FIRST + 5 == METHOD__STRING__CTORF_READONLYSPANOFCHAR);
static_assert_no_msg(METHOD__STRING__CTORF_FIRST + 6 == METHOD__STRING__CTORF_SBYTEPTR);
static_assert_no_msg(METHOD__STRING__CTORF_FIRST + 7 == METHOD__STRING__CTORF_SBYTEPTR_START_LEN);
static_assert_no_msg(METHOD__STRING__CTORF_FIRST + 8 == METHOD__STRING__CTORF_SBYTEPTR_START_LEN_ENCODING);
// ECall::CtorCharXxx has to be in same order as METHOD__STRING__CTORF_XXX
#define ECallCtor_First ECall::CtorCharArrayManaged
static_assert_no_msg(ECallCtor_First + 0 == ECall::CtorCharArrayManaged);
static_assert_no_msg(ECallCtor_First + 1 == ECall::CtorCharArrayStartLengthManaged);
static_assert_no_msg(ECallCtor_First + 2 == ECall::CtorCharCountManaged);
static_assert_no_msg(ECallCtor_First + 3 == ECall::CtorCharPtrManaged);
static_assert_no_msg(ECallCtor_First + 4 == ECall::CtorCharPtrStartLengthManaged);
static_assert_no_msg(ECallCtor_First + 5 == ECall::CtorReadOnlySpanOfCharManaged);
static_assert_no_msg(ECallCtor_First + 6 == ECall::CtorSBytePtrManaged);
static_assert_no_msg(ECallCtor_First + 7 == ECall::CtorSBytePtrStartLengthManaged);
static_assert_no_msg(ECallCtor_First + 8 == ECall::CtorSBytePtrStartLengthEncodingManaged);
#define NumberOfStringConstructors 9
#ifdef FEATURE_UTF8STRING
// METHOD__UTF8STRING__CTORF_XXX has to be in same order as ECall::Utf8StringCtorCharXxx
#define METHOD__UTF8STRING__CTORF_FIRST METHOD__UTF8_STRING__CTORF_READONLYSPANOFBYTE
static_assert_no_msg(METHOD__UTF8STRING__CTORF_FIRST + 0 == METHOD__UTF8_STRING__CTORF_READONLYSPANOFBYTE);
static_assert_no_msg(METHOD__UTF8STRING__CTORF_FIRST + 1 == METHOD__UTF8_STRING__CTORF_READONLYSPANOFCHAR);
static_assert_no_msg(METHOD__UTF8STRING__CTORF_FIRST + 2 == METHOD__UTF8_STRING__CTORF_BYTEARRAY_START_LEN);
static_assert_no_msg(METHOD__UTF8STRING__CTORF_FIRST + 3 == METHOD__UTF8_STRING__CTORF_BYTEPTR);
static_assert_no_msg(METHOD__UTF8STRING__CTORF_FIRST + 4 == METHOD__UTF8_STRING__CTORF_CHARARRAY_START_LEN);
static_assert_no_msg(METHOD__UTF8STRING__CTORF_FIRST + 5 == METHOD__UTF8_STRING__CTORF_CHARPTR);
static_assert_no_msg(METHOD__UTF8STRING__CTORF_FIRST + 6 == METHOD__UTF8_STRING__CTORF_STRING);
// ECall::Utf8StringCtorCharXxx has to be in same order as METHOD__UTF8STRING__CTORF_XXX
#define ECallUtf8String_Ctor_First ECall::Utf8StringCtorReadOnlySpanOfByteManaged
static_assert_no_msg(ECallUtf8String_Ctor_First + 0 == ECall::Utf8StringCtorReadOnlySpanOfByteManaged);
static_assert_no_msg(ECallUtf8String_Ctor_First + 1 == ECall::Utf8StringCtorReadOnlySpanOfCharManaged);
static_assert_no_msg(ECallUtf8String_Ctor_First + 2 == ECall::Utf8StringCtorByteArrayStartLengthManaged);
static_assert_no_msg(ECallUtf8String_Ctor_First + 3 == ECall::Utf8StringCtorBytePtrManaged);
static_assert_no_msg(ECallUtf8String_Ctor_First + 4 == ECall::Utf8StringCtorCharArrayStartLengthManaged);
static_assert_no_msg(ECallUtf8String_Ctor_First + 5 == ECall::Utf8StringCtorCharPtrManaged);
static_assert_no_msg(ECallUtf8String_Ctor_First + 6 == ECall::Utf8StringCtorStringManaged);
#define NumberOfUtf8StringConstructors 7
#endif // FEATURE_UTF8STRING
void ECall::PopulateManagedStringConstructors()
{
STANDARD_VM_CONTRACT;
INDEBUG(static bool fInitialized = false);
_ASSERTE(!fInitialized); // assume this method is only called once
_ASSERTE(g_pStringClass != NULL);
for (int i = 0; i < NumberOfStringConstructors; i++)
{
MethodDesc* pMD = MscorlibBinder::GetMethod((BinderMethodID)(METHOD__STRING__CTORF_FIRST + i));
_ASSERTE(pMD != NULL);
PCODE pDest = pMD->GetMultiCallableAddrOfCode();
ECall::DynamicallyAssignFCallImpl(pDest, ECallCtor_First + i);
}
#ifdef FEATURE_UTF8STRING
_ASSERTE(g_pUtf8StringClass != NULL);
for (int i = 0; i < NumberOfUtf8StringConstructors; i++)
{
MethodDesc* pMD = MscorlibBinder::GetMethod((BinderMethodID)(METHOD__UTF8STRING__CTORF_FIRST + i));
_ASSERTE(pMD != NULL);
PCODE pDest = pMD->GetMultiCallableAddrOfCode();
ECall::DynamicallyAssignFCallImpl(pDest, ECallUtf8String_Ctor_First + i);
}
#endif // FEATURE_UTF8STRING
INDEBUG(fInitialized = true);
}
static CrstStatic gFCallLock;
// This variable is used to force the compiler not to tailcall a function.
int FC_NO_TAILCALL;
#endif // !DACCESS_COMPILE
// To provide a quick check, this is the lowest and highest
// addresses of any FCALL starting address
GVAL_IMPL_INIT(TADDR, gLowestFCall, (TADDR)-1);
GVAL_IMPL(TADDR, gHighestFCall);
GARY_IMPL(PTR_ECHash, gFCallMethods, FCALL_HASH_SIZE);
inline unsigned FCallHash(PCODE pTarg) {
LIMITED_METHOD_DAC_CONTRACT;
return pTarg % FCALL_HASH_SIZE;
}
#ifdef DACCESS_COMPILE
GARY_IMPL(PCODE, g_FCDynamicallyAssignedImplementations,
ECall::NUM_DYNAMICALLY_ASSIGNED_FCALL_IMPLEMENTATIONS);
#else // !DACCESS_COMPILE
PCODE g_FCDynamicallyAssignedImplementations[ECall::NUM_DYNAMICALLY_ASSIGNED_FCALL_IMPLEMENTATIONS] = {
#undef DYNAMICALLY_ASSIGNED_FCALL_IMPL
#define DYNAMICALLY_ASSIGNED_FCALL_IMPL(id,defaultimpl) GetEEFuncEntryPoint(defaultimpl),
DYNAMICALLY_ASSIGNED_FCALLS()
};
void ECall::DynamicallyAssignFCallImpl(PCODE impl, DWORD index)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
_ASSERTE(index < NUM_DYNAMICALLY_ASSIGNED_FCALL_IMPLEMENTATIONS);
g_FCDynamicallyAssignedImplementations[index] = impl;
}
/*******************************************************************************/
static INT FindImplsIndexForClass(MethodTable* pMT)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
LPCUTF8 pszNamespace = 0;
LPCUTF8 pszName = pMT->GetFullyQualifiedNameInfo(&pszNamespace);
// Array classes get null from the above routine, but they have no ecalls.
if (pszName == NULL)
return (-1);
unsigned low = 0;
unsigned high = c_nECClasses;
#ifdef _DEBUG
static bool checkedSort = false;
if (!checkedSort) {
checkedSort = true;
for (unsigned i = 1; i < high; i++) {
// Make certain list is sorted!
int cmp = strcmp(c_rgECClasses[i].m_szClassName, c_rgECClasses[i-1].m_szClassName);
if (cmp == 0)
cmp = strcmp(c_rgECClasses[i].m_szNameSpace, c_rgECClasses[i-1].m_szNameSpace);
_ASSERTE(cmp > 0 && W("You forgot to keep ECall class names sorted")); // Hey, you forgot to sort the new class
}
}
#endif // _DEBUG
while (high > low) {
unsigned mid = (high + low) / 2;
int cmp = strcmp(pszName, c_rgECClasses[mid].m_szClassName);
if (cmp == 0)
cmp = strcmp(pszNamespace, c_rgECClasses[mid].m_szNameSpace);
if (cmp == 0) {
return(mid);
}
if (cmp > 0)
low = mid+1;
else
high = mid;
}
return (-1);
}
/*******************************************************************************/
/* Finds the implementation for the given method desc. */
static INT FindECIndexForMethod(MethodDesc *pMD, const LPVOID* impls)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
LPCUTF8 szMethodName = pMD->GetName();
PCCOR_SIGNATURE pMethodSig;
ULONG cbMethodSigLen;
pMD->GetSig(&pMethodSig, &cbMethodSigLen);
Module* pModule = pMD->GetModule();
for (ECFunc* cur = (ECFunc*)impls; !cur->IsEndOfArray(); cur = cur->NextInArray())
{
if (strcmp(cur->m_szMethodName, szMethodName) != 0)
continue;
if (cur->HasSignature())
{
Signature sig = MscorlibBinder::GetTargetSignature(cur->m_pMethodSig);
//@GENERICS: none of these methods belong to generic classes so there is no instantiation info to pass in
if (!MetaSig::CompareMethodSigs(pMethodSig, cbMethodSigLen, pModule, NULL,
sig.GetRawSig(), sig.GetRawSigLen(), MscorlibBinder::GetModule(), NULL))
{
continue;
}
}
// We have found a match!
return static_cast<INT>((LPVOID*)cur - impls);
}
return -1;
}
/*******************************************************************************/
/* ID is formed of 2 USHORTs - class index in high word, method index in low word. */
/* class index starts at 1. id == 0 means no implementation. */
DWORD ECall::GetIDForMethod(MethodDesc *pMD)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
// We should not go here for NGened methods
_ASSERTE(!pMD->IsZapped());
INT ImplsIndex = FindImplsIndexForClass(pMD->GetMethodTable());
if (ImplsIndex < 0)
return 0;
INT ECIndex = FindECIndexForMethod(pMD, c_rgECClasses[ImplsIndex].m_pECFunc);
if (ECIndex < 0)
return 0;
return (ImplsIndex<<16) | (ECIndex + 1);
}
static ECFunc *FindECFuncForID(DWORD id)
{
LIMITED_METHOD_CONTRACT;
if (id == 0)
return NULL;
INT ImplsIndex = (id >> 16);
INT ECIndex = (id & 0xffff) - 1;
return (ECFunc*)(c_rgECClasses[ImplsIndex].m_pECFunc + ECIndex);
}
static ECFunc* FindECFuncForMethod(MethodDesc* pMD)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(pMD->IsFCall());
}
CONTRACTL_END;
DWORD id = ((FCallMethodDesc *)pMD)->GetECallID();
if (id == 0)
{
id = ECall::GetIDForMethod(pMD);
CONSISTENCY_CHECK_MSGF(0 != id,
("No method entry found for %s::%s.\n",
pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName));
// Cache the id
((FCallMethodDesc *)pMD)->SetECallID(id);
}
return FindECFuncForID(id);
}
/*******************************************************************************
* Returns 0 if it is an ECALL,
* Otherwise returns the native entry point (FCALL)
*/
PCODE ECall::GetFCallImpl(MethodDesc * pMD, BOOL * pfSharedOrDynamicFCallImpl /*=NULL*/)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(pMD->IsFCall());
}
CONTRACTL_END;
MethodTable * pMT = pMD->GetMethodTable();
//
// Delegate constructors are FCalls for which the entrypoint points to the target of the delegate
// We have to intercept these and set the call target to the helper COMDelegate::DelegateConstruct
//
if (pMT->IsDelegate())
{
if (pfSharedOrDynamicFCallImpl)
*pfSharedOrDynamicFCallImpl = TRUE;
// COMDelegate::DelegateConstruct is the only fcall used by user delegates.
// All the other gDelegateFuncs are only used by System.Delegate
_ASSERTE(pMD->IsCtor());
// We need to set up the ECFunc properly. We don't want to use the pMD passed in,
// since it may disappear. Instead, use the stable one on Delegate. Remember
// that this is 1:M between the FCall and the pMDs.
return GetFCallImpl(MscorlibBinder::GetMethod(METHOD__DELEGATE__CONSTRUCT_DELEGATE));
}
// COM imported classes have special constructors
if (pMT->IsComObjectType()
#ifdef FEATURE_COMINTEROP
&& pMT != g_pBaseCOMObject && pMT != g_pBaseRuntimeClass
#endif // FEATURE_COMINTEROP
)
{
#ifdef FEATURE_COMINTEROP
if (pfSharedOrDynamicFCallImpl)
*pfSharedOrDynamicFCallImpl = TRUE;
// This has to be tlbimp constructor
_ASSERTE(pMD->IsCtor());
_ASSERTE(!pMT->IsProjectedFromWinRT());
// FCComCtor does not need to be in the fcall hashtable since it does not erect frame.
return GetEEFuncEntryPoint(FCComCtor);
#else
COMPlusThrow(kPlatformNotSupportedException, IDS_EE_ERROR_COM);
#endif // FEATURE_COMINTEROP
}
if (!pMD->GetModule()->IsSystem())
COMPlusThrow(kSecurityException, BFA_ECALLS_MUST_BE_IN_SYS_MOD);
ECFunc* ret = FindECFuncForMethod(pMD);
// ECall is a set of tables to call functions within the EE from the classlibs.
// First we use the class name & namespace to find an array of function pointers for
// a class, then use the function name (& sometimes signature) to find the correct
// function pointer for your method. Methods in the BCL will be marked as
// [MethodImplAttribute(MethodImplOptions.InternalCall)] and extern.
//
// You'll see this assert in several situations, almost all being the fault of whomever
// last touched a particular ecall or fcall method, either here or in the classlibs.
// However, you must also ensure you don't have stray copies of mscorlib.dll on your machine.
// 1) You forgot to add your class to c_rgECClasses, the list of classes w/ ecall & fcall methods.
// 2) You forgot to add your particular method to the ECFunc array for your class.
// 3) You misspelled the name of your function and/or classname.
// 4) The signature of the managed function doesn't match the hardcoded metadata signature
// listed in your ECFunc array. The hardcoded metadata sig is only necessary to disambiguate
// overloaded ecall functions - usually you can leave it set to NULL.
// 5) Your copy of mscorlib.dll & mscoree.dll are out of sync - rebuild both.
// 6) You've loaded the wrong copy of mscorlib.dll. In msdev's debug menu,
// select the "Modules..." dialog. Verify the path for mscorlib is right.
// 7) Someone mucked around with how the signatures in metasig.h are parsed, changing the
// interpretation of a part of the signature (this is very rare & extremely unlikely,
// but has happened at least once).
CONSISTENCY_CHECK_MSGF(ret != NULL,
("Could not find an ECALL entry for %s::%s.\n"
"Read comment above this assert in vm/ecall.cpp\n",
pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName));
CONSISTENCY_CHECK_MSGF(!ret->IsQCall(),
("%s::%s is not registered using FCFuncElement macro in ecall.cpp",
pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName));
#ifdef CROSSGEN_COMPILE
// Use the ECFunc address as a unique fake entrypoint to make the entrypoint<->MethodDesc mapping work
PCODE pImplementation = (PCODE)ret;
#ifdef _TARGET_ARM_
pImplementation |= THUMB_CODE;
#endif
#else // CROSSGEN_COMPILE
PCODE pImplementation = (PCODE)ret->m_pImplementation;
int iDynamicID = ret->DynamicID();
if (iDynamicID != InvalidDynamicFCallId)
{
if (pfSharedOrDynamicFCallImpl)
*pfSharedOrDynamicFCallImpl = TRUE;
pImplementation = g_FCDynamicallyAssignedImplementations[iDynamicID];
_ASSERTE(pImplementation != NULL);
return pImplementation;
}
#endif // CROSSGEN_COMPILE
// Insert the implementation into hash table if it is not there already.
CrstHolder holder(&gFCallLock);
MethodDesc * pMDinTable = ECall::MapTargetBackToMethod(pImplementation, &pImplementation);
if (pMDinTable != NULL)
{
if (pMDinTable != pMD)
{
// The fcall entrypoints has to be at unique addresses. If you get failure here, use the following steps
// to fix it:
// 1. Consider merging the offending fcalls into one fcall. Do they really do different things?
// 2. If it does not make sense to merge the offending fcalls into one,
// add FCUnique(<a random unique number here>); to one of the offending fcalls.
_ASSERTE(!"Duplicate pImplementation entries found in reverse fcall table");
ThrowHR(E_FAIL);
}
}
else
{
ECHash * pEntry = (ECHash *)(PVOID)SystemDomain::GetGlobalLoaderAllocator()->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(ECHash)));
pEntry->m_pImplementation = pImplementation;
pEntry->m_pMD = pMD;
if(gLowestFCall > pImplementation)
gLowestFCall = pImplementation;
if(gHighestFCall < pImplementation)
gHighestFCall = pImplementation;
// add to hash table
ECHash** spot = &gFCallMethods[FCallHash(pImplementation)];
for(;;) {
if (*spot == 0) { // found end of list
*spot = pEntry;
break;
}
spot = &(*spot)->m_pNext;
}
}
if (pfSharedOrDynamicFCallImpl)
*pfSharedOrDynamicFCallImpl = FALSE;
_ASSERTE(pImplementation != NULL);
return pImplementation;
}
BOOL ECall::IsSharedFCallImpl(PCODE pImpl)
{
LIMITED_METHOD_CONTRACT;
PCODE pNativeCode = pImpl;
return
#ifdef FEATURE_COMINTEROP
(pNativeCode == GetEEFuncEntryPoint(FCComCtor)) ||
#endif
(pNativeCode == GetEEFuncEntryPoint(COMDelegate::DelegateConstruct));
}
BOOL ECall::CheckUnusedECalls(SetSHash<DWORD>& usedIDs)
{
STANDARD_VM_CONTRACT;
BOOL fUnusedFCallsFound = FALSE;
INT num = c_nECClasses;
for (INT ImplsIndex=0; ImplsIndex < num; ImplsIndex++)
{
const ECClass * pECClass = c_rgECClasses + ImplsIndex;
BOOL fUnreferencedType = TRUE;
for (ECFunc* ptr = (ECFunc*)pECClass->m_pECFunc; !ptr->IsEndOfArray(); ptr = ptr->NextInArray())
{
if (ptr->DynamicID() == InvalidDynamicFCallId && !ptr->IsUnreferenced())
{
INT ECIndex = static_cast<INT>((LPVOID*)ptr - pECClass->m_pECFunc);
DWORD id = (ImplsIndex<<16) | (ECIndex + 1);
if (!usedIDs.Contains(id))
{
printf("CheckMscorlibExtended: Unused ecall found: %s.%s::%s\n", pECClass->m_szNameSpace, c_rgECClasses[ImplsIndex].m_szClassName, ptr->m_szMethodName);
fUnusedFCallsFound = TRUE;
continue;
}
}
fUnreferencedType = FALSE;
}
if (fUnreferencedType)
{
printf("CheckMscorlibExtended: Unused type found: %s.%s\n", c_rgECClasses[ImplsIndex].m_szNameSpace, c_rgECClasses[ImplsIndex].m_szClassName);
fUnusedFCallsFound = TRUE;
continue;
}
}
return !fUnusedFCallsFound;
}
#if defined(FEATURE_COMINTEROP) && !defined(CROSSGEN_COMPILE)
FCIMPL1(VOID, FCComCtor, LPVOID pV)
{
FCALL_CONTRACT;
FCUnique(0x34);
}
FCIMPLEND
#endif // FEATURE_COMINTEROP && !CROSSGEN_COMPILE
/* static */
void ECall::Init()
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
gFCallLock.Init(CrstFCall);
// It is important to do an explicit increment here instead of just in-place initialization
// so that the global optimizer cannot figure out the value and remove the side-effect that
// we depend on in FC_INNER_RETURN macros and other places
FC_NO_TAILCALL++;
}
LPVOID ECall::GetQCallImpl(MethodDesc * pMD)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(pMD->IsNDirect());
}
CONTRACTL_END;
DWORD id = ((NDirectMethodDesc *)pMD)->GetECallID();
if (id == 0)
{
id = ECall::GetIDForMethod(pMD);
_ASSERTE(id != 0);
// Cache the id
((NDirectMethodDesc *)pMD)->SetECallID(id);
}
ECFunc * cur = FindECFuncForID(id);
#ifdef _DEBUG
CONSISTENCY_CHECK_MSGF(cur != NULL,
("%s::%s is not registered in ecall.cpp",
pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName));
CONSISTENCY_CHECK_MSGF(cur->IsQCall(),
("%s::%s is not registered using QCFuncElement macro in ecall.cpp",
pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName));
DWORD dwAttrs = pMD->GetAttrs();
BOOL fPublicOrProtected = IsMdPublic(dwAttrs) || IsMdFamily(dwAttrs) || IsMdFamORAssem(dwAttrs);
// SuppressUnmanagedCodeSecurityAttribute on QCalls suppresses a full demand, but there's still a link demand
// for unmanaged code permission. All QCalls should be private or internal and wrapped in a managed method
// to suppress this link demand.
CONSISTENCY_CHECK_MSGF(!fPublicOrProtected,
("%s::%s has to be private or internal.",
pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName));
#endif
return cur->m_pImplementation;
}
#endif // !DACCESS_COMPILE
MethodDesc* ECall::MapTargetBackToMethod(PCODE pTarg, PCODE * ppAdjustedEntryPoint /*=NULL*/)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
HOST_NOCALLS;
SUPPORTS_DAC;
}
CONTRACTL_END;
// Searching all of the entries is expensive
// and we are often called with pTarg == NULL so
// check for this value and early exit.
if (!pTarg)
return NULL;
// Could this possibily be an FCall?
if ((pTarg < gLowestFCall) || (pTarg > gHighestFCall))
return NULL;
ECHash * pECHash = gFCallMethods[FCallHash(pTarg)];
while (pECHash != NULL)
{
if (pECHash->m_pImplementation == pTarg)
{
return pECHash->m_pMD;
}
pECHash = pECHash->m_pNext;
}
return NULL;
}
#ifndef DACCESS_COMPILE
/* static */
CorInfoIntrinsics ECall::GetIntrinsicID(MethodDesc* pMD)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(pMD->IsFCall());
}
CONTRACTL_END;
MethodTable * pMT = pMD->GetMethodTable();
#ifdef FEATURE_COMINTEROP
// COM imported classes have special constructors
if (pMT->IsComObjectType())
{
// This has to be tlbimp constructor
return(CORINFO_INTRINSIC_Illegal);
}
#endif // FEATURE_COMINTEROP
//
// Delegate constructors are FCalls for which the entrypoint points to the target of the delegate
// We have to intercept these and set the call target to the helper COMDelegate::DelegateConstruct
//
if (pMT->IsDelegate())
{
// COMDelegate::DelegateConstruct is the only fcall used by user delegates.
// All the other gDelegateFuncs are only used by System.Delegate
_ASSERTE(pMD->IsCtor());
return(CORINFO_INTRINSIC_Illegal);
}
// All intrinsic live in mscorlib.dll (FindECFuncForMethod does not work for non-mscorlib intrinsics)
if (!pMD->GetModule()->IsSystem())
{
return(CORINFO_INTRINSIC_Illegal);
}
ECFunc* info = FindECFuncForMethod(pMD);
if (info == NULL)
return(CORINFO_INTRINSIC_Illegal);
return info->IntrinsicID();
}
#ifdef _DEBUG
void FCallAssert(void*& cache, void* target)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_DEBUG_ONLY;
if (cache != 0)
{
return;
}
//
// Special case fcalls with 1:N mapping between implementation and methoddesc
//
if (ECall::IsSharedFCallImpl((PCODE)target))
{
cache = (void*)1;
return;
}
MethodDesc* pMD = ECall::MapTargetBackToMethod((PCODE)target);
if (pMD != 0)
{
return;
}
// Slow but only for debugging. This is needed because in some places
// we call FCALLs directly from EE code.
unsigned num = c_nECClasses;
for (unsigned i=0; i < num; i++)
{
for (ECFunc* ptr = (ECFunc*)c_rgECClasses[i].m_pECFunc; !ptr->IsEndOfArray(); ptr = ptr->NextInArray())
{
if (ptr->m_pImplementation == target)
{
cache = target;
return;
}
}
}
// Now check the dynamically assigned table too.
for (unsigned i=0; i<ECall::NUM_DYNAMICALLY_ASSIGNED_FCALL_IMPLEMENTATIONS; i++)
{
if (g_FCDynamicallyAssignedImplementations[i] == (PCODE)target)
{
cache = target;
return;
}
}
_ASSERTE(!"Could not find FCall implemenation in ECall.cpp");
}
void HCallAssert(void*& cache, void* target)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
DEBUG_ONLY;
}
CONTRACTL_END;
if (cache != 0)
cache = ECall::MapTargetBackToMethod((PCODE)target);
_ASSERTE(cache == 0 || "Use FCIMPL for fcalls");
}
#endif // _DEBUG
#endif // !DACCESS_COMPILE
#ifdef DACCESS_COMPILE
void ECall::EnumFCallMethods()
{
SUPPORTS_DAC;
gLowestFCall.EnumMem();
gHighestFCall.EnumMem();
gFCallMethods.EnumMem();
// save all ECFunc for stackwalks.
// TODO: we could be smarter and only save buckets referenced during stackwalks. But we
// need that entire bucket so that traversals such as MethodDesc* ECall::MapTargetBackToMethod will work.
for (UINT i=0;i<FCALL_HASH_SIZE;i++)
{
ECHash *ecHash = gFCallMethods[i];
while (ecHash)
{
// If we can't read the target memory, stop immediately so we don't work
// with broken data.
if (!DacEnumMemoryRegion(dac_cast<TADDR>(ecHash), sizeof(ECHash)))
break;
ecHash = ecHash->m_pNext;
#if defined (_DEBUG)
// Test hook: when testing on debug builds, we want an easy way to test that the while
// correctly terminates in the face of ridiculous stuff from the target.
if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DumpGeneration_IntentionallyCorruptDataFromTarget) == 1)
{
// Force us to struggle on with something bad.
if (!ecHash)
{
ecHash = (ECHash *)(((unsigned char *)&gFCallMethods[i])+1);
}
}
#endif // defined (_DEBUG)
}
}
}
#endif // DACCESS_COMPILE
| {'content_hash': '83c6808314f2956f75e420e9bbd1b510', 'timestamp': '', 'source': 'github', 'line_count': 862, 'max_line_length': 172, 'avg_line_length': 33.05104408352668, 'alnum_prop': 0.6499122499122499, 'repo_name': 'wtgodbe/coreclr', 'id': 'dfeff95d6f9293f53611e2b3c53598a0b7314bce', 'size': '28490', 'binary': False, 'copies': '31', 'ref': 'refs/heads/master', 'path': 'src/vm/ecall.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '976648'}, {'name': 'Awk', 'bytes': '6904'}, {'name': 'Batchfile', 'bytes': '167893'}, {'name': 'C', 'bytes': '4862319'}, {'name': 'C#', 'bytes': '154822068'}, {'name': 'C++', 'bytes': '64306017'}, {'name': 'CMake', 'bytes': '723128'}, {'name': 'M4', 'bytes': '15214'}, {'name': 'Makefile', 'bytes': '46117'}, {'name': 'Objective-C', 'bytes': '14116'}, {'name': 'Perl', 'bytes': '23653'}, {'name': 'PowerShell', 'bytes': '132755'}, {'name': 'Python', 'bytes': '480080'}, {'name': 'Roff', 'bytes': '672227'}, {'name': 'Scala', 'bytes': '4102'}, {'name': 'Shell', 'bytes': '513230'}, {'name': 'Smalltalk', 'bytes': '635930'}, {'name': 'SuperCollider', 'bytes': '650'}, {'name': 'TeX', 'bytes': '126781'}, {'name': 'XSLT', 'bytes': '1016'}, {'name': 'Yacc', 'bytes': '157492'}]} |
package com.ctrip.framework.apollo.metaservice.controller;
import com.ctrip.framework.apollo.core.ServiceNameConsts;
import com.ctrip.framework.apollo.core.dto.ServiceDTO;
import com.ctrip.framework.apollo.metaservice.service.DiscoveryService;
import com.google.common.collect.Lists;
import java.util.List;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* For non-eureka discovery services such as kubernetes and nacos, there is no eureka home page, so we need to add a default one
*/
@Profile({"kubernetes", "nacos-discovery", "consul-discovery"})
@RestController
public class HomePageController {
private final DiscoveryService discoveryService;
public HomePageController(DiscoveryService discoveryService) {
this.discoveryService = discoveryService;
}
@GetMapping("/")
public List<ServiceDTO> listAllServices() {
List<ServiceDTO> allServices = Lists.newLinkedList();
allServices
.addAll(discoveryService.getServiceInstances(ServiceNameConsts.APOLLO_CONFIGSERVICE));
allServices.addAll(discoveryService.getServiceInstances(ServiceNameConsts.APOLLO_ADMINSERVICE));
return allServices;
}
}
| {'content_hash': 'b8e9bf546e422f0650d3bc2c2f2ca45e', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 128, 'avg_line_length': 36.371428571428574, 'alnum_prop': 0.8012568735271013, 'repo_name': 'yiming187/apollo', 'id': 'b7591884599f6ff2252e60fbfee0b753863496ae', 'size': '1869', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'apollo-configservice/src/main/java/com/ctrip/framework/apollo/metaservice/controller/HomePageController.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2286'}, {'name': 'CSS', 'bytes': '13275'}, {'name': 'Dockerfile', 'bytes': '11985'}, {'name': 'HTML', 'bytes': '395972'}, {'name': 'Java', 'bytes': '3024697'}, {'name': 'JavaScript', 'bytes': '337509'}, {'name': 'Mustache', 'bytes': '4897'}, {'name': 'Shell', 'bytes': '38649'}]} |
using System;
using Zirpl.AppEngine.Service;
using Zirpl.Examples.CodeGeneration.VS2013.Commerce.Model.Subscriptions;
namespace Zirpl.Examples.CodeGeneration.VS2013.Commerce.Service.Subscriptions
{
public partial interface IPendingSubscriptionChangeService : ICompleteService<PendingSubscriptionChange, int>
{
}
}
| {'content_hash': '0ec11ed4a201f669c420df5d530aa305', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 114, 'avg_line_length': 32.9, 'alnum_prop': 0.8206686930091185, 'repo_name': 'zirplsoftware/ZAppEngine', 'id': '568528dfe08739a5fe0950466bf428acc07398ad', 'size': '331', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Zirpl.Examples.CodeGeneration.VS2013.Commerce.Service/_auto/Subscriptions/IPendingSubscriptionChangeService.auto.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '2908246'}, {'name': 'Shell', 'bytes': '1826'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mathcomp-solvable: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.7.1+2 / mathcomp-solvable - 1.12.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
mathcomp-solvable
<small>
1.12.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-21 01:45:33 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-21 01:45:33 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.7.1+2 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.06.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.06.1 Official 4.06.1 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Mathematical Components <[email protected]>"
homepage: "https://math-comp.github.io/"
bug-reports: "https://github.com/math-comp/math-comp/issues"
dev-repo: "git+https://github.com/math-comp/math-comp.git"
license: "CECILL-B"
build: [ make "-C" "mathcomp/solvable" "-j" "%{jobs}%" "COQEXTRAFLAGS+=-native-compiler yes" {coq-native:installed & coq:version < "8.13~" } ]
install: [ make "-C" "mathcomp/solvable" "install" ]
depends: [ "coq-mathcomp-algebra" { = version } ]
tags: [ "keyword:finite groups" "keyword:Feit Thompson theorem" "keyword:small scale reflection" "keyword:mathematical components" "keyword:odd order theorem" "logpath:mathcomp.solvable" ]
authors: [ "Jeremy Avigad <>" "Andrea Asperti <>" "Stephane Le Roux <>" "Yves Bertot <>" "Laurence Rideau <>" "Enrico Tassi <>" "Ioana Pasca <>" "Georges Gonthier <>" "Sidi Ould Biha <>" "Cyril Cohen <>" "Francois Garillot <>" "Alexey Solovyev <>" "Russell O'Connor <>" "Laurent Théry <>" "Assia Mahboubi <>" ]
synopsis: "Mathematical Components Library on finite groups (II)"
description:"""
This library contains more definitions and theorems about finite groups.
"""
url {
src: "https://github.com/math-comp/math-comp/archive/mathcomp-1.12.0.tar.gz"
checksum: "sha256=a57b79a280e7e8527bf0d8710c1f65cde00032746b52b87be1ab12e6213c9783"
}
</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-mathcomp-solvable.1.12.0 coq.8.7.1+2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1+2).
The following dependencies couldn't be met:
- coq-mathcomp-solvable -> coq-mathcomp-algebra = 1.12.0 -> coq-mathcomp-fingroup = 1.12.0 -> coq-mathcomp-ssreflect = 1.12.0 -> coq >= 8.10 -> ocaml >= 4.09.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-mathcomp-solvable.1.12.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': '1be07ee230af006deeb95858d4b1d192', 'timestamp': '', 'source': 'github', 'line_count': 161, 'max_line_length': 554, 'avg_line_length': 48.52795031055901, 'alnum_prop': 0.5643158837834379, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': '83525bcc34d08ed90457cf315fac72dccedb4ac6', 'size': '7839', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.06.1-2.0.5/released/8.7.1+2/mathcomp-solvable/1.12.0.html', 'mode': '33188', 'license': 'mit', 'language': []} |
package org.springframework.boot.actuate.autoconfigure.metrics.web.tomcat;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.tomcat.TomcatMetrics;
import org.apache.catalina.Manager;
import org.springframework.boot.actuate.autoconfigure.metrics.CompositeMeterRegistryAutoConfiguration;
import org.springframework.boot.actuate.metrics.web.tomcat.TomcatMetricsBinder;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* {@link EnableAutoConfiguration Auto-configuration} for {@link TomcatMetrics}.
*
* @author Andy Wilkinson
* @since 2.0.0
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication
@ConditionalOnClass({ TomcatMetrics.class, Manager.class })
@AutoConfigureAfter(CompositeMeterRegistryAutoConfiguration.class)
public class TomcatMetricsAutoConfiguration {
@Bean
@ConditionalOnBean(MeterRegistry.class)
@ConditionalOnMissingBean({ TomcatMetrics.class, TomcatMetricsBinder.class })
public TomcatMetricsBinder tomcatMetricsBinder(MeterRegistry meterRegistry) {
return new TomcatMetricsBinder(meterRegistry);
}
}
| {'content_hash': '38c69d62ec0e4ed94f2c46be30ceff04', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 102, 'avg_line_length': 41.64102564102564, 'alnum_prop': 0.854679802955665, 'repo_name': 'jxblum/spring-boot', 'id': 'e3d17f6ee7922c20993803de846d8eac9149998d', 'size': '2245', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfiguration.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2141'}, {'name': 'CSS', 'bytes': '450'}, {'name': 'Dockerfile', 'bytes': '2231'}, {'name': 'Groovy', 'bytes': '26659'}, {'name': 'HTML', 'bytes': '70165'}, {'name': 'Java', 'bytes': '19425145'}, {'name': 'JavaScript', 'bytes': '37722'}, {'name': 'Kotlin', 'bytes': '61130'}, {'name': 'Mustache', 'bytes': '449'}, {'name': 'Ruby', 'bytes': '7744'}, {'name': 'Shell', 'bytes': '42147'}, {'name': 'Smarty', 'bytes': '2882'}, {'name': 'Vim Snippet', 'bytes': '135'}]} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Duality;
using Duality.Editor;
using Duality.Resources;
using Duality.Components;
using Duality.Components.Physics;
using Duality.Components.Renderers;
namespace DualStickSpaceShooter
{
public class ShipBlueprint : Resource
{
private float thrusterPower = 0.0f;
private float turnPower = 0.0f;
private float healRate = 0.0f;
private float maxHitpoints = 100.0f;
private float maxSpeed = 0.0f;
private float maxTurnSpeed = 0.0f;
private ContentRef<Prefab> damageEffect = null;
private ContentRef<Prefab>[] deathEffects = null;
private ContentRef<BulletBlueprint> bulletType = null;
private float weaponDelay = 0.0f;
public float ThrusterPower
{
get { return this.thrusterPower; }
set { this.thrusterPower = value; }
}
public float TurnPower
{
get { return this.turnPower; }
set { this.turnPower = value; }
}
[EditorHintDecimalPlaces(0)]
public float HealRate
{
get { return this.healRate; }
set { this.healRate = value; }
}
[EditorHintDecimalPlaces(0)]
public float MaxHitpoints
{
get { return this.maxHitpoints; }
set { this.maxHitpoints = value; }
}
public float MaxSpeed
{
get { return this.maxSpeed; }
set { this.maxSpeed = value; }
}
public float MaxTurnSpeed
{
get { return this.maxTurnSpeed; }
set { this.maxTurnSpeed = value; }
}
public ContentRef<Prefab> DamageEffect
{
get { return this.damageEffect; }
set { this.damageEffect = value; }
}
public ContentRef<Prefab>[] DeathEffects
{
get { return this.deathEffects; }
set { this.deathEffects = value; }
}
public ContentRef<BulletBlueprint> BulletType
{
get { return this.bulletType; }
set { this.bulletType = value; }
}
public float WeaponDelay
{
get { return this.weaponDelay; }
set { this.weaponDelay = value; }
}
}
}
| {'content_hash': 'd6c1a4db30e95f1abff60839c5904133', 'timestamp': '', 'source': 'github', 'line_count': 82, 'max_line_length': 59, 'avg_line_length': 24.23170731707317, 'alnum_prop': 0.6743834927025667, 'repo_name': 'cpascal/duality', 'id': '6782acbcabaad40aa60e89e39314655e04a8ff17', 'size': '1989', 'binary': False, 'copies': '14', 'ref': 'refs/heads/master', 'path': 'SampleProjects/DualStickSpaceShooter/Blueprints/ShipBlueprint.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '333'}, {'name': 'C#', 'bytes': '3565511'}, {'name': 'GLSL', 'bytes': '1775'}]} |
__Description__: The user should be able to be define `state` options within the root of the `state` object through the `option` object
__Notes__
+ Alias: `common`, `global`, and `option` | {'content_hash': 'a8385d6580962f503528259fb46913b1', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 135, 'avg_line_length': 37.8, 'alnum_prop': 0.708994708994709, 'repo_name': 'ctr-lang/ctr', 'id': 'b4b968e1bf7ce97f8a25ff74127a4918479687f9', 'size': '189', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '__tests__/cases-core/state/option/specific/misc/option-object.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '2147929'}, {'name': 'JavaScript', 'bytes': '722012'}]} |
import Helper from '@ember/component/helper';
import { get } from '@ember/object';
import { inject as service } from '@ember/service';
export default Helper.extend({
markdownResolver: service(),
compute([tree, file]) {
let md = get(this, 'markdownResolver')._file(tree, file);
return get(md, 'content');
}
});
| {'content_hash': '7bdd16384f1b719980579abee83b1390', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 61, 'avg_line_length': 23.428571428571427, 'alnum_prop': 0.6646341463414634, 'repo_name': 'willviles/ember-cli-markdown-resolver', 'id': 'fd037939960ab320b459c9ab1414b3ff716c0879', 'size': '328', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'addon/helpers/get-markdown-content.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '20'}, {'name': 'HTML', 'bytes': '1934'}, {'name': 'JavaScript', 'bytes': '11243'}]} |
package com.mlavrik.weatherapp.views;
import com.mlavrik.weatherapp.models.Day;
public interface WeatherCityView {
void renderCityWeather(Day day);
void onNetworkError();
void cityNotFoundError();
}
| {'content_hash': 'ebca5b5cb7bbc3920258060dd1705860', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 41, 'avg_line_length': 16.692307692307693, 'alnum_prop': 0.7511520737327189, 'repo_name': 'mshq37/WeatherApp', 'id': '819d33496619207d70aad640299ea75d50488048', 'size': '217', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/java/com/mlavrik/weatherapp/views/WeatherCityView.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '110014'}]} |
package org.springframework.data.hazelcast.repository;
import org.junit.Test;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.test.context.ActiveProfiles;
import test.utils.TestData;
import test.utils.TestConstants;
import test.utils.TestDataHelper;
import test.utils.domain.Person;
import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
* <p>
* Downcast a {@link HazelcastRepository} into a {@link PagingAndSortingRepository} to test paging and sorting
* additions.
* </P>
* <p>
* Where possible, verify the repository against the underlying Hazelcast instance directly.
* </P>
*
* @author Neil Stevenson
*/
@ActiveProfiles(TestConstants.SPRING_TEST_PROFILE_CLIENT_SERVER)
public class PagingSortingIT
extends TestDataHelper {
// PersonRepository is really a HazelcastRepository
@Resource
private PagingAndSortingRepository<Person, String> personRepository;
// If no paging provided, everything is returned on a single page
@Test
public void unpaged() {
Page<Person> page = this.personRepository.findAll(Pageable.unpaged());
assertThat("Page returned for null input", page, notNullValue());
List<Person> content = page.getContent();
assertThat("First page is returned", page.getNumber(), equalTo(0));
assertThat("First page count matches content", page.getNumberOfElements(), equalTo(content.size()));
assertThat("First page has all content", (long) page.getNumberOfElements(), equalTo(page.getTotalElements()));
assertThat("First page has correct content count", page.getNumberOfElements(), equalTo(TestData.bestActors.length));
assertThat("First page is only page", page.getTotalPages(), equalTo(1));
}
@Test
public void paging() {
int PAGE_0 = 0;
int PAGE_2 = 2;
int SIZE_5 = 5;
int SIZE_20 = 20;
PageRequest thirdPageOf5Request = PageRequest.of(PAGE_2, SIZE_5);
Page<Person> thirdPageOf5Response = this.personRepository.findAll(thirdPageOf5Request);
assertThat("11 onwards returned", thirdPageOf5Response, notNullValue());
List<Person> thirdPageOf5Content = thirdPageOf5Response.getContent();
assertThat("11-15 returned", thirdPageOf5Content.size(), equalTo(5));
Pageable fourthPageOf5Request = thirdPageOf5Response.nextPageable();
Page<Person> fourthPageOf5Response = this.personRepository.findAll(fourthPageOf5Request);
assertThat("16 onwards returned", fourthPageOf5Response, notNullValue());
List<Person> fourthPageOf5Content = fourthPageOf5Response.getContent();
assertThat("16-20 returned", fourthPageOf5Content.size(), equalTo(5));
PageRequest firstPageOf20Request = PageRequest.of(PAGE_0, SIZE_20);
Page<Person> firstPageOf20Response = this.personRepository.findAll(firstPageOf20Request);
assertThat("1 onwards returned", firstPageOf20Response, notNullValue());
List<Person> firstPageOf20Content = firstPageOf20Response.getContent();
assertThat("1-20 returned", firstPageOf20Content.size(), equalTo(20));
assertThat("11th", thirdPageOf5Content.get(0), equalTo(firstPageOf20Content.get(10)));
assertThat("12th", thirdPageOf5Content.get(1), equalTo(firstPageOf20Content.get(11)));
assertThat("13th", thirdPageOf5Content.get(2), equalTo(firstPageOf20Content.get(12)));
assertThat("14th", thirdPageOf5Content.get(3), equalTo(firstPageOf20Content.get(13)));
assertThat("15th", thirdPageOf5Content.get(4), equalTo(firstPageOf20Content.get(14)));
assertThat("16th", fourthPageOf5Content.get(0), equalTo(firstPageOf20Content.get(15)));
assertThat("17th", fourthPageOf5Content.get(1), equalTo(firstPageOf20Content.get(16)));
assertThat("18th", fourthPageOf5Content.get(2), equalTo(firstPageOf20Content.get(17)));
assertThat("19th", fourthPageOf5Content.get(3), equalTo(firstPageOf20Content.get(18)));
assertThat("20th", fourthPageOf5Content.get(4), equalTo(firstPageOf20Content.get(19)));
Set<String> ids = new TreeSet<>();
firstPageOf20Content.forEach(person -> ids.add(person.getId()));
assertThat("20 different years", ids.size(), equalTo(20));
}
@Test
public void unsorted() {
Iterable<Person> iterable = this.personRepository.findAll(Sort.unsorted());
assertThat("Results returned", iterable, notNullValue());
Iterator<Person> iterator = iterable.iterator();
int count = 0;
while (iterator.hasNext()) {
count++;
iterator.next();
}
assertThat("Correct number, order undefined", count, equalTo(TestData.bestActors.length));
}
@Test
public void sorting() {
Sort sortAscending = Sort.by(Sort.Direction.ASC, "firstname");
Sort sortDescending = Sort.by(Sort.Direction.DESC, "firstname");
Iterable<Person> iterableAscending = this.personRepository.findAll(sortAscending);
Iterable<Person> iterableDescending = this.personRepository.findAll(sortDescending);
assertThat("Results returned ascending", iterableAscending, notNullValue());
assertThat("Results returned descending", iterableDescending, notNullValue());
Iterator<Person> iteratorAscending = iterableAscending.iterator();
Iterator<Person> iteratorDescending = iterableDescending.iterator();
assertThat("Not empty returned ascending", iteratorAscending.hasNext(), is(true));
assertThat("Not empty returned descending", iteratorDescending.hasNext(), is(true));
String previousFirstname = "";
int count = 0;
while (iteratorAscending.hasNext()) {
Person person = iteratorAscending.next();
assertThat("Firstname " + count + " ascending", person.getFirstname(), greaterThanOrEqualTo(previousFirstname));
count++;
previousFirstname = person.getFirstname();
}
assertThat("Everything found ascending", count, equalTo(TestData.bestActors.length));
assertThat("1956 winner, last firstname ascending", previousFirstname, equalTo("Yul"));
while (iteratorDescending.hasNext()) {
Person person = iteratorDescending.next();
assertThat("Firstname " + count + " descending", person.getFirstname(), lessThanOrEqualTo(previousFirstname));
count--;
previousFirstname = person.getFirstname();
}
assertThat("Everything found decending", count, equalTo(0));
assertThat("2002 winner, last firstname descending", previousFirstname, equalTo("Adrien"));
}
}
| {'content_hash': '7508dc97af8a853448da077aaed03f5b', 'timestamp': '', 'source': 'github', 'line_count': 165, 'max_line_length': 124, 'avg_line_length': 44.09090909090909, 'alnum_prop': 0.7109278350515464, 'repo_name': 'hazelcast/spring-data-hazelcast', 'id': 'be02d37041051c214c3f764203254c54f9646d1a', 'size': '7900', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/java/org/springframework/data/hazelcast/repository/PagingSortingIT.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '311086'}]} |
function Welcome() {
this.ready = true;
}
module.exports = Welcome; | {'content_hash': '3f9e2787a2c3f51bdfee451fdd1a66ed', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 25, 'avg_line_length': 14.4, 'alnum_prop': 0.6666666666666666, 'repo_name': 'linclark/algorithms-101', 'id': 'f59833f71d8dfa30964543461e544517a4e9ae1a', 'size': '72', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'exercises/welcome/solution/solution.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'JavaScript', 'bytes': '8483'}]} |
package com.ximalaya.ratel.common
/**
* Created by think on 2017/7/22.
*/
case class RpcResponse(id:Long, result:Either[Throwable,(String,Any)])
| {'content_hash': '841f7056be84e0799e61f0c0dfdc496b', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 70, 'avg_line_length': 25.0, 'alnum_prop': 0.72, 'repo_name': 'dongjiaqiang/Ratel', 'id': '03248d8aaa38a33ac9a15aafd85d30b88f9ae78d', 'size': '150', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ratel-rpc/src/main/scala/com/ximalaya/ratel/common/RpcResponse.scala', 'mode': '33188', 'license': 'mit', 'language': []} |
<?php
/* SonataSeoBundle:Block:block_twitter_mention_button.html.twig */
class __TwigTemplate_c15936a8ed48d6ae2e250615c45a2a07e88a1931c80c95147924492a773272e4 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->blocks = array(
'block' => array($this, 'block_block'),
);
}
protected function doGetParent(array $context)
{
// line 11
return $this->loadTemplate($this->getAttribute($this->getAttribute((isset($context["sonata_block"]) ? $context["sonata_block"] : $this->getContext($context, "sonata_block")), "templates", array()), "block_base", array()), "SonataSeoBundle:Block:block_twitter_mention_button.html.twig", 11);
}
protected function doDisplay(array $context, array $blocks = array())
{
$__internal_56d8750bf02212eee53a747aadee259291677d112a6bf358f85c3ef77593b1c4 = $this->env->getExtension("native_profiler");
$__internal_56d8750bf02212eee53a747aadee259291677d112a6bf358f85c3ef77593b1c4->enter($__internal_56d8750bf02212eee53a747aadee259291677d112a6bf358f85c3ef77593b1c4_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "SonataSeoBundle:Block:block_twitter_mention_button.html.twig"));
$this->getParent($context)->display($context, array_merge($this->blocks, $blocks));
$__internal_56d8750bf02212eee53a747aadee259291677d112a6bf358f85c3ef77593b1c4->leave($__internal_56d8750bf02212eee53a747aadee259291677d112a6bf358f85c3ef77593b1c4_prof);
}
// line 13
public function block_block($context, array $blocks = array())
{
$__internal_fac307541d86d817e1bf602fc300a620fa26e60f2c1356d60ad69178e81e62e2 = $this->env->getExtension("native_profiler");
$__internal_fac307541d86d817e1bf602fc300a620fa26e60f2c1356d60ad69178e81e62e2->enter($__internal_fac307541d86d817e1bf602fc300a620fa26e60f2c1356d60ad69178e81e62e2_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "block"));
// line 14
ob_start();
// line 15
echo "
";
// line 16
if ($this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "user", array())) {
// line 17
echo "
<a href=\"https://twitter.com/intent/tweet?screen_name=";
// line 18
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "user", array()), "html", null, true);
echo "\" class=\"twitter-mention-button\"
data-related=\"";
// line 19
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "recommend", array()), "html", null, true);
echo "\"
";
// line 20
if ($this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "text", array())) {
echo "data-text=\"";
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "text", array()), "html", null, true);
echo "\"";
}
// line 21
echo " ";
if ($this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "recommend", array())) {
echo "data-related=\"";
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "recommend", array()), "html", null, true);
echo "\"";
}
// line 22
echo " ";
if ($this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "large_button", array())) {
echo "data-size=\"large\"";
}
// line 23
echo " data-lang=\"";
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "language", array()), "html", null, true);
echo "\"
";
// line 24
if ($this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "opt_out", array())) {
echo "data-dnt=\"true\"";
}
echo ">
Tweet to @";
// line 25
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "user", array()), "html", null, true);
echo "
</a>
";
}
// line 29
echo "
";
echo trim(preg_replace('/>\s+</', '><', ob_get_clean()));
$__internal_fac307541d86d817e1bf602fc300a620fa26e60f2c1356d60ad69178e81e62e2->leave($__internal_fac307541d86d817e1bf602fc300a620fa26e60f2c1356d60ad69178e81e62e2_prof);
}
public function getTemplateName()
{
return "SonataSeoBundle:Block:block_twitter_mention_button.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 93 => 29, 86 => 25, 80 => 24, 75 => 23, 70 => 22, 63 => 21, 57 => 20, 53 => 19, 49 => 18, 46 => 17, 44 => 16, 41 => 15, 39 => 14, 33 => 13, 18 => 11,);
}
}
/* {#*/
/* */
/* This file is part of the Sonata package.*/
/* */
/* (c) Thomas Rabaix <[email protected]>*/
/* */
/* For the full copyright and license information, please view the LICENSE*/
/* file that was distributed with this source code.*/
/* */
/* #}*/
/* {% extends sonata_block.templates.block_base %}*/
/* */
/* {% block block %}*/
/* {% spaceless %}*/
/* */
/* {% if settings.user %}*/
/* */
/* <a href="https://twitter.com/intent/tweet?screen_name={{ settings.user }}" class="twitter-mention-button"*/
/* data-related="{{ settings.recommend }}"*/
/* {% if settings.text %}data-text="{{ settings.text }}"{% endif %}*/
/* {% if settings.recommend %}data-related="{{ settings.recommend }}"{% endif %}*/
/* {% if settings.large_button %}data-size="large"{% endif %}*/
/* data-lang="{{ settings.language }}"*/
/* {% if settings.opt_out %}data-dnt="true"{% endif %}>*/
/* Tweet to @{{ settings.user }}*/
/* </a>*/
/* */
/* {% endif %}*/
/* */
/* {% endspaceless %}*/
/* {% endblock %}*/
/* */
| {'content_hash': '403028d7cf9b065f57d8dbfc6d44f27e', 'timestamp': '', 'source': 'github', 'line_count': 147, 'max_line_length': 305, 'avg_line_length': 47.14965986394558, 'alnum_prop': 0.580291444236041, 'repo_name': 'DevKhater/YallaWebSite', 'id': 'b0457c3640caa186e46dfeac2f6ad8ac2418ad87', 'size': '6931', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/cache/dev/twig/4f/4fd0b1b19715e72de8a71615ee587055f474e9973dc404d3f528b73a01dafd0e.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '3606'}, {'name': 'Batchfile', 'bytes': '5124'}, {'name': 'CSS', 'bytes': '216209'}, {'name': 'HTML', 'bytes': '129116'}, {'name': 'JavaScript', 'bytes': '539065'}, {'name': 'Makefile', 'bytes': '5620'}, {'name': 'PHP', 'bytes': '188837'}, {'name': 'Python', 'bytes': '8002'}]} |
<?php
namespace filsh\datepicker;
use \Yii;
/**
* Description of DateTimePicker
* @property type $name Description
*/
class DatePickerAsset extends \yii\web\AssetBundle
{
public $sourcePath = '@bower/bootstrap-datepicker/dist';
public $enableLocale = true;
public $js = [
'js/bootstrap-datepicker.min.js'
];
public $css = [
'css/bootstrap-datepicker3.min.css'
];
public $depends = [
\yii\web\JqueryAsset::class
];
public function init()
{
if(!empty($this->js) && $this->enableLocale && ($language = $this->getLanguage()) !== null) {
$this->js[] = 'js/locales/bootstrap-datepicker.'. $language .'.min.js';
}
parent::init();
}
protected function getLanguage()
{
$language = str_replace('-', '_', strtolower(Yii::$app->language));
if(strpos($language, '_') !== false) {
$language = explode('_', $language)[0];
}
if($language === 'en') {
$language = null;
}
return $language;
}
} | {'content_hash': '650953e819e782369ed031e6ce9a28d6', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 101, 'avg_line_length': 22.53061224489796, 'alnum_prop': 0.532608695652174, 'repo_name': 'Filsh/yii2-datepicker', 'id': 'f1fecff4553fe3cf853142b779b9d05c139df317', 'size': '1104', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'DatePickerAsset.php', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'PHP', 'bytes': '7321'}]} |
#ifndef GLOBUS_DONT_DOCUMENT_INTERNAL
/**
* @file globus_error_gssapi.c
* @brief Globus Error GSS API
*/
#endif
#include "globus_i_error_gssapi.h"
#include <string.h>
/**
* @brief Construct Error
* @ingroup globus_gssapi_error_object
* @details
* Allocate and initialize an error of type GLOBUS_ERROR_TYPE_GSSAPI
*
* @param base_source
* Pointer to the originating module.
* @param base_cause
* The error object causing the error. If this is the original
* error, this parameter may be NULL.
* @param major_status
* The GSSAPI major status
* @param minor_status
* The GSSAPI minor status
* @return
* The resulting error object. It is the user's responsibility
* to eventually free this object using globus_object_free(). A
* globus_result_t may be obtained by calling
* globus_error_put() on this object.
*/
globus_object_t *
globus_error_construct_gssapi_error(
globus_module_descriptor_t * base_source,
globus_object_t * base_cause,
const OM_uint32 major_status,
const OM_uint32 minor_status)
{
globus_object_t * error;
globus_object_t * newerror;
newerror = globus_object_construct(GLOBUS_ERROR_TYPE_GSSAPI);
error = globus_error_initialize_gssapi_error(
newerror,
base_source,
base_cause,
major_status,
minor_status);
if (error == NULL)
{
globus_object_free(newerror);
}
return error;
}/* globus_error_construct_gssapi_error() */
/**
* @brief Initialize Error
* @ingroup globus_gssapi_error_object
* @details
* Initialize a previously allocated error of type
* GLOBUS_ERROR_TYPE_GSSAPI
*
* @param error
* The previously allocated error object.
* @param base_source
* Pointer to the originating module.
* @param base_cause
* The error object causing the error. If this is the original
* error this parameter may be NULL.
* @param major_status
* The GSSAPI major status
* @param minor_status
* The GSSAPI minor status
* @return
* The resulting error object. You may have to call
* globus_error_put() on this object before passing it on.
*/
globus_object_t *
globus_error_initialize_gssapi_error(
globus_object_t * error,
globus_module_descriptor_t * base_source,
globus_object_t * base_cause,
const OM_uint32 major_status,
const OM_uint32 minor_status)
{
globus_l_gssapi_error_data_t * instance_data;
globus_object_t * minor_obj;
gss_OID_set actual_mechs;
OM_uint32 local_minor_status;
extern gss_OID gss_mech_globus_gssapi_openssl;
instance_data = (globus_l_gssapi_error_data_t *)
malloc(sizeof(globus_l_gssapi_error_data_t));
instance_data->major_status = major_status;
instance_data->minor_status = minor_status;
instance_data->is_globus_gsi = GLOBUS_FALSE;
if(gss_indicate_mechs(
&local_minor_status, &actual_mechs) == GSS_S_COMPLETE)
{
int boolean;
if(gss_test_oid_set_member(
&local_minor_status,
gss_mech_globus_gssapi_openssl,
actual_mechs,
&boolean) == GSS_S_COMPLETE && boolean)
{
instance_data->is_globus_gsi = GLOBUS_TRUE;
}
gss_release_oid_set(&local_minor_status, &actual_mechs);
}
if(instance_data->is_globus_gsi)
{
minor_obj = globus_error_get((globus_result_t) minor_status);
if(!base_cause)
{
base_cause = minor_obj;
}
else if(minor_obj)
{
base_cause = globus_error_initialize_base(
minor_obj, globus_error_get_source(base_cause), base_cause);
}
}
globus_object_set_local_instance_data(error, instance_data);
return globus_error_initialize_base(error, base_source, base_cause);
}/* globus_error_initialize_gssapi_error() */
/**
* @brief Get Major Status
* @ingroup globus_gssapi_error_accessor
* @details
* Retrieve the major status from a GSSAPI error object.
*
* @param error
* The error from which to retrieve the major status
* @return
* The major status stored in the object
*/
OM_uint32
globus_error_gssapi_get_major_status(
globus_object_t * error)
{
return ((globus_l_gssapi_error_data_t *)
globus_object_get_local_instance_data(error))->major_status;
}/* globus_error_gssapi_get_major_status */
/**
* @brief Set Major Status
* @ingroup globus_gssapi_error_accessor
* @details
* Set the major status in a GSSAPI error object.
*
* @param error
* The error object for which to set the major status
* @param major_status
* The major status
* @return
* void
*/
void
globus_error_gssapi_set_major_status(
globus_object_t * error,
const OM_uint32 major_status)
{
((globus_l_gssapi_error_data_t *)
globus_object_get_local_instance_data(error))->major_status = major_status;
}/* globus_error_gssapi_set_major_status */
/**
* @brief Get Minor Status
* @ingroup globus_gssapi_error_accessor
* @details
* Retrieve the minor status from a gssapi error object.
*
* @param error
* The error from which to retrieve the minor status
* @return
* The minor status stored in the object
*/
OM_uint32
globus_error_gssapi_get_minor_status(
globus_object_t * error)
{
globus_l_gssapi_error_data_t * data;
data = (globus_l_gssapi_error_data_t *)
globus_object_get_local_instance_data(error);
if(data)
{
if(data->is_globus_gsi)
{
return (OM_uint32) globus_error_put(
globus_object_copy(globus_error_get_cause(error)));
}
else
{
return data->minor_status;
}
}
return 0;
}
/* globus_error_gssapi_get_minor_status() */
/**
* @brief Error Match
* @ingroup globus_gssapi_error_utility
* @details
* Check whether the error originated from a specific module and
* match a specific major status.
*
* This function checks whether the error or any of it's causative
* errors originated from a specific module and contains a specific
* major status. If the module descriptor is left unspecified this
* function will check for any error of the specified major_status
* and vice versa.
*
* @param error
* The error object for which to perform the check
* @param module
* The module descriptor to check for
* @param major_status
* The major status to check for
* @retval GLOBUS_TRUE The error matched the module and major status
* @retval GLOBUS_FALSE The error failed to match the module and major status
*/
globus_bool_t
globus_error_gssapi_match(
globus_object_t * error,
globus_module_descriptor_t * module,
const OM_uint32 major_status)
{
globus_module_descriptor_t * source_module;
int current_major_status;
if(error == NULL)
{
return GLOBUS_FALSE;
}
if(globus_object_get_type(error) != GLOBUS_ERROR_TYPE_GSSAPI)
{
/* not our type, skip it */
return globus_error_gssapi_match(
globus_error_get_cause(error),
module,
major_status);
}
source_module = globus_error_get_source(error);
current_major_status = globus_error_gssapi_get_major_status(error);
if(source_module == module && current_major_status == major_status)
{
return GLOBUS_TRUE;
}
else
{
return globus_error_gssapi_match(
globus_error_get_cause(error),
module,
major_status);
}
}
/* globus_error_gssapi_match */
/**
* @brief Wrap GSSAPI Error
* @ingroup globus_gssapi_error_utility
* @details
* Allocate and initialize an error of type GLOBUS_ERROR_TYPE_GLOBUS
* which contains a causal error of type GLOBUS_ERROR_TYPE_GSSAPI.
*
* @param base_source
* Pointer to the originating module.
* @param major_status
* The major status to use when generating the causal error.
* @param minor_status
* The minor status to use when generating the causal error.
* @param type
* The error type. We may reserve part of this namespace for
* common errors. Errors not in this space are assumed to be
* local to the originating module.
* @param source_file
* Name of file. Use __FILE__
* @param source_func
* Name of function. Use _globus_func_name and declare your func with
* GlobusFuncName(<name>)
* @param source_line
* Line number. Use __LINE__
* @param short_desc_format
* Short format string giving a succinct description
* of the error. To be passed on to the user.
* @param ...
* Arguments for the format string.
* @return
* The resulting error object. It is the user's responsibility
* to eventually free this object using globus_object_free(). A
* globus_result_t may be obtained by calling
* globus_error_put() on this object.
*/
globus_object_t *
globus_error_wrap_gssapi_error(
globus_module_descriptor_t * base_source,
OM_uint32 major_status,
OM_uint32 minor_status,
int type,
const char * source_file,
const char * source_func,
int source_line,
const char * short_desc_format,
...)
{
globus_object_t * causal_error;
globus_object_t * error;
va_list ap;
causal_error = globus_error_construct_gssapi_error(
GLOBUS_GSI_GSSAPI_MODULE,
NULL,
major_status,
minor_status);
if(!causal_error)
{
return GLOBUS_NULL;
}
va_start(ap, short_desc_format);
error = globus_error_v_construct_error(
base_source,
causal_error,
type,
source_file,
source_func,
source_line,
short_desc_format,
ap);
va_end(ap);
if(error == GLOBUS_NULL)
{
globus_object_free(causal_error);
}
return error;
}
/* globus_error_wrap_gssapi_error */
| {'content_hash': 'db3829dfc5a0fb0ca1f394a3f33e214e', 'timestamp': '', 'source': 'github', 'line_count': 362, 'max_line_length': 80, 'avg_line_length': 29.867403314917127, 'alnum_prop': 0.5895301516833148, 'repo_name': 'eunsungc/gt6-RAMSES_8_5', 'id': '579893158dff1caffcc5c673928416a59e98d44d', 'size': '11420', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'gsi/gssapi_error/source/library/globus_error_gssapi.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '8555'}, {'name': 'C', 'bytes': '21601985'}, {'name': 'C++', 'bytes': '219725'}, {'name': 'CSS', 'bytes': '3348'}, {'name': 'Groff', 'bytes': '2150691'}, {'name': 'HTML', 'bytes': '55140'}, {'name': 'KRL', 'bytes': '4950'}, {'name': 'Lex', 'bytes': '18165'}, {'name': 'M4', 'bytes': '453378'}, {'name': 'Makefile', 'bytes': '5063950'}, {'name': 'Objective-C', 'bytes': '212361'}, {'name': 'Perl', 'bytes': '795825'}, {'name': 'Python', 'bytes': '246664'}, {'name': 'Shell', 'bytes': '20472031'}, {'name': 'XSLT', 'bytes': '13587'}, {'name': 'Yacc', 'bytes': '23583'}]} |
package p01_Geometry.Abstract;
import p01_Geometry.Vertices.Vertex;
public abstract class Shape {
protected Vertex[] coordinates;
protected Shape() {
}
public Vertex[] getCoordinates() {
return coordinates;
}
protected String getClassName() {
String fullClassName = this.getClass().toString();
int indexOfLastDot = fullClassName.lastIndexOf('.');
return fullClassName.substring(indexOfLastDot + 1, fullClassName.length());
}
}
| {'content_hash': 'bb24a8c38e84a69d15fc6056d2e5016d', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 77, 'avg_line_length': 21.333333333333332, 'alnum_prop': 0.7433035714285714, 'repo_name': 'HouseBreaker/Java-Fundamentals', 'id': 'f6f7fdb6c633b38dc4317e1298dc195b1b01305a', 'size': '448', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '05. OOP in Java/src/p01_Geometry/Abstract/Shape.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '58060'}]} |
import { mount } from '@vue/test-utils';
import store from 'kolibri.coreVue.vuex.store';
import ContentNodeRow from '../../src/views/SelectContentPage/ContentNodeRow';
import { makeNode } from '../utils/data';
const defaultProps = {
node: {
title: 'Awesome Content',
kind: 'topic',
id: 'awesome_content',
},
message: 'HELLO',
};
function makeWrapper(props = {}) {
return mount(ContentNodeRow, {
propsData: { ...defaultProps, ...props },
store,
});
}
// prettier-ignore
function getElements(wrapper) {
return {
titleText: () => wrapper.find('.title').text().trim(),
messageText: () => wrapper.find('.message').text().trim(),
goToTopicButton: () => wrapper.find('a[name="select-node"]'),
checkbox: () => wrapper.find('input[type="checkbox"]'),
KCheckbox: () => wrapper.find({ name: 'KCheckbox' }),
};
}
describe('contentNodeRow component', () => {
it('shows the correct title', () => {
const wrapper = makeWrapper();
const { titleText } = getElements(wrapper);
expect(titleText()).toEqual('Awesome Content');
});
it('shows the correct message', () => {
const wrapper = makeWrapper();
const { messageText } = getElements(wrapper);
expect(messageText()).toEqual('HELLO');
});
it('when node is a topic, title is a button that emits "clicktopic" event', () => {
const wrapper = makeWrapper();
const { goToTopicButton } = getElements(wrapper);
goToTopicButton().trigger('click');
expect(wrapper.emitted().clicktopic).toEqual([[wrapper.vm.node]]);
});
it('when node is not a topic, title is just text', () => {
const wrapper = makeWrapper({
node: makeNode('1', {
kind: 'video',
}),
});
const { goToTopicButton, titleText } = getElements(wrapper);
expect(goToTopicButton().exists()).toEqual(false);
expect(titleText()).toEqual('node_1');
});
it('when node is disabled, title is just text', () => {
const wrapper = makeWrapper({ disabled: true });
const { goToTopicButton, titleText } = getElements(wrapper);
expect(goToTopicButton()[0]).toEqual(undefined);
expect(titleText()).toEqual('Awesome Content');
});
it('when checkbox is changed, it emits a "changeselection" event', () => {
const wrapper = makeWrapper();
const { checkbox } = getElements(wrapper);
// have to "click" the inner checkbox to trigger "change" on whole component
checkbox().trigger('click');
expect(wrapper.emitted().changeselection).toEqual([[wrapper.vm.node]]);
});
it('when props.disabled, the checkbox is disabled', () => {
const wrapper = makeWrapper({ disabled: true });
const { checkbox } = getElements(wrapper);
expect(checkbox().attributes().disabled).toEqual('disabled');
});
it('when props.checked, the checkbox is checked', () => {
const wrapper = makeWrapper({
disabled: true,
checked: true,
});
// For some reason, the HTML for the actual checkbox does not have checked attribute
const { KCheckbox } = getElements(wrapper);
expect(KCheckbox().props().checked).toEqual(true);
});
it('when props.determinate, the checkbox is indeterminate', () => {
const wrapper = makeWrapper({
disabled: true,
checked: true,
indeterminate: true,
});
const { KCheckbox } = getElements(wrapper);
expect(KCheckbox().props().indeterminate).toEqual(true);
});
});
| {'content_hash': '27a4981024ff41f1e8b738b9495fadc9', 'timestamp': '', 'source': 'github', 'line_count': 104, 'max_line_length': 88, 'avg_line_length': 32.83653846153846, 'alnum_prop': 0.6354319180087847, 'repo_name': 'lyw07/kolibri', 'id': '4b72f5db5b8e22a2bd867b9e7ead150f18e96c42', 'size': '3415', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'kolibri/plugins/device_management/assets/test/views/content-node-row.spec.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '601'}, {'name': 'CSS', 'bytes': '2007902'}, {'name': 'Dockerfile', 'bytes': '6930'}, {'name': 'Gherkin', 'bytes': '199214'}, {'name': 'HTML', 'bytes': '34393'}, {'name': 'JavaScript', 'bytes': '1376767'}, {'name': 'Makefile', 'bytes': '11718'}, {'name': 'Python', 'bytes': '1896793'}, {'name': 'Shell', 'bytes': '11350'}, {'name': 'Vue', 'bytes': '1278479'}]} |
var player, OKEvents, options;
(function ($) {
"use strict";
var BLANK_GIF = "data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw%3D%3D";
$.okvideo = function (options) {
// if the option var was just a string, turn it into an object
if (typeof options !== 'object') options = { 'video' : options };
var base = this;
// kick things off
base.init = function () {
base.options = $.extend({}, $.okvideo.options, options);
// support older versions of okvideo
if (base.options.video === null) base.options.video = base.options.source;
if (OKEvents.utils.isMobile()) {
$('body').append('<div id="okplayer" style="position:fixed;left:0;top:0;overflow:hidden;z-index:-999;height:100%;width:100%;"></div>');
} else if (base.options.adproof) {
$('body').append('<div style="position:fixed;left:0;top:0;overflow:hidden;z-index:-998;height:100%;width:100%;" id="okplayer-mask"></div><div id="okplayer" style="position:fixed;left:0;top:0;overflow:hidden;z-index:-999;height:110%;width:110%;"></div>');
} else {
$('body').append('<div style="position:fixed;left:0;top:0;overflow:hidden;z-index:-998;height:100%;width:100%;" id="okplayer-mask"></div><div id="okplayer" style="position:fixed;left:0;top:0;overflow:hidden;z-index:-999;height:100%;width:100%;"></div>');
}
$("#okplayer-mask").css("background-image", "url(" + BLANK_GIF + ")");
base.setOptions();
if (base.options.playlist.list === null) {
if (base.options.video.provider === 'youtube') {
base.loadYouTubeAPI();
} else if (base.options.video.provider === 'vimeo') {
base.options.volume /= 100;
base.loadVimeoAPI();
}
} else {
base.loadYouTubeAPI();
}
};
// clean the options
base.setOptions = function () {
// exchange 'true' for '1' and 'false' for 3
for (var key in this.options){
if (this.options[key] == true) this.options[key] = 1;
if (this.options[key] == false) this.options[key] = 3;
}
if (base.options.playlist.list === null) {
base.options.video = base.determineProvider();
}
// pass options to the window
$(window).data('okoptions', base.options);
};
// load the youtube api
base.loadYouTubeAPI = function (callback) {
base.insertJS('http://www.youtube.com/player_api');
};
base.loadYouTubePlaylist = function() {
player.loadPlaylist(base.options.playlist.list, base.options.playlist.index, base.options.playlist.startSeconds, base.options.playlist.suggestedQuality);
};
// load the vimeo api by replacing the div with an iframe and loading js
base.loadVimeoAPI = function() {
$('#okplayer').replaceWith(function() {
return '<iframe src="http://player.vimeo.com/video/' + base.options.video.id + '?api=1&js_api=1&title=0&byline=0&portrait=0&playbar=0&loop=' + base.options.loop + '&autoplay=1&player_id=okplayer" frameborder="0" style="' + $(this).attr('style') + 'visibility:hidden;background-color:black;" id="' + $(this).attr('id') + '"></iframe>';
});
base.insertJS('http://a.vimeocdn.com/js/froogaloop2.min.js', function(){
vimeoPlayerReady();
});
};
// insert js into the head and exectue a callback function
base.insertJS = function(src, callback){
var tag = document.createElement('script');
if (callback){
if (tag.readyState){ //IE
tag.onreadystatechange = function(){
if (tag.readyState === "loaded" ||
tag.readyState === "complete"){
tag.onreadystatechange = null;
callback();
}
};
} else {
tag.onload = function() {
callback();
};
}
}
tag.src = src;
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
};
// is it from youtube or vimeo?
base.determineProvider = function () {
var a = document.createElement('a');
a.href = base.options.video;
if (/youtube.com/.test(base.options.video)){
return { "provider" : "youtube", "id" : a.href.slice(a.href.indexOf('v=') + 2).toString() };
} else if (/vimeo.com/.test(base.options.video)) {
return { "provider" : "vimeo", "id" : a.href.split('/')[3].toString() };
} else if (/[A-Za-z0-9_]+/.test(base.options.video)) {
var id = new String(base.options.video.match(/[A-Za-z0-9_]+/));
if (id.length == 11) {
return { "provider" : "youtube", "id" : id.toString() };
} else {
for (var i = 0; i < base.options.video.length; i++) {
if (typeof parseInt(base.options.video[i]) !== "number") {
throw 'not vimeo but thought it was for a sec';
}
}
return { "provider" : "vimeo", "id" : base.options.video };
}
} else {
throw "OKVideo: Invalid video source";
}
};
base.init();
};
$.okvideo.options = {
source: null, // Deprecate dis l8r
video: null,
playlist: { // eat ur heart out @brokyo
list: null,
index: 0,
startSeconds: 0,
suggestedQuality: "default" // options: small, medium, large, hd720, hd1080, highres, default
},
disableKeyControl: 1,
captions: 0,
loop: 1,
hd: 1,
volume: 0,
adproof: false,
unstarted: null,
onFinished: null,
onReady: null,
onPlay: null,
onPause: null,
buffering: null,
annotations: true,
cued: null
};
$.fn.okvideo = function (options) {
return this.each(function () {
(new $.okvideo(options));
});
};
})(jQuery);
// vimeo player ready
function vimeoPlayerReady() {
options = $(window).data('okoptions');
var iframe = $('#okplayer')[0];
player = $f(iframe);
// hide player until Vimeo hides controls...
window.setTimeout(function(){
$('#okplayer').css('visibility', 'visible');
}, 2000);
player.addEvent('ready', function () {
OKEvents.v.onReady();
player.api('play');
if (OKEvents.utils.isMobile()) {
// mobile devices cannot listen for play event
OKEvents.v.onPlay();
} else {
player.addEvent('play', OKEvents.v.onPlay);
player.addEvent('pause', OKEvents.v.onPause);
player.addEvent('finish', OKEvents.v.onFinish);
}
});
}
// youtube player ready
function onYouTubePlayerAPIReady() {
options = $(window).data('okoptions');
player = new YT.Player('okplayer', {
videoId: options.video ? options.video.id : null,
playerVars: {
'autohide': 1,
'autoplay': 1,
'disablekb': options.keyControls,
'cc_load_policy': options.captions,
'controls': 0,
'enablejsapi': 1,
'fs': 0,
'modestbranding': 1,
'iv_load_policy': options.annotations,
'loop': options.loop,
'showinfo': 0,
'rel': 0,
'wmode': 'opaque',
'hd': options.hd
},
events: {
'onReady': OKEvents.yt.ready,
'onStateChange': OKEvents.yt.onStateChange,
'onError': OKEvents.yt.error
}
});
}
OKEvents = {
yt: {
ready: function(event){
event.target.setVolume(options.volume);
if (options.playlist.list) {
player.loadPlaylist(options.playlist.list, options.playlist.index, options.playlist.startSeconds, options.playlist.suggestedQuality);
} else {
event.target.playVideo();
}
OKEvents.utils.isFunction(options.onReady) && options.onReady();
},
onStateChange: function(event){
switch(event.data){
case -1:
OKEvents.utils.isFunction(options.unstarted) && options.unstarted();
break;
case 0:
OKEvents.utils.isFunction(options.onFinished) && options.onFinished();
options.loop && event.target.playVideo();
break;
case 1:
OKEvents.utils.isFunction(options.onPlay) && options.onPlay();
break;
case 2:
OKEvents.utils.isFunction(options.onPause) && options.onPause();
break;
case 3:
OKEvents.utils.isFunction(options.buffering) && options.buffering();
break;
case 5:
OKEvents.utils.isFunction(options.cued) && options.cued();
break;
default:
throw "OKVideo: received invalid data from YT player.";
}
},
error: function(event){
throw event;
}
},
v: {
onReady: function(){
OKEvents.utils.isFunction(options.onReady) && options.onReady();
},
onPlay: function(){
if (!OKEvents.utils.isMobile()) player.api('api_setVolume', options.volume);
OKEvents.utils.isFunction(options.onPlay) && options.onPlay();
},
onPause: function(){
OKEvents.utils.isFunction(options.onPause) && options.onPause();
},
onFinish: function(){
OKEvents.utils.isFunction(options.onFinish) && options.onFinish();
}
},
utils: {
isFunction: function(func){
if (typeof func === 'function'){
return true;
} else {
return false;
}
},
isMobile: function() {
if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
return true;
} else {
return false;
}
}
}
};
| {'content_hash': '5d2105e967966aa9c9f9fa937a8755a6', 'timestamp': '', 'source': 'github', 'line_count': 298, 'max_line_length': 342, 'avg_line_length': 31.553691275167786, 'alnum_prop': 0.5886419227905988, 'repo_name': 'giuseppezileni/savemadeitaly', 'id': '975887c5b5b4550acfeb7247193fed9ed6f65333', 'size': '9525', 'binary': False, 'copies': '1', 'ref': 'refs/heads/gh-pages', 'path': 'javascripts/okvideo.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '600918'}, {'name': 'HTML', 'bytes': '238558'}, {'name': 'JavaScript', 'bytes': '1601022'}, {'name': 'PHP', 'bytes': '186697'}]} |
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at '[email protected]'. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
| {'content_hash': 'd2a7ebe00cde332ac922f5cd0915e1ed', 'timestamp': '', 'source': 'github', 'line_count': 70, 'max_line_length': 87, 'avg_line_length': 45.42857142857143, 'alnum_prop': 0.8210691823899371, 'repo_name': 'TraiLYNNE/oracle-cli-project', 'id': '2ceb0b8c9e39bc5a923ac2e9bb52b138d47c5d09', 'size': '3235', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'CODE_OF_CONDUCT.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '6359'}, {'name': 'Shell', 'bytes': '131'}]} |
"""Specialization for linux containers, using environment variables."""
from __future__ import unicode_literals
import errno
import os
import platform
import shutil
from psqtraviscontainer import architecture
from psqtraviscontainer import container
from psqtraviscontainer import distro
from psqtraviscontainer import linux_container
from psqtraviscontainer import package_system
DistroInfo = distro.DistroInfo
DistroConfig = distro.DistroConfig
def get_dir_for_distro(container_dir, config):
"""Get the distro dir in a container_dir for a DistroConfig."""
arch = config["arch"]
url = config["url"]
distro_folder_name_template = (os.path.basename(url) + ".root")
distro_folder_name = distro_folder_name_template.format(arch=arch)
return os.path.realpath(os.path.join(container_dir, distro_folder_name))
class LocalLinuxContainer(container.AbstractContainer):
"""A container for a linux distribution.
We can execute commands inside this container by using proot and qemu.
"""
def __init__(self, # suppress(too-many-arguments)
package_root,
release,
arch,
pkg_sys_constructor):
"""Initialize this LocalLinuxContainer, storing its distro config."""
super(LocalLinuxContainer, self).__init__()
self._arch = arch
self._package_root = package_root
self._pkgsys = pkg_sys_constructor(release, arch, self)
def _root_filesystem_directory(self):
"""Return directory on parent filesystem where our root is located."""
return self._package_root
def _package_system(self):
"""Return package system for this distribution."""
return self._pkgsys
def _subprocess_popen_arguments(self, argv, **kwargs):
"""For native arguments argv, return AbstractContainer.PopenArguments.
This returned tuple will have no environment variables set, but the
proot command to enter this container will be prepended to the
argv provided.
"""
popen_args = self.__class__.PopenArguments
prepend_env = {
"LD_LIBRARY_PATH": os.pathsep.join([
os.path.join(self._package_root,
"usr",
"lib",
"x86_64-linux-gnu"),
os.path.join(self._package_root,
"usr",
"lib",
"i686-linux-gnu"),
os.path.join(self._package_root,
"usr",
"lib")
]),
"PKG_CONFIG_PATH": os.pathsep.join([
os.path.join(self._package_root,
"usr",
"lib",
"pkgconfig"),
os.path.join(self._package_root,
"usr",
"lib",
"x86_64-linux-gnu",
"pkgconfig"),
os.path.join(self._package_root,
"usr",
"lib",
"i686-linux-gnu",
"pkgconfig")
]),
"LIBRARY_PATH": os.pathsep.join([
os.path.join(self._package_root,
"usr",
"lib"),
os.path.join(self._package_root,
"usr",
"lib",
"x86_64-linux-gnu"),
os.path.join(self._package_root,
"usr",
"lib",
"i686-linux-gnu")
]),
"INCLUDE_PATH": os.pathsep.join([
os.path.join(self._package_root,
"usr",
"include")
]),
"CPATH": os.pathsep.join([
os.path.join(self._package_root,
"usr",
"include")
]),
"CPPPATH": os.pathsep.join([
os.path.join(self._package_root,
"usr",
"include")
]),
"PATH": os.pathsep.join([
os.path.join(self._package_root,
"usr",
"bin")
])
}
return popen_args(prepend=prepend_env,
overwrite=dict(),
argv=argv)
def clean(self):
"""Clean out this container."""
remove_directories = linux_container.directories_to_remove_on_clean(
self._package_root
)
for directory in remove_directories:
if os.path.islink(directory):
continue
try:
shutil.rmtree(os.path.join(self._package_root, directory))
except OSError as error:
if error.errno != errno.ENOENT:
raise error
create_directories = linux_container.directories_to_create_on_clean(
self._package_root
)
for directory in create_directories:
try:
os.makedirs(directory)
except OSError as error:
if error.errno != errno.EEXIST: # suppress(PYC90)
raise error
def container_for_directory(container_dir, distro_config):
"""G an existing LocalLinuxContainer at container_dir for distro_config.
Also take into account arguments in result to look up the the actual
directory for this distro.
"""
path_to_distro_folder = get_dir_for_distro(container_dir,
distro_config)
return LocalLinuxContainer(path_to_distro_folder,
distro_config["release"],
distro_config["arch"],
distro_config["pkgsys"])
def create(container_dir, distro_config):
"""Create a container using proot."""
_, minimize_actions = linux_container.fetch_distribution(container_dir,
None,
distro_config)
path_to_distro_folder = get_dir_for_distro(container_dir,
distro_config)
local_container = LocalLinuxContainer(path_to_distro_folder,
distro_config["release"],
distro_config["arch"],
distro_config["pkgsys"])
minimize_actions[distro_config["distro"]](local_container,
path_to_distro_folder)
return local_container
def _info_with_arch_to_config(info, arch):
"""Convert selected architecture for DistroInfo into DistroConfig."""
config = info.kwargs.copy()
del config["arch"]
del config["archfetch"]
config["arch"] = arch
return config
def _valid_archs(archs):
"""Return valid archs to emulate from archs."""
alias = architecture.Alias.universal(platform.machine())
return [a for a in archs
if architecture.Alias.universal(a) == alias]
def match(info, arguments):
"""Check if info matches arguments."""
if platform.system() != "Linux":
return None
if arguments.get("distro", None) != info.kwargs["distro"]:
return None
if not (arguments.get("local", None) or
arguments.get("installation", None) == "local"):
return None
distro_release = info.kwargs["release"]
# pychecker thinks that a list comprehension as a return value is
# always None.
distro_archs = _valid_archs(info.kwargs["arch"]) # suppress(PYC90)
distro_archfetch = info.kwargs["archfetch"]
if arguments.get("release", None) == distro_release:
converted = distro_archfetch(arguments.get("arch", None))
if converted in distro_archs:
return _info_with_arch_to_config(info, converted)
return None
def enumerate_all(info):
"""Enumerate all valid configurations for this DistroInfo."""
if platform.system() != "Linux":
return
for arch in _valid_archs(info.kwargs["arch"]): # suppress(PYC90)
yield _info_with_arch_to_config(info, arch)
class LinuxLocalInfo(DistroInfo):
"""Linux-specific specialization of DistroInfo."""
PACKAGE_SYSTEMS = {
"Ubuntu": package_system.DpkgLocal,
}
def __new__(cls, distro_type, **kwargs):
"""Create DistroInfo tuple using provided arguments."""
kwargs.update({
"distro": distro_type,
"pkgsys": LinuxLocalInfo.PACKAGE_SYSTEMS[distro_type],
"installation": "local"
})
return DistroInfo.__new__(cls,
create_func=create,
get_func=container_for_directory,
match_func=match,
enumerate_func=enumerate_all,
kwargs=kwargs)
DISTRIBUTIONS = [ # suppress(unused-variable)
LinuxLocalInfo("Ubuntu",
release="precise",
url=("http://old-releases.ubuntu.com/releases/ubuntu-core/"
"releases/12.04.3/release/"
"ubuntu-core-12.04.3-core-{arch}.tar.gz"),
arch=["i386", "amd64", "armhf"],
archfetch=architecture.Alias.debian),
LinuxLocalInfo("Ubuntu",
release="trusty",
url=("http://old-releases.ubuntu.com/releases/ubuntu-core/"
"releases/utopic/release/"
"ubuntu-core-14.10-core-{arch}.tar.gz"),
arch=["i386", "amd64", "armhf", "powerpc"],
archfetch=architecture.Alias.debian),
LinuxLocalInfo("Ubuntu",
release="focal",
url=("http://cdimage.ubuntu.com/ubuntu-base/releases/20.04/release/"
"releases/utopic/release/"
"ubuntu-base-20.04-base-{arch}.tar.gz"),
arch=["amd64"],
archfetch=architecture.Alias.debian)
]
| {'content_hash': 'aa9b9b059181ece0a34038e8de795b43', 'timestamp': '', 'source': 'github', 'line_count': 293, 'max_line_length': 87, 'avg_line_length': 35.93174061433447, 'alnum_prop': 0.5072188449848024, 'repo_name': 'polysquare/polysquare-travis-container', 'id': '16672d1827af1e2ec65f1fbf11756a32f95eb14d', 'size': '10793', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'psqtraviscontainer/linux_local_container.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '134851'}]} |
namespace bubblefs {
namespace mytoft {
class FingerprintSharding : public ShardingPolicy {
DECLARE_UNCOPYABLE(FingerprintSharding);
public:
FingerprintSharding();
virtual ~FingerprintSharding();
virtual int Shard(const std::string& key);
};
} // namespace mytoft
} // namespace bubblefs
#endif // BUBBLEFS_UTILS_TOFT_STORAGE_SHARDING_FINGER_SHARDING_H_ | {'content_hash': '1d2ca2cf993661a1c17376ad0ebe44b7', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 66, 'avg_line_length': 25.0, 'alnum_prop': 0.744, 'repo_name': 'mengjiahao/bubblefs', 'id': '95944d328adacf3089920118a7966f17aa606361', 'size': '738', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/utils/toft_storage_sharding_fingerprint_sharding.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '106898'}, {'name': 'C++', 'bytes': '13707092'}, {'name': 'Makefile', 'bytes': '16035'}, {'name': 'Shell', 'bytes': '30451'}]} |
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>dashboard on Joost Plattel</title>
<link>http://jplattel.nl/tags/dashboard/</link>
<description>Recent content in dashboard on Joost Plattel</description>
<generator>Hugo -- gohugo.io</generator>
<language>en-us</language>
<copyright>&copy; 2019</copyright>
<lastBuildDate>Tue, 16 Feb 2016 15:10:08 +0100</lastBuildDate>
<atom:link href="http://jplattel.nl/tags/dashboard/index.xml" rel="self" type="application/rss+xml" />
<item>
<title>Musings on transparency</title>
<link>http://jplattel.nl/post/2016-02-16-musings-on-transparency/</link>
<pubDate>Tue, 16 Feb 2016 15:10:08 +0100</pubDate>
<guid>http://jplattel.nl/post/2016-02-16-musings-on-transparency/</guid>
<description>I've been thinking about and exploring transparency a lot lately. As I'm building dashboards for employees, transparency is one of the key factors of integration within the workforce. But there are some funny things about transparency and this is why most companies and organisations are having difficulty adopting a transparant way of working.
Ownership is spread when sharing processes, this lessens your level of power, but this world is not just about ownership any more, access is what it is all about.</description>
</item>
<item>
<title>Experimenting with company activity dashboards</title>
<link>http://jplattel.nl/post/2014-02-07-experimenting-company-activity-dashboards/</link>
<pubDate>Fri, 07 Feb 2014 14:44:58 +0100</pubDate>
<guid>http://jplattel.nl/post/2014-02-07-experimenting-company-activity-dashboards/</guid>
<description>As an experiment, I'm collecting data from the Moves app from multiple persons within a organisation. The goal is to find out what's possible with the amount of data the persons generate each day. Currently, the collection of data is ongoing and the next step would be the visualization of the data. Here are some simple graphs you can make with the data:
Further steps could be exploring what a group wants from visualisations like this.</description>
</item>
<item>
<title>Using Moves data for?</title>
<link>http://jplattel.nl/post/2013-12-18-using-moves-data/</link>
<pubDate>Wed, 18 Dec 2013 18:29:35 +0100</pubDate>
<guid>http://jplattel.nl/post/2013-12-18-using-moves-data/</guid>
<description>In July I wrote a little wrapper for the Moves App API. But I didn't develop the ideas I had for it any further due to time constraints. But other projects got me into it and I wanted to share what I'm currently building. I've drawn the same concept of a fitbit dashboard over to a Moves Dashboard, so we can use the same data. And I've got some friends who come up with great ideas too!</description>
</item>
<item>
<title>Making sense of your phone invoices</title>
<link>http://jplattel.nl/post/2013-10-21-making-sense-of-your-phone-invoices/</link>
<pubDate>Mon, 21 Oct 2013 10:02:44 +0200</pubDate>
<guid>http://jplattel.nl/post/2013-10-21-making-sense-of-your-phone-invoices/</guid>
<description>Telephone companies tend to have a lot of data about a user. This data includes some information that could help you decide whether you could pay for another subscription that fits more to your usage. To fix that problem I've build a dashboard which uses all the information available trough the invoices my current company (T-mobile) provides in a PDF. (FYI, I got a version running that's also working with receipts from Vodafone)</description>
</item>
<item>
<title>Building a Fitbit organisation dashboard</title>
<link>http://jplattel.nl/post/2013-08-15-fitbit-organisation-dashboard/</link>
<pubDate>Thu, 15 Aug 2013 18:54:46 +0200</pubDate>
<guid>http://jplattel.nl/post/2013-08-15-fitbit-organisation-dashboard/</guid>
<description>The Fitbit (affiliate link) is one of the best tools for activity tracking.The interface is nice and the hardware is durable and syncs wirelessly. For a personal level is good, but using group-wise or equipping all employees with a Fitbit turns out to be non-existent.
During the past few days I've spend some time building a dashboard that lets people see the data from all users within a group. It gets all data trough the Fitbit API and summarizes it into a view per day/week/month.</description>
</item>
</channel>
</rss> | {'content_hash': '58cc261b6f4e2ee498b3d45891b6346c', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 473, 'avg_line_length': 71.93846153846154, 'alnum_prop': 0.7230538922155688, 'repo_name': 'jplattel/jplattel.github.io', 'id': 'cefae95719fd0d61f833ab647a089a5013eb4073', 'size': '4676', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/tags/dashboard/index.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '29686'}, {'name': 'HTML', 'bytes': '370052'}, {'name': 'JavaScript', 'bytes': '11674'}, {'name': 'Shell', 'bytes': '358'}, {'name': 'TeX', 'bytes': '254'}]} |
/* @flow */
import { REHYDRATE } from 'redux-persist/constants';
import type { NavigationState, Action } from '../types';
import { navigateToAccountPicker, navigateToAuth } from './navActions';
import { getStateForRoute, getInitialRoute } from './navSelectors';
import AppNavigator from './AppNavigator';
import {
RESET_NAVIGATION,
INITIAL_FETCH_COMPLETE,
ACCOUNT_SWITCH,
SET_AUTH_TYPE,
LOGIN_SUCCESS,
LOGOUT,
} from '../actionConstants';
export default (
state: NavigationState = getStateForRoute('realm'),
action: Action,
): NavigationState => {
switch (action.type) {
case REHYDRATE:
return getStateForRoute(getInitialRoute(action.payload));
case RESET_NAVIGATION:
case ACCOUNT_SWITCH:
return getStateForRoute(getInitialRoute(state));
case SET_AUTH_TYPE: {
return AppNavigator.router.getStateForAction(navigateToAuth(action.authType), state);
}
case LOGIN_SUCCESS:
case INITIAL_FETCH_COMPLETE:
return getStateForRoute('main');
case LOGOUT: {
return AppNavigator.router.getStateForAction(navigateToAccountPicker(), state);
}
default:
return AppNavigator.router.getStateForAction(action, state);
}
};
| {'content_hash': '19794c2ccbdafe85eae9401a059b890d', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 91, 'avg_line_length': 30.76923076923077, 'alnum_prop': 0.7175, 'repo_name': 'Sam1301/zulip-mobile', 'id': '954cb02aa9adcaab0596f256c47b140955a68fac', 'size': '1200', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/nav/navReducers.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '67421'}, {'name': 'Java', 'bytes': '51739'}, {'name': 'JavaScript', 'bytes': '514683'}, {'name': 'Objective-C', 'bytes': '20886'}, {'name': 'Python', 'bytes': '1508'}, {'name': 'Ruby', 'bytes': '383'}, {'name': 'Shell', 'bytes': '18106'}]} |
define(
({
viewer: {
common: {
close: "Fermer"
},
loading: {
step1: "Chargement du récit",
step2: "Chargement des données",
step3: "Initialisation",
loadBuilder: "Accéder au générateur",
long: "Le journal cartographique est en cours d\'initialisation",
long2: "Merci de patienter",
failButton: "Recharger le récit"
},
signin: {
title: "L\'authentification est nécessaire",
explainViewer: "Connectez-vous avec un compte sur %PORTAL_LINK% pour accéder au récit.",
explainBuilder: "Connectez-vous avec un compte sur %PORTAL_LINK% pour configurer le récit."
},
errors: {
boxTitle: "Une erreur s\’est produite",
invalidConfig: "Configuration non valide",
invalidConfigNoApp: "Identifiant de l\'application de cartographie Web non spécifié dans index.html.",
invalidConfigNoAppDev: "Aucun identifiant d\'application cartographique Web n\'est spécifié dans les paramètres de l\'URL (?appid=). En mode de développement, la configuration d\'appid dans index.html est ignorée.",
unspecifiedConfigOwner: "Le propriétaire autorisé n\'est pas configuré.",
invalidConfigOwner: "Le propriétaire du récit n\'est pas autorisé.",
createMap: "Impossible de créer la carte",
invalidApp: "Le %TPL_NAME% n\'existe pas ou n\'est pas accessible.",
appLoadingFail: "Une erreur s\'est produite et le chargement de %TPL_NAME% ne s\'est pas correctement déroulé.",
notConfiguredDesktop: "Le récit n\'est pas encore configuré.",
notConfiguredMobile: "Le générateur %TPL_NAME% n\'est pas pris en charge avec cette taille d\'affichage. Si possible, redimensionnez votre navigateur pour pouvoir accéder au générateur ou élaborez votre récit sur un appareil doté d\'un écran plus grand.",
notConfiguredMobile2: "Veuillez tourner votre appareil en orientation paysage pour utiliser le générateur %TPL_NAME%.",
notAuthorized: "Vous n\'êtes pas autorisé à accéder à ce récit.",
notAuthorizedBuilder: "Vous n\'êtes pas autorisé à utiliser le générateur %TPL_NAME%.",
noBuilderIE: "Le générateur n\'est pas pris en charge dans Internet Explorer avant la version %VERSION%. %UPGRADE%",
noViewerIE: "Ce récit n\'est pas pris en charge dans Internet Explorer avant la version %VERSION%. %UPGRADE%",
upgradeBrowser: "<a href='http://browsehappy.com/' target='_blank'>Mettez votre navigateur à jour</a>.",
mapLoadingFail: "Une erreur s\'est produite et la carte n\'a pas été correctement chargée.",
signOut: "Se déconnecter"
},
mobileView: {
tapForDetails: "Touchez pour obtenir des détails",
clickForDetails: "En savoir plus",
swipeToExplore: "Effectuez un mouvement de balayage pour explorer",
tapForMap: "Touchez pour revenir à la carte",
clickForMap: "RETOUR A LA CARTE"
},
floatLayout: {
scroll: "Défilement"
},
sideLayout: {
scroll: "Faites défiler pour en savoir plus !"
},
mainStage: {
back: "Retour"
},
headerFromCommon: {
storymapsText: "Une Story Map",
builderButton: "Modifier",
facebookTooltip: "Partager sur Facebook",
twitterTooltip: "Partager sur Twitter",
bitlyTooltip: "Obtenir un lien court",
templateTitle: "Définir le titre du modèle",
templateSubtitle: "Définir le sous-titre du modèle",
share: "Partager",
checking: "Vérification du contenu de votre récit",
fix: "Résoudre les problèmes du récit",
noerrors: "Aucun problème détecté",
tooltipAutoplayDisabled: "Ceci n\'est pas disponible en mode de lecture automatique",
notshared: "Récit non partagé"
},
overviewFromCommon: {
title: "Vue générale"
},
legendFromCommon: {
title: "Légende"
},
shareFromCommon: {
copy: "Copier",
copied: "Copié",
open: "Ouvrir",
embed: "Incorporer dans une page Web",
embedExplain: "Utilisez le code HTML suivant pour incorporer le journal dans une page Web.",
size: "Taille (largeur/hauteur) :",
autoplayLabel: "Mode de lecture automatique",
autoplayExplain1: "Le mode de lecture automatique fait avancer votre récit à intervalle régulier. Il est idéal pour les écrans publics, mais, dans d\'autres cas, il peut compliquer la lecture du récit. Cette fonctionnalité n\'est pas prise en charge sur les petits écrans.",
autoplayExplain2: "Lorsque ce mode est actif, vous disposez de contrôles pour lire le récit ou le mettre en pause, ainsi que régler la vitesse de navigation.",
linksupdated: "Liens mis à jour"
}
}
})
); | {'content_hash': '357457752910a8246d41675bebf812c9', 'timestamp': '', 'source': 'github', 'line_count': 93, 'max_line_length': 278, 'avg_line_length': 49.60215053763441, 'alnum_prop': 0.693258183394754, 'repo_name': 'blueraster/UNICEF-Climate-Change', 'id': '506557216d9ec217827d47f1433780ef5538c505', 'size': '4711', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'resources/tpl/viewer/nls/fr/template.js', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '15727'}, {'name': 'HTML', 'bytes': '26627'}, {'name': 'JavaScript', 'bytes': '921604'}]} |
package org.pentaho.di.trans.steps.singlethreader;
import java.util.ArrayList;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.logging.KettleLogStore;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.SingleThreadedTransExecutor;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.TransMeta.TransformationType;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.RowAdapter;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.steps.mapping.MappingValueRename;
import org.pentaho.di.trans.steps.mappinginput.MappingInputData;
/**
* Execute a mapping: a re-usuable transformation
*
* @author Matt
* @since 22-nov-2005
*/
public class SingleThreader extends BaseStep implements StepInterface {
private static Class<?> PKG = SingleThreaderMeta.class; // for i18n purposes, needed by Translator2!!
private SingleThreaderMeta meta;
private SingleThreaderData data;
public SingleThreader( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta,
Trans trans ) {
super( stepMeta, stepDataInterface, copyNr, transMeta, trans );
}
/**
* Process rows in batches of N rows. The sub-transformation will execute in a single thread.
*/
public boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException {
meta = (SingleThreaderMeta) smi;
data = (SingleThreaderData) sdi;
Object[] row = getRow();
if ( row == null ) {
if ( data.batchCount > 0 ) {
data.batchCount = 0;
return execOneIteration();
}
setOutputDone();
return false;
}
if ( first ) {
first = false;
data.startTime = System.currentTimeMillis();
}
// Add the row to the producer...
//
data.rowProducer.putRow( getInputRowMeta(), row );
data.batchCount++;
if ( getStepMeta().isDoingErrorHandling() ) {
data.errorBuffer.add( row );
}
boolean countWindow = data.batchSize > 0 && data.batchCount >= data.batchSize;
boolean timeWindow = data.batchTime > 0 && ( System.currentTimeMillis() - data.startTime ) > data.batchTime;
if ( countWindow || timeWindow ) {
data.batchCount = 0;
boolean more = execOneIteration();
if ( !more ) {
setOutputDone();
return false;
}
data.startTime = System.currentTimeMillis();
}
return true;
}
private boolean execOneIteration() {
boolean more = false;
try {
more = data.executor.oneIteration();
if ( data.executor.isStopped() || data.executor.getErrors() > 0 ) {
return handleError();
}
} catch ( Exception e ) {
setErrors( 1L );
stopAll();
logError( BaseMessages.getString( PKG, "SingleThreader.Log.ErrorOccurredInSubTransformation" ) );
return false;
} finally {
if ( getStepMeta().isDoingErrorHandling() ) {
data.errorBuffer.clear();
}
}
return more;
}
private boolean handleError() throws KettleStepException {
if ( getStepMeta().isDoingErrorHandling() ) {
int lastLogLine = KettleLogStore.getLastBufferLineNr();
StringBuffer logText =
KettleLogStore.getAppender().getBuffer( data.mappingTrans.getLogChannelId(), false, data.lastLogLine );
data.lastLogLine = lastLogLine;
for ( Object[] row : data.errorBuffer ) {
putError( getInputRowMeta(), row, 1L, logText.toString(), null, "STR-001" );
}
data.executor.clearError();
return true; // continue
} else {
setErrors( 1 );
stopAll();
logError( BaseMessages.getString( PKG, "SingleThreader.Log.ErrorOccurredInSubTransformation" ) );
return false; // stop running
}
}
private void passParameters() throws KettleException {
String[] parameters;
String[] parameterValues;
if ( meta.isPassingAllParameters() ) {
// We pass the values for all the parameters from the parent transformation
//
parameters = data.mappingTransMeta.listParameters();
parameterValues = new String[parameters.length];
for ( int i = 0; i < parameters.length; i++ ) {
parameterValues[i] = getVariable( parameters[i] );
}
} else {
// We pass down the listed variables with the specified values...
//
parameters = meta.getParameters();
parameterValues = new String[parameters.length];
for ( int i = 0; i < parameters.length; i++ ) {
parameterValues[i] = environmentSubstitute( meta.getParameterValues()[i] );
}
}
for ( int i = 0; i < parameters.length; i++ ) {
String value = Const.NVL( parameterValues[i], "" );
data.mappingTrans.setParameterValue( parameters[i], value );
}
data.mappingTrans.activateParameters();
}
public void prepareMappingExecution() throws KettleException {
// Set the type to single threaded in case the user forgot...
//
data.mappingTransMeta.setTransformationType( TransformationType.SingleThreaded );
// Create the transformation from meta-data...
//
data.mappingTrans = new Trans( data.mappingTransMeta, getTrans() );
// Pass the parameters down to the sub-transformation.
//
passParameters();
// Disable thread priority managment as it will slow things down needlessly.
// The single threaded engine doesn't use threads and doesn't need row locking.
//
data.mappingTrans.getTransMeta().setUsingThreadPriorityManagment( false );
// Leave a path up so that we can set variables in sub-transformations...
//
data.mappingTrans.setParentTrans( getTrans() );
// Pass down the safe mode flag to the mapping...
//
data.mappingTrans.setSafeModeEnabled( getTrans().isSafeModeEnabled() );
// Pass down the metrics gathering flag to the mapping...
//
data.mappingTrans.setGatheringMetrics( getTrans().isGatheringMetrics() );
// Also set the name of this step in the mapping transformation for logging purposes
//
data.mappingTrans.setMappingStepName( getStepname() );
// Pass the servlet print writer
//
data.mappingTrans.setServletPrintWriter( getTrans().getServletPrintWriter() );
data.mappingTrans.setServletReponse( getTrans().getServletResponse() );
data.mappingTrans.setServletRequest( getTrans().getServletRequest() );
// prepare the execution
//
data.mappingTrans.prepareExecution( null );
// If the inject step is a mapping input step, tell it all is OK...
//
if ( data.injectStepMeta.isMappingInput() ) {
MappingInputData mappingInputData =
(MappingInputData) data.mappingTrans.findDataInterface( data.injectStepMeta.getName() );
mappingInputData.sourceSteps = new StepInterface[0];
mappingInputData.valueRenames = new ArrayList<MappingValueRename>();
}
// Add row producer & row listener
//
data.rowProducer = data.mappingTrans.addRowProducer( meta.getInjectStep(), 0 );
StepInterface retrieveStep = data.mappingTrans.getStepInterface( meta.getRetrieveStep(), 0 );
retrieveStep.addRowListener( new RowAdapter() {
@Override
public void rowWrittenEvent( RowMetaInterface rowMeta, Object[] row ) throws KettleStepException {
// Simply pass it along to the next steps after the SingleThreader
//
SingleThreader.this.putRow( rowMeta, row );
}
} );
data.mappingTrans.startThreads();
// Create the executor...
//
data.executor = new SingleThreadedTransExecutor( data.mappingTrans );
// We launch the transformation in the processRow when the first row is received.
// This will allow the correct variables to be passed.
// Otherwise the parent is the init() thread which will be gone once the init is done.
//
try {
boolean ok = data.executor.init();
if ( !ok ) {
throw new KettleException( BaseMessages.getString(
PKG, "SingleThreader.Exception.UnableToInitSingleThreadedTransformation" ) );
}
} catch ( KettleException e ) {
throw new KettleException( BaseMessages.getString(
PKG, "SingleThreader.Exception.UnableToPrepareExecutionOfMapping" ), e );
}
// Add the mapping transformation to the active sub-transformations map in the parent transformation
//
getTrans().getActiveSubtransformations().put( getStepname(), data.mappingTrans );
}
public boolean init( StepMetaInterface smi, StepDataInterface sdi ) {
meta = (SingleThreaderMeta) smi;
data = (SingleThreaderData) sdi;
if ( super.init( smi, sdi ) ) {
// First we need to load the mapping (transformation)
try {
// The batch size...
//
data.batchSize = Const.toInt( environmentSubstitute( meta.getBatchSize() ), 0 );
data.batchTime = Const.toInt( environmentSubstitute( meta.getBatchTime() ), 0 );
// Pass the repository down to the metadata object...
//
meta.setRepository( getTransMeta().getRepository() );
data.mappingTransMeta = SingleThreaderMeta.loadSingleThreadedTransMeta( meta, meta.getRepository(), this );
if ( data.mappingTransMeta != null ) { // Do we have a mapping at all?
// Validate the inject and retrieve step names
//
String injectStepName = environmentSubstitute( meta.getInjectStep() );
data.injectStepMeta = data.mappingTransMeta.findStep( injectStepName );
if ( data.injectStepMeta == null ) {
logError( "The inject step with name '"
+ injectStepName + "' couldn't be found in the sub-transformation" );
}
String retrieveStepName = environmentSubstitute( meta.getRetrieveStep() );
if ( !Const.isEmpty( retrieveStepName ) ) {
data.retrieveStepMeta = data.mappingTransMeta.findStep( retrieveStepName );
if ( data.retrieveStepMeta == null ) {
logError( "The retrieve step with name '"
+ retrieveStepName + "' couldn't be found in the sub-transformation" );
}
}
// OK, now prepare the execution of the mapping.
// This includes the allocation of RowSet buffers, the creation of the
// sub-transformation threads, etc.
//
prepareMappingExecution();
if ( getStepMeta().isDoingErrorHandling() ) {
data.errorBuffer = new ArrayList<Object[]>();
}
// That's all for now...
//
return true;
} else {
logError( "No valid mapping was specified!" );
return false;
}
} catch ( Exception e ) {
logError( "Unable to load the mapping transformation because of an error : " + e.toString() );
logError( Const.getStackTracker( e ) );
}
}
return false;
}
public void dispose( StepMetaInterface smi, StepDataInterface sdi ) {
// dispose of the single threading execution engine
//
try {
data.executor.dispose();
} catch ( KettleException e ) {
log.logError( "Error disposing of sub-transformation: ", e );
}
super.dispose( smi, sdi );
}
public void stopRunning( StepMetaInterface stepMetaInterface, StepDataInterface stepDataInterface ) throws KettleException {
if ( data.mappingTrans != null ) {
data.mappingTrans.stopAll();
}
}
public void stopAll() {
// Stop the mapping step.
if ( data.mappingTrans != null ) {
data.mappingTrans.stopAll();
}
// Also stop this step
super.stopAll();
}
public Trans getMappingTrans() {
return data.mappingTrans;
}
}
| {'content_hash': 'a69c7761238e2b8f02db507ce0316ac8', 'timestamp': '', 'source': 'github', 'line_count': 353, 'max_line_length': 126, 'avg_line_length': 34.09915014164306, 'alnum_prop': 0.6651989698429841, 'repo_name': 'AndreyBurikhin/pentaho-kettle', 'id': 'dbcf7d844a6f389f80535e4638239c4f783c04a7', 'size': '12941', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'engine/src/org/pentaho/di/trans/steps/singlethreader/SingleThreader.java', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
package com.google.security.zynamics.binnavi.debug.connection.packets.arguments;
/**
* Class that can be used to add integer values to debug message arguments.
*/
public final class DebugMessageIntegerArgument extends DebugMessageArgument {
/**
* Creates a new integer debug argument.
*
* @param value Value of the integer argument.
*/
public DebugMessageIntegerArgument(final int value) {
super(DebugArgumentType.INTEGER);
appendInt(value);
}
}
| {'content_hash': 'ce74b14f8ffb1b72b5dc8431aa3e623b', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 80, 'avg_line_length': 28.0, 'alnum_prop': 0.7436974789915967, 'repo_name': 'AmesianX/binnavi', 'id': '78522be919828330596f99e1831ac8bb1704c05a', 'size': '1059', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/google/security/zynamics/binnavi/debug/connection/packets/arguments/DebugMessageIntegerArgument.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '1479'}, {'name': 'C++', 'bytes': '1876'}, {'name': 'CSS', 'bytes': '12843'}, {'name': 'GAP', 'bytes': '3637'}, {'name': 'HTML', 'bytes': '437420'}, {'name': 'Java', 'bytes': '21671316'}, {'name': 'PLSQL', 'bytes': '1866504'}, {'name': 'PLpgSQL', 'bytes': '638893'}, {'name': 'Python', 'bytes': '23981'}, {'name': 'SQLPL', 'bytes': '330046'}, {'name': 'Shell', 'bytes': '708'}]} |
/*
###
# # ######### _______ _ _ ______ _ _
## ######## @ ## |______ | | | ____ | |
################## | |_____| |_____| |_____|
## ############# f r a m e w o r k
# # #########
###
(c) 2015 - 2018 FUGU framework project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
namespace Fugu.Localization.Tool
{
public class LanguageOptions
{
public String Input { get; set; }
public String[] Output { get; set; }
}
}
| {'content_hash': 'addc912d13637cbe34452653fd3a2a75', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 72, 'avg_line_length': 27.833333333333332, 'alnum_prop': 0.5658682634730539, 'repo_name': 'FUGU-framework/Fugu', 'id': '20697a41d5e0d762a7bd99940ebd24548a2c0e83', 'size': '1004', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Fugu.Localization.Tool/LanguageOptions.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '1351511'}, {'name': 'PowerShell', 'bytes': '2560'}]} |
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2011 BiGCaT Bioinformatics
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Tokenizer for SVG path expressions.
*/
class Tokenizer
{
private String s;
private String newS; // new string after token is eaten
Token nextToken;
public Tokenizer (String as) throws PathParseException
{
s = as;
nextToken = tokenize();
}
/**
returns the next token and moves ahead in the string
*/
public Token eat () throws PathParseException
{
Token result = nextToken;
s = newS;
nextToken = tokenize();
return result;
}
/**
Returns the next token without moving ahead in the string
*/
public Token lookAt ()
{
return nextToken;
}
private static final String VALID_COMMANDS = "MmZzLlHhVvCcSsQqTtAa";
/**
returns the upcoming token, while setting newS to the string after the token.
*/
private Token tokenize () throws PathParseException
{
Pattern commaWsp = Pattern.compile ("\\s*,\\s*");
Pattern wsp = Pattern.compile ("\\s+");
Pattern floatWithExponent = Pattern.compile ("[+-]?(\\.\\d+|\\d+\\.?\\d*)([eE][+-]?\\d+)");
Pattern floatWithoutExponent = Pattern.compile ("[+-]?(\\d+\\.\\d*|\\d*\\.\\d+)");
Pattern intConstant = Pattern.compile ("[+-]?\\d+");
Pattern command = Pattern.compile ("[" + VALID_COMMANDS + "]");
if (s == null || s.equals (""))
{
return new Token (Token.F_END);
}
Matcher m = commaWsp.matcher (s);
if (m.lookingAt())
{
newS = s.substring (m.end());
return (new Token (Token.F_WHITESPACE_OR_COMMA | Token.F_COMMA));
}
m.usePattern (wsp);
if (m.lookingAt())
{
newS = s.substring (m.end());
return (new Token (Token.F_WHITESPACE_OR_COMMA | Token.F_WHITESPACE));
}
m.usePattern (floatWithoutExponent);
if (m.lookingAt())
{
newS = s.substring (m.end());
return new Token (
Token.F_NUMBER | Token.F_DOUBLE,
Double.parseDouble(m.group())
);
}
m.usePattern (floatWithExponent);
if (m.lookingAt())
{
newS = s.substring (m.end());
return new Token (
Token.F_NUMBER | Token.F_DOUBLE,
Double.parseDouble(m.group())
);
}
m.usePattern (intConstant);
if (m.lookingAt())
{
newS = s.substring (m.end());
int value = Integer.parseInt (m.group());
return new Token (
Token.F_NUMBER | Token.F_NOT_DOUBLE | ((value == 0 || value == 1) ? Token.F_FLAG : 0),
value
);
}
m.usePattern(command);
if (m.lookingAt())
{
newS = s.substring (m.end());
return new Token (m.group().charAt(0));
}
throw new PathParseException ("Parse error: unknown Token");
}
}
| {'content_hash': 'b41be70d0009fd28b650bcc1c47b6af8', 'timestamp': '', 'source': 'github', 'line_count': 127, 'max_line_length': 93, 'avg_line_length': 25.37795275590551, 'alnum_prop': 0.6524976729754887, 'repo_name': 'egonw/pathvisio', 'id': '3c4905b2ab0f3f3f1033f613a6685c13b28a8d6d', 'size': '3223', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'tools/path2java/src/Tokenizer.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '52'}, {'name': 'CSS', 'bytes': '390'}, {'name': 'HTML', 'bytes': '28275'}, {'name': 'Inno Setup', 'bytes': '2290'}, {'name': 'Java', 'bytes': '2465720'}, {'name': 'JavaScript', 'bytes': '16917'}, {'name': 'Perl', 'bytes': '588'}, {'name': 'Shell', 'bytes': '13207'}]} |
#include "FlattenBrush.h"
//-------------------------------------------------------------------------------------------------
FlattenBrush::FlattenBrush()
{
pCurAction = nullptr;
}
//-------------------------------------------------------------------------------------------------
FlattenBrush::~FlattenBrush() {}
//-------------------------------------------------------------------------------------------------
bool
FlattenBrush::beginPaint()
{
pCurAction = new ActionPaintTile();
return true;
}
//-------------------------------------------------------------------------------------------------
Action*
FlattenBrush::endPaint()
{
ActionPaintTile* pRetAction = pCurAction;
if (pCurAction)
{
if (!pCurAction->vertexInfoList.Count())
{
delete pCurAction;
pRetAction = nullptr;
}
}
// land->reCalcLight();
land->recalcWater();
pCurAction = nullptr;
return pRetAction;
}
//-------------------------------------------------------------------------------------------------
bool
FlattenBrush::paint(Stuff::Vector3D& worldPos, int32_t screenX, int32_t screenY)
{
int32_t closestX = floor((worldPos.x - land->mapTopLeft3d.x) / land->worldUnitsPerVertex + .5);
int32_t closestY = floor((land->mapTopLeft3d.y - worldPos.y) / land->worldUnitsPerVertex + .5);
float height = 0.f;
float viable = 0.f;
for (size_t i = closestX - 1; i < closestX + 2; ++i)
{
for (size_t j = closestY - 1; j < closestY + 2; ++j)
{
if (j < land->realVerticesMapSide && j > -1 && i < land->realVerticesMapSide && i > -1)
{
height += land->getTerrainElevation(j, i);
viable += 1.0f;
}
}
}
height /= viable;
if (closestY > -1 && closestY < land->realVerticesMapSide && closestX < land->realVerticesMapSide && closestX > -1)
flattenVertex(closestY, closestX, height);
return true;
}
//-------------------------------------------------------------------------------------------------
Action*
FlattenBrush::applyToSelection()
{
float height = getAverageheightOfSelection();
return applyheightToSelection(height);
}
//-------------------------------------------------------------------------------------------------
float
FlattenBrush::getAverageheightOfSelection()
{
float height = 0.f;
float count = 0.0f;
for (size_t j = 0; j < land->realVerticesMapSide; ++j)
{
for (size_t i = 0; i < land->realVerticesMapSide; ++i)
{
if (land->isVertexSelected(j, i))
{
count += 1.f;
height += land->getTerrainElevation(j, i);
}
}
}
height /= count;
return height;
}
//-------------------------------------------------------------------------------------------------
Action*
FlattenBrush::applyheightToSelection(float height)
{
beginPaint();
for (size_t j = 0; j < land->realVerticesMapSide; ++j)
{
for (size_t i = 0; i < land->realVerticesMapSide; ++i)
{
if (land->isVertexSelected(j, i))
{
flattenVertex(j, i, height);
}
}
}
return endPaint();
}
//-------------------------------------------------------------------------------------------------
void
FlattenBrush::flattenVertex(int32_t row, int32_t col, float val)
{
#if 1 /*flattening without "area effect"*/
{
int32_t i = col;
int32_t j = row;
if (i > -1 && i < land->realVerticesMapSide && j > -1 && j < land->realVerticesMapSide)
{
pCurAction->addChangedVertexInfo(j, i);
land->setVertexheight(j * land->realVerticesMapSide + i, val);
}
}
#else /*flattening without "area effect"*/
for (size_t i = col - 1; i < col + 2; ++i)
{
for (size_t j = row - 1; j < row + 2; ++j)
{
if (i > -1 && i < land->realVerticesMapSide && j > -1 && j < land->realVerticesMapSide)
{
pCurAction->addChangedVertexInfo(j, i);
land->setVertexheight(j * land->realVerticesMapSide + i, val);
}
}
}
#endif /*flattening without "area effect"*/
}
// end of file ( FlattenBrush.cpp )
| {'content_hash': '73c1cd3344edbb01a07f938370007438', 'timestamp': '', 'source': 'github', 'line_count': 142, 'max_line_length': 116, 'avg_line_length': 26.964788732394368, 'alnum_prop': 0.4933402977278663, 'repo_name': 'mechasource/mechcommander2', 'id': '1e2ac93f58d5c4973742768e25bfcbac20f1971a', 'size': '4335', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'source/tools/editor/flattenbrush.cpp', 'mode': '33261', 'license': 'bsd-2-clause', 'language': [{'name': 'Batchfile', 'bytes': '4848'}, {'name': 'C', 'bytes': '499088'}, {'name': 'C++', 'bytes': '12057913'}, {'name': 'CMake', 'bytes': '37250'}, {'name': 'Objective-C', 'bytes': '7354'}, {'name': 'PHP', 'bytes': '7506'}, {'name': 'Rich Text Format', 'bytes': '22446'}, {'name': 'Shell', 'bytes': '853'}]} |
<?xml version="1.0" encoding="UTF-8" ?>
<!--
Copyright (c) 2011 International Business Machines Corporation and others. All rights reserved.
-->
<!DOCTYPE ldml SYSTEM "http://www.unicode.org/repos/cldr/trunk/common/dtd/ldml.dtd"
[
<!ENTITY % icu SYSTEM "http://www.unicode.org/repos/cldr/trunk/common/dtd/ldmlICU.dtd">
%icu;
]
>
<ldml>
<identity>
<version number="$Revision: 30037 $"/>
<generation date="$Date: 2011-05-05 11:12:27 -0700 (Thu, 05 May 2011) $"/>
<language type="mua"/>
</identity>
<characters>
<special xmlns:icu="http://www.icu-project.org/">
<icu:scripts>
<icu:script type="1">Latn</icu:script>
</icu:scripts>
</special>
</characters>
</ldml>
| {'content_hash': '4a756e8a378259df4d174a39fc6cbc25', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 96, 'avg_line_length': 27.72, 'alnum_prop': 0.6608946608946609, 'repo_name': 'indashnet/InDashNet.Open.UN2000', 'id': '53ad477ae07942b773e846fd6a0b6582028d2671', 'size': '693', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'android/external/icu4c/data/xml/main/mua.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
<!-- <div ng-controller="ChatCtrl">
<div ng-view="ChatCtrl"></div>
</div> -->
<h2>Playlist</h2>
<md-autocomplete
md-selected-item="selectedItem"
md-search-text-change="searchTextChange(searchText)"
md-search-text="searchText"
md-selected-item-change="selectedItemChange(item)"
md-items="item in querySearch(searchText)"
md-item-text="item.title"
md-min-length="0"
placeholder="Search YouTube"
md-menu-class="autocomplete-custom-template">
<md-item-template>
<div class="media">
<div class="media-left">
<img ng-src="http://i1.ytimg.com/vi/{{item.ytid}}/mqdefault.jpg" height='50'/>
</div>
<div class="media-body">
<h4> {{item.title}} </h4>
<!-- <p> {{item.summary}} </p> -->
</div>
</div>
</md-item-template>
</md-autocomplete>
<ul id="playlist" class="media-list" ng-show="playlist.length">
<li ng-repeat="track in playlist" class="media">
<div class="media-left media-middle">
<img ng-src="http://i1.ytimg.com/vi/{{track.ytid}}/mqdefault.jpg" height='100'/>
</div>
<div class="media-body">
<h4 class="media-heading">{{track.title}}</h4>
<p>{{track.summary}}</p>
<p>Added by {{track.username}}</p>
</div>
<div class="media-right media-middle">
<span ng-click="removeTrack(track.ytid);" class="glyphicon glyphicon-remove"></span>
</div>
</li>
</ul>
<div class="alert alert-info" ng-hide="playlist.length">There is nothing in the playlist</div>
| {'content_hash': '278edbe5866451e28f049a512de3d46b', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 94, 'avg_line_length': 31.065217391304348, 'alnum_prop': 0.6529041287613716, 'repo_name': 'thenarruc/team-dj', 'id': '6c3c12906ddc8836e4383a0f3850114c1912adf2', 'size': '1429', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/views/playlist.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '24139'}, {'name': 'CSS', 'bytes': '1596'}, {'name': 'HTML', 'bytes': '19303'}, {'name': 'JavaScript', 'bytes': '47415'}]} |
.class public Landroid/graphics/RadialGradient;
.super Landroid/graphics/Shader;
.source "RadialGradient.java"
# static fields
.field private static final TYPE_COLORS_AND_POSITIONS:I = 0x1
.field private static final TYPE_COLOR_CENTER_AND_COLOR_EDGE:I = 0x2
# instance fields
.field private mCenterColor:I
.field private mColors:[I
.field private mEdgeColor:I
.field private mPositions:[F
.field private mRadius:F
.field private mTileMode:Landroid/graphics/Shader$TileMode;
.field private mType:I
.field private mX:F
.field private mY:F
# direct methods
.method public constructor <init>(FFFIILandroid/graphics/Shader$TileMode;)V
.locals 2
invoke-direct {p0}, Landroid/graphics/Shader;-><init>()V
const/4 v0, 0x0
cmpg-float v0, p3, v0
if-gtz v0, :cond_0
new-instance v0, Ljava/lang/IllegalArgumentException;
const-string/jumbo v1, "radius must be > 0"
invoke-direct {v0, v1}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V
throw v0
:cond_0
const/4 v0, 0x2
iput v0, p0, Landroid/graphics/RadialGradient;->mType:I
iput p1, p0, Landroid/graphics/RadialGradient;->mX:F
iput p2, p0, Landroid/graphics/RadialGradient;->mY:F
iput p3, p0, Landroid/graphics/RadialGradient;->mRadius:F
iput p4, p0, Landroid/graphics/RadialGradient;->mCenterColor:I
iput p5, p0, Landroid/graphics/RadialGradient;->mEdgeColor:I
iput-object p6, p0, Landroid/graphics/RadialGradient;->mTileMode:Landroid/graphics/Shader$TileMode;
return-void
.end method
.method public constructor <init>(FFF[I[FLandroid/graphics/Shader$TileMode;)V
.locals 3
const/4 v1, 0x0
invoke-direct {p0}, Landroid/graphics/Shader;-><init>()V
const/4 v0, 0x0
cmpg-float v0, p3, v0
if-gtz v0, :cond_0
new-instance v0, Ljava/lang/IllegalArgumentException;
const-string/jumbo v1, "radius must be > 0"
invoke-direct {v0, v1}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V
throw v0
:cond_0
array-length v0, p4
const/4 v2, 0x2
if-ge v0, v2, :cond_1
new-instance v0, Ljava/lang/IllegalArgumentException;
const-string/jumbo v1, "needs >= 2 number of colors"
invoke-direct {v0, v1}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V
throw v0
:cond_1
if-eqz p5, :cond_2
array-length v0, p4
array-length v2, p5
if-eq v0, v2, :cond_2
new-instance v0, Ljava/lang/IllegalArgumentException;
const-string/jumbo v1, "color and position arrays must be of equal length"
invoke-direct {v0, v1}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V
throw v0
:cond_2
const/4 v0, 0x1
iput v0, p0, Landroid/graphics/RadialGradient;->mType:I
iput p1, p0, Landroid/graphics/RadialGradient;->mX:F
iput p2, p0, Landroid/graphics/RadialGradient;->mY:F
iput p3, p0, Landroid/graphics/RadialGradient;->mRadius:F
invoke-virtual {p4}, Ljava/lang/Object;->clone()Ljava/lang/Object;
move-result-object v0
check-cast v0, [I
iput-object v0, p0, Landroid/graphics/RadialGradient;->mColors:[I
if-eqz p5, :cond_3
invoke-virtual {p5}, Ljava/lang/Object;->clone()Ljava/lang/Object;
move-result-object v0
check-cast v0, [F
:goto_0
iput-object v0, p0, Landroid/graphics/RadialGradient;->mPositions:[F
iput-object p6, p0, Landroid/graphics/RadialGradient;->mTileMode:Landroid/graphics/Shader$TileMode;
return-void
:cond_3
move-object v0, v1
goto :goto_0
.end method
.method private static native nativeCreate1(JFFF[I[FI)J
.end method
.method private static native nativeCreate2(JFFFIII)J
.end method
# virtual methods
.method protected copy()Landroid/graphics/Shader;
.locals 7
const/4 v5, 0x0
iget v1, p0, Landroid/graphics/RadialGradient;->mType:I
const/4 v2, 0x1
if-ne v1, v2, :cond_1
new-instance v0, Landroid/graphics/RadialGradient;
iget v1, p0, Landroid/graphics/RadialGradient;->mX:F
iget v2, p0, Landroid/graphics/RadialGradient;->mY:F
iget v3, p0, Landroid/graphics/RadialGradient;->mRadius:F
iget-object v4, p0, Landroid/graphics/RadialGradient;->mColors:[I
invoke-virtual {v4}, Ljava/lang/Object;->clone()Ljava/lang/Object;
move-result-object v4
check-cast v4, [I
iget-object v6, p0, Landroid/graphics/RadialGradient;->mPositions:[F
if-eqz v6, :cond_0
iget-object v5, p0, Landroid/graphics/RadialGradient;->mPositions:[F
invoke-virtual {v5}, Ljava/lang/Object;->clone()Ljava/lang/Object;
move-result-object v5
check-cast v5, [F
:cond_0
iget-object v6, p0, Landroid/graphics/RadialGradient;->mTileMode:Landroid/graphics/Shader$TileMode;
invoke-direct/range {v0 .. v6}, Landroid/graphics/RadialGradient;-><init>(FFF[I[FLandroid/graphics/Shader$TileMode;)V
:goto_0
invoke-virtual {p0, v0}, Landroid/graphics/RadialGradient;->copyLocalMatrix(Landroid/graphics/Shader;)V
return-object v0
:cond_1
new-instance v0, Landroid/graphics/RadialGradient;
iget v1, p0, Landroid/graphics/RadialGradient;->mX:F
iget v2, p0, Landroid/graphics/RadialGradient;->mY:F
iget v3, p0, Landroid/graphics/RadialGradient;->mRadius:F
iget v4, p0, Landroid/graphics/RadialGradient;->mCenterColor:I
iget v5, p0, Landroid/graphics/RadialGradient;->mEdgeColor:I
iget-object v6, p0, Landroid/graphics/RadialGradient;->mTileMode:Landroid/graphics/Shader$TileMode;
invoke-direct/range {v0 .. v6}, Landroid/graphics/RadialGradient;-><init>(FFFIILandroid/graphics/Shader$TileMode;)V
goto :goto_0
.end method
.method createNativeInstance(J)J
.locals 9
iget v0, p0, Landroid/graphics/RadialGradient;->mType:I
const/4 v1, 0x1
if-ne v0, v1, :cond_0
iget v2, p0, Landroid/graphics/RadialGradient;->mX:F
iget v3, p0, Landroid/graphics/RadialGradient;->mY:F
iget v4, p0, Landroid/graphics/RadialGradient;->mRadius:F
iget-object v5, p0, Landroid/graphics/RadialGradient;->mColors:[I
iget-object v6, p0, Landroid/graphics/RadialGradient;->mPositions:[F
iget-object v0, p0, Landroid/graphics/RadialGradient;->mTileMode:Landroid/graphics/Shader$TileMode;
iget v7, v0, Landroid/graphics/Shader$TileMode;->nativeInt:I
move-wide v0, p1
invoke-static/range {v0 .. v7}, Landroid/graphics/RadialGradient;->nativeCreate1(JFFF[I[FI)J
move-result-wide v0
return-wide v0
:cond_0
iget v2, p0, Landroid/graphics/RadialGradient;->mX:F
iget v3, p0, Landroid/graphics/RadialGradient;->mY:F
iget v4, p0, Landroid/graphics/RadialGradient;->mRadius:F
iget v5, p0, Landroid/graphics/RadialGradient;->mCenterColor:I
iget v6, p0, Landroid/graphics/RadialGradient;->mEdgeColor:I
iget-object v0, p0, Landroid/graphics/RadialGradient;->mTileMode:Landroid/graphics/Shader$TileMode;
iget v7, v0, Landroid/graphics/Shader$TileMode;->nativeInt:I
move-wide v0, p1
invoke-static/range {v0 .. v7}, Landroid/graphics/RadialGradient;->nativeCreate2(JFFFIII)J
move-result-wide v0
return-wide v0
.end method
| {'content_hash': '5c20801f5c79d952707abfe96f6d37d3', 'timestamp': '', 'source': 'github', 'line_count': 295, 'max_line_length': 121, 'avg_line_length': 24.250847457627117, 'alnum_prop': 0.7085546547386078, 'repo_name': 'BatMan-Rom/ModdedFiles', 'id': '608abc97ce5a3be7fd3da191ccd9def0bafc55fa', 'size': '7154', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'framework.jar.out/smali/android/graphics/RadialGradient.smali', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'GLSL', 'bytes': '15069'}, {'name': 'HTML', 'bytes': '139176'}, {'name': 'Smali', 'bytes': '541934400'}]} |
using System;
class DecimalToBinary
{
static void Main()
{
int number;
while (!int.TryParse(Console.ReadLine(), out number)) { Console.WriteLine("Enter again!"); }
string binary = "";
while (number != 0)
{
binary = number % 2 + binary;
number /= 2;
}
Console.WriteLine("Binary: "+binary);
}
}
| {'content_hash': '0860e141d40fa4f7bb80fbafda2ccc47', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 100, 'avg_line_length': 19.9, 'alnum_prop': 0.49748743718592964, 'repo_name': 'Ico093/TelerikAcademy', 'id': '27381cfe921076ab721f9de776d6390428413cf2', 'size': '400', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'C#2/Homework/4.NumeralSystems/NumeralSystems/01.DecimalToBinary/DecimalToBinary.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '172617'}, {'name': 'C', 'bytes': '1487'}, {'name': 'C#', 'bytes': '2694080'}, {'name': 'CSS', 'bytes': '253424'}, {'name': 'HTML', 'bytes': '518941'}, {'name': 'Java', 'bytes': '47848'}, {'name': 'JavaScript', 'bytes': '1224835'}, {'name': 'Visual Basic', 'bytes': '540085'}]} |
#include "VFSDialog.moc.h"
#include <QVBoxLayout>
#include <QTreeWidget>
#include <QHeaderView>
#include <QTreeWidgetItem>
#include <QLineEdit>
#include <QPushButton>
#include <QDialogButtonBox>
#include <QMessageBox>
#include <Core/List.h>
#include <Core/String.h>
#include <Core/System/Files.h>
namespace QtToolbox
{
VFSDialog::VFSDialog( Core::VirtualFileSystem & vfs,
EVFSDialogMode loadFile,
QWidget * parent)
: QDialog(parent),
_layout(NULL),
_treeView(NULL),
_lineEdit(NULL),
_buttonBox(NULL),
_vfs(vfs),
_loadFile(loadFile)
{
setupUi();
}
VFSDialog::VFSDialog( Core::VirtualFileSystem & vfs,
EVFSDialogMode loadFile,
const Core::String & extension,
QWidget * parent)
: QDialog(parent),
_layout(NULL),
_treeView(NULL),
_lineEdit(NULL),
_buttonBox(NULL),
_vfs(vfs),
_loadFile(loadFile),
_extension(extension)
{
setupUi();
}
VFSDialog::~VFSDialog()
{
if(_layout != NULL)
delete _layout;
if(_treeView != NULL)
delete _treeView;
if(_lineEdit != NULL)
delete _lineEdit;
if(_buttonBox != NULL)
delete _buttonBox;
_layout = NULL;
_treeView = NULL;
_lineEdit = NULL;
_buttonBox = NULL;
}
void VFSDialog::setupUi()
{
if (this->objectName().isEmpty())
this->setObjectName(QString::fromUtf8("VFSDialog"));
this->setWindowTitle("VFS Explorer");
this->setMinimumWidth(512);
this->setMinimumHeight(512);
_layout = new QVBoxLayout();
_layout->setObjectName(QString::fromUtf8("VBoxLayout"));
_layout->setContentsMargins(0, 0, 0, 0);
_treeView = new QTreeWidget(this);
_treeView->header()->setVisible(false);
QTreeWidgetItem * root = new QTreeWidgetItem();
root->setText(0, "/");
QTreeWidgetItem * dummy = new QTreeWidgetItem();
dummy->setText(0, "dummy");
dummy->setDisabled(true);
root->addChild(dummy);
_treeView->addTopLevelItem( root );
_layout->addWidget(_treeView);
_lineEdit = new QLineEdit(this);
_lineEdit->setReadOnly(_loadFile == VFSD_LOAD);
_layout->addWidget(_lineEdit);
_buttonBox = new QDialogButtonBox ( QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
Qt::Horizontal,
this );
_buttonBox->button( QDialogButtonBox::Ok )->setEnabled(false);
_layout->addWidget(_buttonBox);
setLayout(_layout);
connect(_treeView, SIGNAL(itemExpanded(QTreeWidgetItem *)),
this, SLOT(exploreVFS(QTreeWidgetItem *)));
connect(_treeView, SIGNAL(itemClicked(QTreeWidgetItem *, int)),
this, SLOT(chooseFile(QTreeWidgetItem *, int)));
connect(_treeView, SIGNAL(itemActivated(QTreeWidgetItem *, int)),
this, SLOT(chooseFile(QTreeWidgetItem *, int)));
connect(_treeView, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),
this, SLOT(chooseFileAndAccept(QTreeWidgetItem *, int)));
connect(_lineEdit, SIGNAL(textChanged(const QString &)),
this, SLOT(textChanged(const QString &)));
connect(_buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(_buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
}
const Core::String & VFSDialog::getSelectedFile()
{
if(VFSD_SAVE)
{
Core::String extension;
extension << L"." <<_extension;
if(_extension != Core::String::EMPTY && !_selectedString.endsWith(extension))
{
_selectedString << extension;
}
}
return _selectedString;
}
void VFSDialog::exploreVFS(QTreeWidgetItem * item)
{
Core::String location = locate(item);
//Si le dummy est présent c'est la première fois que ce noeud est ouvert
if(item->child(0)->isDisabled())
{
item->removeChild(item->child(0));
Core::List<Core::String> directories;
Core::List<Core::String> files;
_vfs.listDirs(location, directories);
_vfs.listFiles(location, files);
int32 ii = 0;
//On ajoute les répertoires
while(ii < directories.size())
{
Core::String8 directory(directories[ii]);
QTreeWidgetItem * newItem = new QTreeWidgetItem();
newItem->setText(0, directory.c_str());
QTreeWidgetItem * dummy = new QTreeWidgetItem();
dummy->setText(0, "dummy");
dummy->setDisabled(true);
newItem->addChild(dummy);
item->addChild(newItem);
++ii;
}
ii = 0;
//On ajoute les fichier
while(ii < files.size())
{
if(_extension.length() == 0
|| Core::System::getFileExt(files[ii]) == _extension)
{
Core::String8 file(files[ii]);
QTreeWidgetItem * newItem = new QTreeWidgetItem();
newItem->setText(0, file.c_str());
item->addChild(newItem);
}
++ii;
}
}
}
void VFSDialog::chooseFile(QTreeWidgetItem * item, int column)
{
Core::String location = locate(item);
if(_loadFile == VFSD_LOAD)
{
if(item->childCount() == 0)//Peut-être un fichier
{
if(_vfs.fileExists(location))
{
_lineEdit->setText(Core::String8(location).c_str());
_selectedString = location;
}
}
}
else
{
if(_vfs.dirExists(location))
{
location << L"/";
}
_lineEdit->setText(Core::String8(location).c_str());
_selectedString = location;
}
}
void VFSDialog::chooseFileAndAccept(QTreeWidgetItem * item, int column)
{
Core::String location = locate(item);
if(item->childCount() == 0)//Peut-être un fichier
{
if(_vfs.fileExists(location))
{
_lineEdit->setText(Core::String8(location).c_str());
_selectedString = location;
if(_loadFile == VFSD_SAVE)
{
if( QMessageBox::question( this,
"VFSDialog",
"Are you sure you want to overwrite this file?",
QMessageBox::Ok|QMessageBox::Cancel,
QMessageBox::Cancel ) == QMessageBox::Cancel)
{
return;
}
}
accept();
}
}
}
Core::String VFSDialog::locate(QTreeWidgetItem * item)
{
Core::String location;
location << Core::String8(item->text(0).toStdString().c_str());
while(item->parent() != NULL)
{
item = item->parent();
Core::String temp;
temp << Core::String8(item->text(0).toStdString().c_str());
if(temp != L"/")
temp << L"/";
temp << location;
location = temp;
}
return location;
}
void VFSDialog::textChanged(const QString & text)
{
String lineEditText(_lineEdit->text().toStdString().c_str());
bool enableOkButton = false;
enableOkButton = (_lineEdit->text().length() > 0) && !_vfs.dirExists(lineEditText) && lineEditText.startsWith(L"/");
_buttonBox->button( QDialogButtonBox::Ok )->setEnabled( enableOkButton );
if(_loadFile == VFSD_SAVE)
{
String8 selectedString8(text.toStdString().c_str());
_selectedString = String(selectedString8);
}
}
}//namespace QtToolbox
| {'content_hash': '5b519bb87dd60b68b93495e4970ac7ef', 'timestamp': '', 'source': 'github', 'line_count': 271, 'max_line_length': 120, 'avg_line_length': 29.121771217712176, 'alnum_prop': 0.5415610745058287, 'repo_name': 'benkaraban/anima-games-engine', 'id': '366fa9dc43ebd5273d1bfd80eff5966e4166427d', 'size': '9566', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Sources/Tools/QtToolbox/VFSDialog.moc.cpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '8772269'}, {'name': 'C#', 'bytes': '125904'}, {'name': 'C++', 'bytes': '74431764'}, {'name': 'CMake', 'bytes': '43555'}, {'name': 'Java', 'bytes': '95806'}, {'name': 'Makefile', 'bytes': '17914'}, {'name': 'NSIS', 'bytes': '17188'}, {'name': 'Objective-C', 'bytes': '50195'}, {'name': 'Perl', 'bytes': '6275'}, {'name': 'Python', 'bytes': '22678'}, {'name': 'Shell', 'bytes': '21728'}]} |
#include <machine/endian.h>
#if defined(__DARWIN_LITTLE_ENDIAN) && defined(__DARWIN_BYTE_ORDER)
#define PLATFORM_IS_LITTLE_ENDIAN \
(__DARWIN_BYTE_ORDER == __DARWIN_LITTLE_ENDIAN)
#endif
#elif defined(OS_SOLARIS)
#include <sys/isa_defs.h>
#ifdef _LITTLE_ENDIAN
#define PLATFORM_IS_LITTLE_ENDIAN true
#else
#define PLATFORM_IS_LITTLE_ENDIAN false
#endif
#elif defined(OS_FREEBSD)
#include <sys/types.h>
#include <sys/endian.h>
#define PLATFORM_IS_LITTLE_ENDIAN (_BYTE_ORDER == _LITTLE_ENDIAN)
#elif defined(OS_OPENBSD) || defined(OS_NETBSD) ||\
defined(OS_DRAGONFLYBSD)
#include <sys/types.h>
#include <sys/endian.h>
#elif defined(OS_HPUX)
#define PLATFORM_IS_LITTLE_ENDIAN false
#elif defined(OS_ANDROID)
// Due to a bug in the NDK x86 <sys/endian.h> definition,
// _BYTE_ORDER must be used instead of __BYTE_ORDER on Android.
// See http://code.google.com/p/android/issues/detail?id=39824
#include <endian.h>
#define PLATFORM_IS_LITTLE_ENDIAN (_BYTE_ORDER == _LITTLE_ENDIAN)
#else
#include <endian.h>
#endif
#include <pthread.h>
#ifdef SNAPPY
#include <snappy.h>
#endif
#include <stdint.h>
#include <string>
#include "port/atomic_pointer.h"
#ifndef PLATFORM_IS_LITTLE_ENDIAN
#define PLATFORM_IS_LITTLE_ENDIAN (__BYTE_ORDER == __LITTLE_ENDIAN)
#endif
#if defined(OS_MACOSX) || defined(OS_SOLARIS) || defined(OS_FREEBSD) ||\
defined(OS_NETBSD) || defined(OS_OPENBSD) || defined(OS_DRAGONFLYBSD) ||\
defined(OS_ANDROID) || defined(OS_HPUX)
// Use fread/fwrite/fflush on platforms without _unlocked variants
#define fread_unlocked fread
#define fwrite_unlocked fwrite
#define fflush_unlocked fflush
#endif
#if defined(OS_MACOSX) || defined(OS_FREEBSD) ||\
defined(OS_OPENBSD) || defined(OS_DRAGONFLYBSD)
// Use fsync() on platforms without fdatasync()
#define fdatasync fsync
#endif
#if defined(OS_ANDROID) && __ANDROID_API__ < 9
// fdatasync() was only introduced in API level 9 on Android. Use fsync()
// when targetting older platforms.
#define fdatasync fsync
#endif
namespace leveldb {
namespace port {
static const bool kLittleEndian = PLATFORM_IS_LITTLE_ENDIAN;
#undef PLATFORM_IS_LITTLE_ENDIAN
class CondVar;
class Mutex {
public:
Mutex();
~Mutex();
void Lock();
void Unlock();
void AssertHeld() { }
private:
friend class CondVar;
pthread_mutex_t mu_;
// No copying
Mutex(const Mutex&);
void operator=(const Mutex&);
};
class CondVar {
public:
explicit CondVar(Mutex* mu);
~CondVar();
void Wait();
bool Wait(int64_t wait_millisec);
void Signal();
void SignalAll();
private:
pthread_cond_t cond_;
pthread_condattr_t attr_;
Mutex* mu_;
};
typedef pthread_once_t OnceType;
#define LEVELDB_ONCE_INIT PTHREAD_ONCE_INIT
extern void InitOnce(OnceType* once, void (*initializer)());
inline bool Snappy_Compress(const char* input, size_t length,
::std::string* output) {
#ifdef SNAPPY
output->resize(snappy::MaxCompressedLength(length));
size_t outlen;
snappy::RawCompress(input, length, &(*output)[0], &outlen);
output->resize(outlen);
return true;
#endif
return false;
}
inline bool Snappy_GetUncompressedLength(const char* input, size_t length,
size_t* result) {
#ifdef SNAPPY
return snappy::GetUncompressedLength(input, length, result);
#else
return false;
#endif
}
inline bool Snappy_Uncompress(const char* input, size_t length,
char* output) {
#ifdef SNAPPY
return snappy::RawUncompress(input, length, output);
#else
return false;
#endif
}
/////////// Compression Ext ///////////
bool Bmz_Compress(const char* input, size_t input_size,
std::string* output);
bool Bmz_Uncompress(const char* input, size_t input_size,
char* output, size_t* output_size);
bool Lz4_Compress(const char* input, size_t input_size,
std::string* output);
bool Lz4_Uncompress(const char* input, size_t input_size,
char* output, size_t* output_size);
//////////////////////////////
inline bool GetHeapProfile(void (*func)(void*, const char*, int), void* arg) {
return false;
}
} // namespace port
} // namespace leveldb
#endif // STORAGE_LEVELDB_PORT_PORT_POSIX_H_
| {'content_hash': '552086c4ca2d5a9558b2ef8b3f7382b2', 'timestamp': '', 'source': 'github', 'line_count': 164, 'max_line_length': 78, 'avg_line_length': 26.121951219512194, 'alnum_prop': 0.6720354808590103, 'repo_name': 'PengyuSun/tera', 'id': 'ed19e222f91f1fb12bd3bc80c7b7a2320fd482ce', 'size': '4888', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/leveldb/port/port_posix.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '86078'}, {'name': 'C++', 'bytes': '3322198'}, {'name': 'CMake', 'bytes': '1040'}, {'name': 'Java', 'bytes': '39999'}, {'name': 'Makefile', 'bytes': '18707'}, {'name': 'Protocol Buffer', 'bytes': '31237'}, {'name': 'Python', 'bytes': '157375'}, {'name': 'Shell', 'bytes': '37983'}]} |
#ifndef XENIA_FRONTEND_PPC_TRANSLATOR_H_
#define XENIA_FRONTEND_PPC_TRANSLATOR_H_
#include <memory>
#include "xenia/base/string_buffer.h"
#include "xenia/cpu/backend/assembler.h"
#include "xenia/cpu/compiler/compiler.h"
#include "xenia/cpu/symbol_info.h"
namespace xe {
namespace cpu {
namespace frontend {
class PPCFrontend;
class PPCHIRBuilder;
class PPCScanner;
class PPCTranslator {
public:
PPCTranslator(PPCFrontend* frontend);
~PPCTranslator();
bool Translate(FunctionInfo* symbol_info, uint32_t debug_info_flags,
Function** out_function);
private:
void DumpSource(FunctionInfo* symbol_info, StringBuffer* string_buffer);
private:
PPCFrontend* frontend_;
std::unique_ptr<PPCScanner> scanner_;
std::unique_ptr<PPCHIRBuilder> builder_;
std::unique_ptr<compiler::Compiler> compiler_;
std::unique_ptr<backend::Assembler> assembler_;
StringBuffer string_buffer_;
};
} // namespace frontend
} // namespace cpu
} // namespace xe
#endif // XENIA_FRONTEND_PPC_TRANSLATOR_H_
| {'content_hash': '0825f9a809af9838dc3110d90b92e05b', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 74, 'avg_line_length': 22.347826086956523, 'alnum_prop': 0.7334630350194552, 'repo_name': 'TingPing/xenia', 'id': 'f0263c859f10a6c89525680894675197b587fa42', 'size': '1515', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/xenia/cpu/frontend/ppc_translator.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '245586'}, {'name': 'Batchfile', 'bytes': '1182'}, {'name': 'C', 'bytes': '10073'}, {'name': 'C++', 'bytes': '3078450'}, {'name': 'Lua', 'bytes': '17222'}, {'name': 'PHP', 'bytes': '372073'}, {'name': 'Python', 'bytes': '27766'}]} |
/**********************************
Global Modal Spec
**********************************/
var modal = {
_spec: new ReactiveDict(),
_onConfirm: null
};
function setModal(spec) {
_.each(spec, function (val, key) {
if (key !== 'onConfirm') {
modal._spec.set(key, val);
} else if (val instanceof Function) {
modal._onConfirm = val;
modal._spec.set(key, true);
}
});
_.each(modal._spec.keys, function (val, key) {
if (!(key in spec)) {
modal._spec.set(key, null);
if (key === 'onConfirm') {
modal._onConfirm = null;
}
}
});
if (!('show' in spec)) {
modal._spec.set('show', true);
}
}
modal.set = setModal;
function showModal () {
if (modal._spec) {
modal._spec.set('show', true);
}
}
modal.hide = hideModal;
function hideModal() {
if (modal._spec) {
modal._spec.set('show', false);
}
}
modal.hide = hideModal;
MDL.modal = modal;
/**********************************
Template logic
**********************************/
function mdlModalClasses (data) {
var classes = ['mdl-modal'];
if (data.show) {
classes.push('is-visible');
}
if (data.error) {
classes.push('is-error');
}
return classes;
}
Template.mdlModal.helpers({
atts: function () {
var modalData = {
show: modal._spec.get('show'),
error: modal._spec.get('error')
};
var data = _.extend(Template.currentData() || {}, modalData);
var atts = MDL.filterAtts('div', data);
atts.class = (atts.class ? [atts.class] : []).concat(mdlModalClasses(data)).join(' ');
return atts;
},
message: function () {
return modal._spec.get('message') || modal._spec.get('error');
},
confirm: function () {
return !!modal._spec.get('onConfirm');
},
template: function () {
return modal._spec.get('template');
},
templateData: function () {
return modal._spec.get('templateData');
}
});
Template.mdlModal.events({
'click .mdl-modal__close-btn': function () {
modal._spec.set('show', false);
},
'click .mdl-modal__cancel-btn': function () {
modal._spec.set('show', false);
},
'click .mdl-modal__confirm-btn': function () {
modal._spec.set('show', false);
if (modal._onConfirm) { modal._onConfirm(); }
}
});
| {'content_hash': '7300915a13198a3fcc4818d7eeb8621b', 'timestamp': '', 'source': 'github', 'line_count': 105, 'max_line_length': 90, 'avg_line_length': 21.65714285714286, 'alnum_prop': 0.5400175901495162, 'repo_name': 'rhythnic/meteor-mdl-ux', 'id': '510cdf52eb35367af41c006604d6e617fef93795', 'size': '2274', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'components/modal/modal.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '949'}, {'name': 'HTML', 'bytes': '2558'}, {'name': 'JavaScript', 'bytes': '14648'}]} |
package resources // import "google.golang.org/genproto/googleapis/ads/googleads/v0/resources"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import wrappers "github.com/golang/protobuf/ptypes/wrappers"
import common "google.golang.org/genproto/googleapis/ads/googleads/v0/common"
import enums "google.golang.org/genproto/googleapis/ads/googleads/v0/enums"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
// A conversion action.
type ConversionAction struct {
// The resource name of the conversion action.
// Conversion action resource names have the form:
//
// `customers/{customer_id}/conversionActions/{conversion_action_id}`
ResourceName string `protobuf:"bytes,1,opt,name=resource_name,json=resourceName,proto3" json:"resource_name,omitempty"`
// The ID of the conversion action.
Id *wrappers.Int64Value `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"`
// The name of the conversion action.
//
// This field is required and should not be empty when creating new
// conversion actions.
Name *wrappers.StringValue `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"`
// The status of this conversion action for conversion event accrual.
Status enums.ConversionActionStatusEnum_ConversionActionStatus `protobuf:"varint,4,opt,name=status,proto3,enum=google.ads.googleads.v0.enums.ConversionActionStatusEnum_ConversionActionStatus" json:"status,omitempty"`
// The type of this conversion action.
Type enums.ConversionActionTypeEnum_ConversionActionType `protobuf:"varint,5,opt,name=type,proto3,enum=google.ads.googleads.v0.enums.ConversionActionTypeEnum_ConversionActionType" json:"type,omitempty"`
// The category of conversions reported for this conversion action.
Category enums.ConversionActionCategoryEnum_ConversionActionCategory `protobuf:"varint,6,opt,name=category,proto3,enum=google.ads.googleads.v0.enums.ConversionActionCategoryEnum_ConversionActionCategory" json:"category,omitempty"`
// The resource name of the conversion action owner customer, or null if this
// is a system-defined conversion action.
OwnerCustomer *wrappers.StringValue `protobuf:"bytes,7,opt,name=owner_customer,json=ownerCustomer,proto3" json:"owner_customer,omitempty"`
// Whether this conversion action should be included in the "conversions"
// metric.
IncludeInConversionsMetric *wrappers.BoolValue `protobuf:"bytes,8,opt,name=include_in_conversions_metric,json=includeInConversionsMetric,proto3" json:"include_in_conversions_metric,omitempty"`
// The maximum number of days that may elapse between an interaction
// (e.g., a click) and a conversion event.
ClickThroughLookbackWindowDays *wrappers.Int64Value `protobuf:"bytes,9,opt,name=click_through_lookback_window_days,json=clickThroughLookbackWindowDays,proto3" json:"click_through_lookback_window_days,omitempty"`
// The maximum number of days which may elapse between an impression and a
// conversion without an interaction.
ViewThroughLookbackWindowDays *wrappers.Int64Value `protobuf:"bytes,10,opt,name=view_through_lookback_window_days,json=viewThroughLookbackWindowDays,proto3" json:"view_through_lookback_window_days,omitempty"`
// Settings related to the value for conversion events associated with this
// conversion action.
ValueSettings *ConversionAction_ValueSettings `protobuf:"bytes,11,opt,name=value_settings,json=valueSettings,proto3" json:"value_settings,omitempty"`
// How to count conversion events for the conversion action.
CountingType enums.ConversionActionCountingTypeEnum_ConversionActionCountingType `protobuf:"varint,12,opt,name=counting_type,json=countingType,proto3,enum=google.ads.googleads.v0.enums.ConversionActionCountingTypeEnum_ConversionActionCountingType" json:"counting_type,omitempty"`
// Settings related to this conversion action's attribution model.
AttributionModelSettings *ConversionAction_AttributionModelSettings `protobuf:"bytes,13,opt,name=attribution_model_settings,json=attributionModelSettings,proto3" json:"attribution_model_settings,omitempty"`
// The snippets used for tracking conversions.
TagSnippets []*common.TagSnippet `protobuf:"bytes,14,rep,name=tag_snippets,json=tagSnippets,proto3" json:"tag_snippets,omitempty"`
// The phone call duration in seconds after which a conversion should be
// reported for this conversion action.
//
// The value must be between 0 and 10000, inclusive.
PhoneCallDurationSeconds *wrappers.Int64Value `protobuf:"bytes,15,opt,name=phone_call_duration_seconds,json=phoneCallDurationSeconds,proto3" json:"phone_call_duration_seconds,omitempty"`
// App ID for an app conversion action.
AppId *wrappers.StringValue `protobuf:"bytes,16,opt,name=app_id,json=appId,proto3" json:"app_id,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *ConversionAction) Reset() { *m = ConversionAction{} }
func (m *ConversionAction) String() string { return proto.CompactTextString(m) }
func (*ConversionAction) ProtoMessage() {}
func (*ConversionAction) Descriptor() ([]byte, []int) {
return fileDescriptor_conversion_action_84c1356f86b03971, []int{0}
}
func (m *ConversionAction) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_ConversionAction.Unmarshal(m, b)
}
func (m *ConversionAction) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_ConversionAction.Marshal(b, m, deterministic)
}
func (dst *ConversionAction) XXX_Merge(src proto.Message) {
xxx_messageInfo_ConversionAction.Merge(dst, src)
}
func (m *ConversionAction) XXX_Size() int {
return xxx_messageInfo_ConversionAction.Size(m)
}
func (m *ConversionAction) XXX_DiscardUnknown() {
xxx_messageInfo_ConversionAction.DiscardUnknown(m)
}
var xxx_messageInfo_ConversionAction proto.InternalMessageInfo
func (m *ConversionAction) GetResourceName() string {
if m != nil {
return m.ResourceName
}
return ""
}
func (m *ConversionAction) GetId() *wrappers.Int64Value {
if m != nil {
return m.Id
}
return nil
}
func (m *ConversionAction) GetName() *wrappers.StringValue {
if m != nil {
return m.Name
}
return nil
}
func (m *ConversionAction) GetStatus() enums.ConversionActionStatusEnum_ConversionActionStatus {
if m != nil {
return m.Status
}
return enums.ConversionActionStatusEnum_UNSPECIFIED
}
func (m *ConversionAction) GetType() enums.ConversionActionTypeEnum_ConversionActionType {
if m != nil {
return m.Type
}
return enums.ConversionActionTypeEnum_UNSPECIFIED
}
func (m *ConversionAction) GetCategory() enums.ConversionActionCategoryEnum_ConversionActionCategory {
if m != nil {
return m.Category
}
return enums.ConversionActionCategoryEnum_UNSPECIFIED
}
func (m *ConversionAction) GetOwnerCustomer() *wrappers.StringValue {
if m != nil {
return m.OwnerCustomer
}
return nil
}
func (m *ConversionAction) GetIncludeInConversionsMetric() *wrappers.BoolValue {
if m != nil {
return m.IncludeInConversionsMetric
}
return nil
}
func (m *ConversionAction) GetClickThroughLookbackWindowDays() *wrappers.Int64Value {
if m != nil {
return m.ClickThroughLookbackWindowDays
}
return nil
}
func (m *ConversionAction) GetViewThroughLookbackWindowDays() *wrappers.Int64Value {
if m != nil {
return m.ViewThroughLookbackWindowDays
}
return nil
}
func (m *ConversionAction) GetValueSettings() *ConversionAction_ValueSettings {
if m != nil {
return m.ValueSettings
}
return nil
}
func (m *ConversionAction) GetCountingType() enums.ConversionActionCountingTypeEnum_ConversionActionCountingType {
if m != nil {
return m.CountingType
}
return enums.ConversionActionCountingTypeEnum_UNSPECIFIED
}
func (m *ConversionAction) GetAttributionModelSettings() *ConversionAction_AttributionModelSettings {
if m != nil {
return m.AttributionModelSettings
}
return nil
}
func (m *ConversionAction) GetTagSnippets() []*common.TagSnippet {
if m != nil {
return m.TagSnippets
}
return nil
}
func (m *ConversionAction) GetPhoneCallDurationSeconds() *wrappers.Int64Value {
if m != nil {
return m.PhoneCallDurationSeconds
}
return nil
}
func (m *ConversionAction) GetAppId() *wrappers.StringValue {
if m != nil {
return m.AppId
}
return nil
}
// Settings related to this conversion action's attribution model.
type ConversionAction_AttributionModelSettings struct {
// The attribution model type of this conversion action.
AttributionModel enums.AttributionModelEnum_AttributionModel `protobuf:"varint,1,opt,name=attribution_model,json=attributionModel,proto3,enum=google.ads.googleads.v0.enums.AttributionModelEnum_AttributionModel" json:"attribution_model,omitempty"`
// The status of the data-driven attribution model for the conversion
// action.
DataDrivenModelStatus enums.DataDrivenModelStatusEnum_DataDrivenModelStatus `protobuf:"varint,2,opt,name=data_driven_model_status,json=dataDrivenModelStatus,proto3,enum=google.ads.googleads.v0.enums.DataDrivenModelStatusEnum_DataDrivenModelStatus" json:"data_driven_model_status,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *ConversionAction_AttributionModelSettings) Reset() {
*m = ConversionAction_AttributionModelSettings{}
}
func (m *ConversionAction_AttributionModelSettings) String() string { return proto.CompactTextString(m) }
func (*ConversionAction_AttributionModelSettings) ProtoMessage() {}
func (*ConversionAction_AttributionModelSettings) Descriptor() ([]byte, []int) {
return fileDescriptor_conversion_action_84c1356f86b03971, []int{0, 0}
}
func (m *ConversionAction_AttributionModelSettings) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_ConversionAction_AttributionModelSettings.Unmarshal(m, b)
}
func (m *ConversionAction_AttributionModelSettings) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_ConversionAction_AttributionModelSettings.Marshal(b, m, deterministic)
}
func (dst *ConversionAction_AttributionModelSettings) XXX_Merge(src proto.Message) {
xxx_messageInfo_ConversionAction_AttributionModelSettings.Merge(dst, src)
}
func (m *ConversionAction_AttributionModelSettings) XXX_Size() int {
return xxx_messageInfo_ConversionAction_AttributionModelSettings.Size(m)
}
func (m *ConversionAction_AttributionModelSettings) XXX_DiscardUnknown() {
xxx_messageInfo_ConversionAction_AttributionModelSettings.DiscardUnknown(m)
}
var xxx_messageInfo_ConversionAction_AttributionModelSettings proto.InternalMessageInfo
func (m *ConversionAction_AttributionModelSettings) GetAttributionModel() enums.AttributionModelEnum_AttributionModel {
if m != nil {
return m.AttributionModel
}
return enums.AttributionModelEnum_UNSPECIFIED
}
func (m *ConversionAction_AttributionModelSettings) GetDataDrivenModelStatus() enums.DataDrivenModelStatusEnum_DataDrivenModelStatus {
if m != nil {
return m.DataDrivenModelStatus
}
return enums.DataDrivenModelStatusEnum_UNSPECIFIED
}
// Settings related to the value for conversion events associated with this
// conversion action.
type ConversionAction_ValueSettings struct {
// The value to use when conversion events for this conversion action are
// sent with an invalid, disallowed or missing value, or when
// this conversion action is configured to always use the default value.
DefaultValue *wrappers.DoubleValue `protobuf:"bytes,1,opt,name=default_value,json=defaultValue,proto3" json:"default_value,omitempty"`
// The currency code to use when conversion events for this conversion
// action are sent with an invalid or missing currency code, or when this
// conversion action is configured to always use the default value.
DefaultCurrencyCode *wrappers.StringValue `protobuf:"bytes,2,opt,name=default_currency_code,json=defaultCurrencyCode,proto3" json:"default_currency_code,omitempty"`
// Controls whether the default value and default currency code are used in
// place of the value and currency code specified in conversion events for
// this conversion action.
AlwaysUseDefaultValue *wrappers.BoolValue `protobuf:"bytes,3,opt,name=always_use_default_value,json=alwaysUseDefaultValue,proto3" json:"always_use_default_value,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *ConversionAction_ValueSettings) Reset() { *m = ConversionAction_ValueSettings{} }
func (m *ConversionAction_ValueSettings) String() string { return proto.CompactTextString(m) }
func (*ConversionAction_ValueSettings) ProtoMessage() {}
func (*ConversionAction_ValueSettings) Descriptor() ([]byte, []int) {
return fileDescriptor_conversion_action_84c1356f86b03971, []int{0, 1}
}
func (m *ConversionAction_ValueSettings) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_ConversionAction_ValueSettings.Unmarshal(m, b)
}
func (m *ConversionAction_ValueSettings) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_ConversionAction_ValueSettings.Marshal(b, m, deterministic)
}
func (dst *ConversionAction_ValueSettings) XXX_Merge(src proto.Message) {
xxx_messageInfo_ConversionAction_ValueSettings.Merge(dst, src)
}
func (m *ConversionAction_ValueSettings) XXX_Size() int {
return xxx_messageInfo_ConversionAction_ValueSettings.Size(m)
}
func (m *ConversionAction_ValueSettings) XXX_DiscardUnknown() {
xxx_messageInfo_ConversionAction_ValueSettings.DiscardUnknown(m)
}
var xxx_messageInfo_ConversionAction_ValueSettings proto.InternalMessageInfo
func (m *ConversionAction_ValueSettings) GetDefaultValue() *wrappers.DoubleValue {
if m != nil {
return m.DefaultValue
}
return nil
}
func (m *ConversionAction_ValueSettings) GetDefaultCurrencyCode() *wrappers.StringValue {
if m != nil {
return m.DefaultCurrencyCode
}
return nil
}
func (m *ConversionAction_ValueSettings) GetAlwaysUseDefaultValue() *wrappers.BoolValue {
if m != nil {
return m.AlwaysUseDefaultValue
}
return nil
}
func init() {
proto.RegisterType((*ConversionAction)(nil), "google.ads.googleads.v0.resources.ConversionAction")
proto.RegisterType((*ConversionAction_AttributionModelSettings)(nil), "google.ads.googleads.v0.resources.ConversionAction.AttributionModelSettings")
proto.RegisterType((*ConversionAction_ValueSettings)(nil), "google.ads.googleads.v0.resources.ConversionAction.ValueSettings")
}
func init() {
proto.RegisterFile("google/ads/googleads/v0/resources/conversion_action.proto", fileDescriptor_conversion_action_84c1356f86b03971)
}
var fileDescriptor_conversion_action_84c1356f86b03971 = []byte{
// 955 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x56, 0xcf, 0x6e, 0x23, 0x35,
0x18, 0x57, 0xd2, 0xdd, 0xb2, 0xeb, 0x26, 0xd9, 0x62, 0x54, 0x69, 0x94, 0x65, 0x57, 0xed, 0xa2,
0x95, 0x2a, 0x90, 0x26, 0x51, 0x16, 0x90, 0x08, 0x08, 0x29, 0x4d, 0xd0, 0xaa, 0xa8, 0x5d, 0x55,
0x93, 0x52, 0xa4, 0x55, 0x90, 0x71, 0x6c, 0xef, 0x64, 0xd4, 0x19, 0x7b, 0xb0, 0x3d, 0x89, 0x72,
0x84, 0x0b, 0x12, 0x2f, 0xc0, 0x9d, 0x23, 0x6f, 0xc0, 0x2b, 0xf0, 0x28, 0xbc, 0x01, 0x37, 0x34,
0x1e, 0xcf, 0x34, 0x4d, 0x32, 0x4d, 0xc3, 0xcd, 0x1e, 0xff, 0xfe, 0xf8, 0xfb, 0xfc, 0xf9, 0xf3,
0x80, 0x2f, 0x7c, 0x21, 0xfc, 0x90, 0xb5, 0x30, 0x55, 0xad, 0x6c, 0x98, 0x8e, 0xa6, 0xed, 0x96,
0x64, 0x4a, 0x24, 0x92, 0x30, 0xd5, 0x22, 0x82, 0x4f, 0x99, 0x54, 0x81, 0xe0, 0x08, 0x13, 0x1d,
0x08, 0xee, 0xc6, 0x52, 0x68, 0x01, 0x8f, 0x32, 0xbc, 0x8b, 0xa9, 0x72, 0x0b, 0xaa, 0x3b, 0x6d,
0xbb, 0x05, 0xb5, 0xd9, 0x2e, 0x53, 0x27, 0x22, 0x8a, 0x04, 0x6f, 0x69, 0xec, 0x23, 0xc5, 0x83,
0x38, 0x66, 0x3a, 0x13, 0x6d, 0x7e, 0x56, 0xc6, 0x60, 0x3c, 0x89, 0x54, 0x0b, 0x6b, 0x2d, 0x83,
0x71, 0x92, 0xee, 0x02, 0x45, 0x82, 0xb2, 0xd0, 0xd2, 0xbe, 0xbe, 0x9b, 0xb6, 0x12, 0x02, 0x22,
0x58, 0x33, 0x5f, 0xc8, 0xb9, 0xe5, 0xf7, 0xb7, 0xe6, 0x8b, 0x84, 0xeb, 0x80, 0xfb, 0x48, 0xcf,
0x63, 0x66, 0x45, 0xbe, 0xda, 0x56, 0x44, 0x69, 0xac, 0x13, 0x65, 0xd9, 0xdd, 0x6d, 0xd9, 0xf7,
0x77, 0xa6, 0x58, 0x63, 0x44, 0x65, 0x30, 0x65, 0x36, 0x6b, 0xb7, 0x9d, 0x9f, 0x5b, 0xb6, 0x99,
0x8d, 0x93, 0x77, 0xad, 0x99, 0xc4, 0x71, 0xcc, 0xa4, 0x5d, 0x7f, 0xf1, 0xd7, 0x13, 0xb0, 0xdf,
0x2f, 0xec, 0x7b, 0xc6, 0x1d, 0x7e, 0x04, 0xea, 0xf9, 0x39, 0x23, 0x8e, 0x23, 0xe6, 0x54, 0x0e,
0x2b, 0xc7, 0x8f, 0xbd, 0x5a, 0xfe, 0xf1, 0x0d, 0x8e, 0x18, 0xfc, 0x04, 0x54, 0x03, 0xea, 0x54,
0x0f, 0x2b, 0xc7, 0x7b, 0x9d, 0xa7, 0xb6, 0x48, 0xdc, 0xdc, 0xc6, 0x3d, 0xe5, 0xfa, 0xf3, 0x4f,
0xaf, 0x70, 0x98, 0x30, 0xaf, 0x1a, 0x50, 0xd8, 0x06, 0x0f, 0x8c, 0xd0, 0x8e, 0x81, 0x7f, 0xb8,
0x02, 0x1f, 0x6a, 0x19, 0x70, 0x3f, 0xc3, 0x1b, 0x24, 0x9c, 0x80, 0xdd, 0x2c, 0x10, 0xe7, 0xc1,
0x61, 0xe5, 0xb8, 0xd1, 0xb9, 0x70, 0xcb, 0x4a, 0xd2, 0xe4, 0xc1, 0x5d, 0x0e, 0x62, 0x68, 0xc8,
0xdf, 0xf0, 0x24, 0x2a, 0x59, 0xf2, 0xac, 0x3e, 0xfc, 0x11, 0x3c, 0x48, 0xd3, 0xed, 0x3c, 0x34,
0x3e, 0x67, 0x5b, 0xfa, 0x5c, 0xce, 0x63, 0xb6, 0xd6, 0x25, 0x5d, 0xf0, 0x8c, 0x32, 0x8c, 0xc1,
0xa3, 0xbc, 0x26, 0x9d, 0x5d, 0xe3, 0x72, 0xb9, 0xa5, 0x4b, 0xdf, 0xd2, 0xd7, 0x3a, 0xe5, 0x8b,
0x5e, 0xe1, 0x02, 0xfb, 0xa0, 0x21, 0x66, 0x9c, 0x49, 0x44, 0x12, 0xa5, 0x45, 0xc4, 0xa4, 0xf3,
0xde, 0x3d, 0x32, 0x5f, 0x37, 0x9c, 0xbe, 0xa5, 0xc0, 0x1f, 0xc0, 0xb3, 0x80, 0x93, 0x30, 0xa1,
0x0c, 0x05, 0xe9, 0xad, 0xc8, 0x5d, 0x15, 0x8a, 0x98, 0x96, 0x01, 0x71, 0x1e, 0x19, 0xcd, 0xe6,
0x8a, 0xe6, 0x89, 0x10, 0x61, 0xa6, 0xd8, 0xb4, 0x02, 0xa7, 0xfc, 0x66, 0xd3, 0xea, 0xdc, 0xb0,
0xa1, 0x0f, 0x5e, 0x90, 0x30, 0x20, 0xd7, 0x48, 0x4f, 0xa4, 0x48, 0xfc, 0x09, 0x0a, 0x85, 0xb8,
0x1e, 0x63, 0x72, 0x8d, 0x66, 0x01, 0xa7, 0x62, 0x86, 0x28, 0x9e, 0x2b, 0xe7, 0xf1, 0xe6, 0x02,
0x7b, 0x6e, 0x64, 0x2e, 0x33, 0x95, 0x33, 0x2b, 0xf2, 0xbd, 0xd1, 0x18, 0xe0, 0xb9, 0x82, 0x0c,
0x1c, 0x4d, 0x03, 0x36, 0xbb, 0xdb, 0x07, 0x6c, 0xf6, 0x79, 0x96, 0xaa, 0x94, 0xdb, 0x4c, 0x40,
0x63, 0x9a, 0xe2, 0x90, 0x62, 0x3a, 0x6d, 0x1f, 0xca, 0xd9, 0x33, 0x9a, 0x3d, 0x77, 0x63, 0x33,
0x5d, 0x39, 0x52, 0xd7, 0x38, 0x0e, 0xad, 0x90, 0x57, 0x9f, 0x2e, 0x4e, 0xe1, 0xcf, 0x15, 0x50,
0xbf, 0xd5, 0xa4, 0x9c, 0x9a, 0xa9, 0xaa, 0xd1, 0xb6, 0x55, 0x65, 0x35, 0x4a, 0x6b, 0x78, 0x11,
0xe0, 0xd5, 0xc8, 0xc2, 0x0c, 0xfe, 0x56, 0x01, 0xcd, 0x95, 0x8e, 0x7d, 0x13, 0x7a, 0xdd, 0x84,
0x7e, 0xf6, 0x7f, 0x42, 0xef, 0xdd, 0xa8, 0x9e, 0xa7, 0xa2, 0x45, 0x16, 0x1c, 0x5c, 0xb2, 0x02,
0xcf, 0x41, 0x6d, 0xe1, 0xb9, 0x51, 0x4e, 0xe3, 0x70, 0xe7, 0x78, 0xaf, 0xf3, 0x71, 0xa9, 0x7b,
0xf6, 0x44, 0xb9, 0x97, 0xd8, 0x1f, 0x66, 0x14, 0x6f, 0x4f, 0x17, 0x63, 0x05, 0xdf, 0x82, 0xa7,
0xf1, 0x44, 0x70, 0x86, 0x08, 0x0e, 0x43, 0x44, 0x13, 0x89, 0xb3, 0x96, 0xce, 0x88, 0xe0, 0x54,
0x39, 0x4f, 0x36, 0x97, 0x8a, 0x63, 0xf8, 0x7d, 0x1c, 0x86, 0x03, 0xcb, 0x1e, 0x66, 0x64, 0xf8,
0x0a, 0xec, 0xe2, 0x38, 0x46, 0x01, 0x75, 0xf6, 0xef, 0x71, 0x23, 0x1f, 0xe2, 0x38, 0x3e, 0xa5,
0xcd, 0xdf, 0xab, 0xc0, 0x29, 0x4b, 0x0b, 0xfc, 0x09, 0xbc, 0xbf, 0x72, 0x10, 0xa6, 0x63, 0x37,
0x3a, 0x83, 0x0d, 0x05, 0xb1, 0xac, 0x69, 0x8a, 0x60, 0xf9, 0xa3, 0xb7, 0xbf, 0x9c, 0x77, 0xf8,
0x6b, 0x05, 0x38, 0x65, 0x0f, 0x8f, 0x79, 0x12, 0x1a, 0x9d, 0x37, 0x1b, 0xac, 0x07, 0x58, 0xe3,
0x81, 0x61, 0x67, 0xd1, 0xdc, 0xb4, 0xeb, 0xb5, 0x2b, 0xde, 0x01, 0x5d, 0xf7, 0xb9, 0xf9, 0x6f,
0x05, 0xd4, 0x6f, 0xdd, 0x15, 0xd8, 0x03, 0x75, 0xca, 0xde, 0xe1, 0x24, 0xd4, 0xc8, 0xdc, 0x1a,
0x93, 0x8a, 0x75, 0x79, 0x1e, 0x88, 0x64, 0x1c, 0xb2, 0x2c, 0xcf, 0x35, 0x4b, 0x31, 0x33, 0x78,
0x01, 0x0e, 0x72, 0x09, 0x92, 0x48, 0xc9, 0x38, 0x99, 0x23, 0x22, 0x28, 0xb3, 0xaf, 0xdd, 0xdd,
0x47, 0xf6, 0x81, 0xa5, 0xf6, 0x2d, 0xb3, 0x2f, 0x28, 0x83, 0x43, 0xe0, 0xe0, 0x70, 0x86, 0xe7,
0x0a, 0x25, 0x8a, 0xa1, 0xdb, 0xfb, 0xdb, 0xd9, 0xd8, 0x45, 0x0f, 0x32, 0xee, 0x77, 0x8a, 0x0d,
0x16, 0xb6, 0x79, 0xf2, 0x4b, 0x15, 0xbc, 0x24, 0x22, 0xda, 0x7c, 0xc7, 0x4e, 0x0e, 0x96, 0x2f,
0xd9, 0x45, 0x6a, 0x72, 0x51, 0x79, 0xfb, 0xad, 0xe5, 0xfa, 0x22, 0xc4, 0xdc, 0x77, 0x85, 0xf4,
0x5b, 0x3e, 0xe3, 0x66, 0x0b, 0xf9, 0xcf, 0x46, 0x1c, 0xa8, 0x3b, 0xfe, 0x20, 0xbf, 0x2c, 0x46,
0x7f, 0x54, 0x77, 0x5e, 0xf7, 0x7a, 0x7f, 0x56, 0x8f, 0x5e, 0x67, 0x92, 0x3d, 0xaa, 0xdc, 0x6c,
0x98, 0x8e, 0xae, 0xda, 0xae, 0x97, 0x23, 0xff, 0xce, 0x31, 0xa3, 0x1e, 0x55, 0xa3, 0x02, 0x33,
0xba, 0x6a, 0x8f, 0x0a, 0xcc, 0x3f, 0xd5, 0x97, 0xd9, 0x42, 0xb7, 0xdb, 0xa3, 0xaa, 0xdb, 0x2d,
0x50, 0xdd, 0xee, 0x55, 0xbb, 0xdb, 0x2d, 0x70, 0xe3, 0x5d, 0xb3, 0xd9, 0x57, 0xff, 0x05, 0x00,
0x00, 0xff, 0xff, 0xca, 0x40, 0xd9, 0xc1, 0xed, 0x0a, 0x00, 0x00,
}
| {'content_hash': '9214298553c997011e9d121b18377809', 'timestamp': '', 'source': 'github', 'line_count': 399, 'max_line_length': 291, 'avg_line_length': 52.87719298245614, 'alnum_prop': 0.744952128163807, 'repo_name': 'cloudfoundry-community/firehose-to-syslog', 'id': 'dbfde33fbe59cac58e76f76aaeb78d00d3e1d0f1', 'size': '21217', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'vendor/google.golang.org/genproto/googleapis/ads/googleads/v0/resources/conversion_action.pb.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Dockerfile', 'bytes': '1455'}, {'name': 'Go', 'bytes': '85760'}, {'name': 'Makefile', 'bytes': '706'}, {'name': 'Shell', 'bytes': '2582'}]} |
<?php
namespace ScssPhp\ScssPhp\SourceMap;
use ScssPhp\ScssPhp\Exception\CompilerException;
/**
* Source Map Generator
*
* {@internal Derivative of oyejorge/less.php's lib/SourceMap/Generator.php, relicensed with permission. }}
*
* @author Josh Schmidt <[email protected]>
* @author Nicolas FRANÇOIS <[email protected]>
*
* @internal
*/
class SourceMapGenerator
{
/**
* What version of source map does the generator generate?
*/
const VERSION = 3;
/**
* Array of default options
*
* @var array
* @phpstan-var array{sourceRoot: string, sourceMapFilename: string|null, sourceMapURL: string|null, sourceMapWriteTo: string|null, outputSourceFiles: bool, sourceMapRootpath: string, sourceMapBasepath: string}
*/
protected $defaultOptions = [
// an optional source root, useful for relocating source files
// on a server or removing repeated values in the 'sources' entry.
// This value is prepended to the individual entries in the 'source' field.
'sourceRoot' => '',
// an optional name of the generated code that this source map is associated with.
'sourceMapFilename' => null,
// url of the map
'sourceMapURL' => null,
// absolute path to a file to write the map to
'sourceMapWriteTo' => null,
// output source contents?
'outputSourceFiles' => false,
// base path for filename normalization
'sourceMapRootpath' => '',
// base path for filename normalization
'sourceMapBasepath' => ''
];
/**
* The base64 VLQ encoder
*
* @var \ScssPhp\ScssPhp\SourceMap\Base64VLQ
*/
protected $encoder;
/**
* Array of mappings
*
* @var array
* @phpstan-var list<array{generated_line: int, generated_column: int, original_line: int, original_column: int, source_file: string}>
*/
protected $mappings = [];
/**
* Array of contents map
*
* @var array
*/
protected $contentsMap = [];
/**
* File to content map
*
* @var array<string, string>
*/
protected $sources = [];
/**
* @var array<string, int>
*/
protected $sourceKeys = [];
/**
* @var array
* @phpstan-var array{sourceRoot: string, sourceMapFilename: string|null, sourceMapURL: string|null, sourceMapWriteTo: string|null, outputSourceFiles: bool, sourceMapRootpath: string, sourceMapBasepath: string}
*/
private $options;
/**
* @phpstan-param array{sourceRoot?: string, sourceMapFilename?: string|null, sourceMapURL?: string|null, sourceMapWriteTo?: string|null, outputSourceFiles?: bool, sourceMapRootpath?: string, sourceMapBasepath?: string} $options
*/
public function __construct(array $options = [])
{
$this->options = array_replace($this->defaultOptions, $options);
$this->encoder = new Base64VLQ();
}
/**
* Adds a mapping
*
* @param int $generatedLine The line number in generated file
* @param int $generatedColumn The column number in generated file
* @param int $originalLine The line number in original file
* @param int $originalColumn The column number in original file
* @param string $sourceFile The original source file
*
* @return void
*/
public function addMapping($generatedLine, $generatedColumn, $originalLine, $originalColumn, $sourceFile)
{
$this->mappings[] = [
'generated_line' => $generatedLine,
'generated_column' => $generatedColumn,
'original_line' => $originalLine,
'original_column' => $originalColumn,
'source_file' => $sourceFile
];
$this->sources[$sourceFile] = $sourceFile;
}
/**
* Saves the source map to a file
*
* @param string $content The content to write
*
* @return string|null
*
* @throws \ScssPhp\ScssPhp\Exception\CompilerException If the file could not be saved
* @deprecated
*/
public function saveMap($content)
{
$file = $this->options['sourceMapWriteTo'];
assert($file !== null);
$dir = \dirname($file);
// directory does not exist
if (! is_dir($dir)) {
// FIXME: create the dir automatically?
throw new CompilerException(
sprintf('The directory "%s" does not exist. Cannot save the source map.', $dir)
);
}
// FIXME: proper saving, with dir write check!
if (file_put_contents($file, $content) === false) {
throw new CompilerException(sprintf('Cannot save the source map to "%s"', $file));
}
return $this->options['sourceMapURL'];
}
/**
* Generates the JSON source map
*
* @param string $prefix A prefix added in the output file, which needs to shift mappings
*
* @return string
*
* @see https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#
*/
public function generateJson($prefix = '')
{
$sourceMap = [];
$mappings = $this->generateMappings($prefix);
// File version (always the first entry in the object) and must be a positive integer.
$sourceMap['version'] = self::VERSION;
// An optional name of the generated code that this source map is associated with.
$file = $this->options['sourceMapFilename'];
if ($file) {
$sourceMap['file'] = $file;
}
// An optional source root, useful for relocating source files on a server or removing repeated values in the
// 'sources' entry. This value is prepended to the individual entries in the 'source' field.
$root = $this->options['sourceRoot'];
if ($root) {
$sourceMap['sourceRoot'] = $root;
}
// A list of original sources used by the 'mappings' entry.
$sourceMap['sources'] = [];
foreach ($this->sources as $sourceFilename) {
$sourceMap['sources'][] = $this->normalizeFilename($sourceFilename);
}
// A list of symbol names used by the 'mappings' entry.
$sourceMap['names'] = [];
// A string with the encoded mapping data.
$sourceMap['mappings'] = $mappings;
if ($this->options['outputSourceFiles']) {
// An optional list of source content, useful when the 'source' can't be hosted.
// The contents are listed in the same order as the sources above.
// 'null' may be used if some original sources should be retrieved by name.
$sourceMap['sourcesContent'] = $this->getSourcesContent();
}
// less.js compat fixes
if (\count($sourceMap['sources']) && empty($sourceMap['sourceRoot'])) {
unset($sourceMap['sourceRoot']);
}
$jsonSourceMap = json_encode($sourceMap, JSON_UNESCAPED_SLASHES);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \RuntimeException(json_last_error_msg());
}
assert($jsonSourceMap !== false);
return $jsonSourceMap;
}
/**
* Returns the sources contents
*
* @return string[]|null
*/
protected function getSourcesContent()
{
if (empty($this->sources)) {
return null;
}
$content = [];
foreach ($this->sources as $sourceFile) {
$content[] = file_get_contents($sourceFile);
}
return $content;
}
/**
* Generates the mappings string
*
* @param string $prefix A prefix added in the output file, which needs to shift mappings
*
* @return string
*/
public function generateMappings($prefix = '')
{
if (! \count($this->mappings)) {
return '';
}
$prefixLines = substr_count($prefix, "\n");
$lastPrefixNewLine = strrpos($prefix, "\n");
$lastPrefixLineStart = false === $lastPrefixNewLine ? 0 : $lastPrefixNewLine + 1;
$prefixColumn = strlen($prefix) - $lastPrefixLineStart;
$this->sourceKeys = array_flip(array_keys($this->sources));
// group mappings by generated line number.
$groupedMap = $groupedMapEncoded = [];
foreach ($this->mappings as $m) {
$groupedMap[$m['generated_line']][] = $m;
}
ksort($groupedMap);
$lastGeneratedLine = $lastOriginalIndex = $lastOriginalLine = $lastOriginalColumn = 0;
foreach ($groupedMap as $lineNumber => $lineMap) {
if ($lineNumber > 1) {
// The prefix only impacts the column for the first line of the original output
$prefixColumn = 0;
}
$lineNumber += $prefixLines;
while (++$lastGeneratedLine < $lineNumber) {
$groupedMapEncoded[] = ';';
}
$lineMapEncoded = [];
$lastGeneratedColumn = 0;
foreach ($lineMap as $m) {
$generatedColumn = $m['generated_column'] + $prefixColumn;
$mapEncoded = $this->encoder->encode($generatedColumn - $lastGeneratedColumn);
$lastGeneratedColumn = $generatedColumn;
// find the index
if ($m['source_file']) {
$index = $this->findFileIndex($m['source_file']);
if ($index !== false) {
$mapEncoded .= $this->encoder->encode($index - $lastOriginalIndex);
$lastOriginalIndex = $index;
// lines are stored 0-based in SourceMap spec version 3
$mapEncoded .= $this->encoder->encode($m['original_line'] - 1 - $lastOriginalLine);
$lastOriginalLine = $m['original_line'] - 1;
$mapEncoded .= $this->encoder->encode($m['original_column'] - $lastOriginalColumn);
$lastOriginalColumn = $m['original_column'];
}
}
$lineMapEncoded[] = $mapEncoded;
}
$groupedMapEncoded[] = implode(',', $lineMapEncoded) . ';';
}
return rtrim(implode($groupedMapEncoded), ';');
}
/**
* Finds the index for the filename
*
* @param string $filename
*
* @return int|false
*/
protected function findFileIndex($filename)
{
return $this->sourceKeys[$filename];
}
/**
* Normalize filename
*
* @param string $filename
*
* @return string
*/
protected function normalizeFilename($filename)
{
$filename = $this->fixWindowsPath($filename);
$rootpath = $this->options['sourceMapRootpath'];
$basePath = $this->options['sourceMapBasepath'];
// "Trim" the 'sourceMapBasepath' from the output filename.
if (\strlen($basePath) && strpos($filename, $basePath) === 0) {
$filename = substr($filename, \strlen($basePath));
}
// Remove extra leading path separators.
if (strpos($filename, '\\') === 0 || strpos($filename, '/') === 0) {
$filename = substr($filename, 1);
}
return $rootpath . $filename;
}
/**
* Fix windows paths
*
* @param string $path
* @param bool $addEndSlash
*
* @return string
*/
public function fixWindowsPath($path, $addEndSlash = false)
{
$slash = ($addEndSlash) ? '/' : '';
if (! empty($path)) {
$path = str_replace('\\', '/', $path);
$path = rtrim($path, '/') . $slash;
}
return $path;
}
}
| {'content_hash': 'ac5cc0346c463db7f9646793f3b2140c', 'timestamp': '', 'source': 'github', 'line_count': 382, 'max_line_length': 232, 'avg_line_length': 30.903141361256544, 'alnum_prop': 0.5678949597628123, 'repo_name': 'getgrav/grav-plugin-admin', 'id': 'ccd4f0261fe448bb8ab6fff79443e30ca5e84f05', 'size': '11964', 'binary': False, 'copies': '33', 'ref': 'refs/heads/develop', 'path': 'vendor/scssphp/scssphp/src/SourceMap/SourceMapGenerator.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '39102'}, {'name': 'JavaScript', 'bytes': '343485'}, {'name': 'PHP', 'bytes': '345355'}, {'name': 'SCSS', 'bytes': '348172'}, {'name': 'Shell', 'bytes': '491'}, {'name': 'Twig', 'bytes': '259007'}]} |
package net.ontopia.topicmaps.rest.v1.topicmap;
import net.ontopia.topicmaps.entry.TopicMapReferenceIF;
import net.ontopia.topicmaps.rest.resources.AbstractTransactionalResource;
import org.restlet.resource.Post;
public class TopicMapReloadResource extends AbstractTransactionalResource {
@Post
public void reload() {
TopicMapReferenceIF reference = getTopicMapReference();
if (reference.isOpen()) {
reference.close();
reference.open();
}
}
}
| {'content_hash': '37b60897cfc4d477d0cbf12fd58ce38a', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 75, 'avg_line_length': 23.3, 'alnum_prop': 0.7832618025751072, 'repo_name': 'ontopia/ontopia', 'id': 'b7da508ce64b6a6369f1f3513d23d906a60976ee', 'size': '1119', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ontopia-rest/src/main/java/net/ontopia/topicmaps/rest/v1/topicmap/TopicMapReloadResource.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '229'}, {'name': 'CSS', 'bytes': '102701'}, {'name': 'GAP', 'bytes': '55644'}, {'name': 'HTML', 'bytes': '56107'}, {'name': 'Java', 'bytes': '11884136'}, {'name': 'JavaScript', 'bytes': '365763'}, {'name': 'Lex', 'bytes': '19344'}, {'name': 'Python', 'bytes': '27528'}, {'name': 'SCSS', 'bytes': '6338'}, {'name': 'Shell', 'bytes': '202'}]} |
/**
* Created at 5:43:20 AM Jan 14, 2011
*/
package org.jbox2d.testbed.tests;
import java.util.Random;
import org.jbox2d.callbacks.TreeCallback;
import org.jbox2d.callbacks.TreeRayCastCallback;
import org.jbox2d.collision.AABB;
import org.jbox2d.collision.RayCastInput;
import org.jbox2d.collision.RayCastOutput;
import org.jbox2d.collision.broadphase.DynamicTree;
import org.jbox2d.collision.broadphase.DynamicTreeNode;
import org.jbox2d.common.Color3f;
import org.jbox2d.common.MathUtils;
import org.jbox2d.common.Settings;
import org.jbox2d.common.Vec2;
import org.jbox2d.pooling.arrays.Vec2Array;
import org.jbox2d.testbed.framework.TestbedSettings;
import org.jbox2d.testbed.framework.TestbedTest;
/**
* @author Daniel Murphy
*/
public class DynamicTreeTest extends TestbedTest implements TreeCallback,
TreeRayCastCallback {
int e_actorCount = 128;
float worldExtent;
float m_proxyExtent;
DynamicTree m_tree;
AABB m_queryAABB;
RayCastInput m_rayCastInput;
RayCastOutput m_rayCastOutput;
Actor m_rayActor;
Actor m_actors[] = new Actor[e_actorCount];
int m_stepCount;
boolean m_automated;
Random rand = new Random();
/**
* @see org.jbox2d.testbed.framework.TestbedTest#initTest(boolean)
*/
@Override
public void initTest(boolean argDeserialized) {
worldExtent = 15.0f;
m_proxyExtent = 0.5f;
m_tree = new DynamicTree();
for (int i = 0; i < e_actorCount; ++i) {
Actor actor = m_actors[i] = new Actor();
GetRandomAABB(actor.aabb);
actor.proxyId = m_tree.createProxy(actor.aabb, actor);
}
m_stepCount = 0;
float h = worldExtent;
m_queryAABB = new AABB();
m_queryAABB.lowerBound.set(-3.0f, -4.0f + h);
m_queryAABB.upperBound.set(5.0f, 6.0f + h);
m_rayCastInput = new RayCastInput();
m_rayCastInput.p1.set(-5.0f, 5.0f + h);
m_rayCastInput.p2.set(7.0f, -4.0f + h);
// m_rayCastInput.p1.set(0.0f, 2.0f + h);
// m_rayCastInput.p2.set(0.0f, -2.0f + h);
m_rayCastInput.maxFraction = 1.0f;
m_rayCastOutput = new RayCastOutput();
m_automated = false;
}
/**
* @see org.jbox2d.testbed.framework.TestbedTest#keyPressed(char, int)
*/
@Override
public void keyPressed(char argKeyChar, int argKeyCode) {
switch (argKeyChar) {
case 'a':
m_automated = !m_automated;
break;
case 'c':
CreateProxy();
break;
case 'd':
DestroyProxy();
break;
case 'm':
MoveProxy();
break;
}
}
private Vec2Array vecPool = new Vec2Array();
/**
* @see org.jbox2d.testbed.framework.TestbedTest#step(org.jbox2d.testbed.framework.TestbedSettings)
*/
@Override
public void step(TestbedSettings settings) {
m_rayActor = null;
for (int i = 0; i < e_actorCount; ++i) {
m_actors[i].fraction = 1.0f;
m_actors[i].overlap = false;
}
if (m_automated == true) {
int actionCount = MathUtils.max(1, e_actorCount >> 2);
for (int i = 0; i < actionCount; ++i) {
Action();
}
}
Query();
RayCast();
Vec2[] vecs = vecPool.get(4);
for (int i = 0; i < e_actorCount; ++i) {
Actor actor = m_actors[i];
if (actor.proxyId == null)
continue;
Color3f c = new Color3f(0.9f, 0.9f, 0.9f);
if (actor == m_rayActor && actor.overlap) {
c.set(0.9f, 0.6f, 0.6f);
} else if (actor == m_rayActor) {
c.set(0.6f, 0.9f, 0.6f);
} else if (actor.overlap) {
c.set(0.6f, 0.6f, 0.9f);
}
actor.aabb.getVertices(vecs);
getDebugDraw().drawPolygon(vecs, 4, c);
}
Color3f c = new Color3f(0.7f, 0.7f, 0.7f);
m_queryAABB.getVertices(vecs);
getDebugDraw().drawPolygon(vecs, 4, c);
getDebugDraw().drawSegment(m_rayCastInput.p1, m_rayCastInput.p2, c);
Color3f c1 = new Color3f(0.2f, 0.9f, 0.2f);
Color3f c2 = new Color3f(0.9f, 0.2f, 0.2f);
getDebugDraw().drawPoint(m_rayCastInput.p1, 6.0f, c1);
getDebugDraw().drawPoint(m_rayCastInput.p2, 6.0f, c2);
if (m_rayActor != null) {
Color3f cr = new Color3f(0.2f, 0.2f, 0.9f);
Vec2 p = m_rayCastInput.p2.sub(m_rayCastInput.p1)
.mulLocal(m_rayActor.fraction).addLocal(m_rayCastInput.p1);
getDebugDraw().drawPoint(p, 6.0f, cr);
}
++m_stepCount;
if (settings.getSetting(TestbedSettings.DrawTree).enabled) {
m_tree.drawTree(getDebugDraw());
}
m_textLine += 15;
getDebugDraw().drawString(5, m_textLine,
"(c)reate proxy, (d)estroy proxy, (a)utomate", Color3f.WHITE);
}
public boolean treeCallback(DynamicTreeNode proxyId) {
Actor actor = (Actor) proxyId.userData;
actor.overlap = AABB.testOverlap(m_queryAABB, actor.aabb);
return true;
}
public float raycastCallback(final RayCastInput input,
DynamicTreeNode proxyId) {
Actor actor = (Actor) proxyId.userData;
RayCastOutput output = new RayCastOutput();
boolean hit = actor.aabb.raycast(output, input, getWorld().getPool());
if (hit) {
m_rayCastOutput = output;
m_rayActor = actor;
m_rayActor.fraction = output.fraction;
return output.fraction;
}
return input.maxFraction;
}
public static class Actor {
AABB aabb = new AABB();
float fraction;
boolean overlap;
DynamicTreeNode proxyId;
}
public void GetRandomAABB(AABB aabb) {
Vec2 w = new Vec2();
w.set(2.0f * m_proxyExtent, 2.0f * m_proxyExtent);
// aabb.lowerBound.x = -m_proxyExtent;
// aabb.lowerBound.y = -m_proxyExtent + worldExtent;
aabb.lowerBound.x = MathUtils.randomFloat(rand, -worldExtent,
worldExtent);
aabb.lowerBound.y = MathUtils.randomFloat(rand, 0.0f,
2.0f * worldExtent);
aabb.upperBound.set(aabb.lowerBound).addLocal(w);
}
public void MoveAABB(AABB aabb) {
Vec2 d = new Vec2();
d.x = MathUtils.randomFloat(rand, -0.5f, 0.5f);
d.y = MathUtils.randomFloat(rand, -0.5f, 0.5f);
// d.x = 2.0f;
// d.y = 0.0f;
aabb.lowerBound.addLocal(d);
aabb.upperBound.addLocal(d);
Vec2 c0 = aabb.lowerBound.add(aabb.upperBound).mulLocal(.5f);
Vec2 min = new Vec2();
min.set(-worldExtent, 0.0f);
Vec2 max = new Vec2();
max.set(worldExtent, 2.0f * worldExtent);
Vec2 c = MathUtils.clamp(c0, min, max);
aabb.lowerBound.addLocal(c.sub(c0));
aabb.upperBound.addLocal(c.sub(c0));
}
public void CreateProxy() {
for (int i = 0; i < e_actorCount; ++i) {
int j = MathUtils.abs(rand.nextInt() % e_actorCount);
Actor actor = m_actors[j];
if (actor.proxyId == null) {
GetRandomAABB(actor.aabb);
actor.proxyId = m_tree.createProxy(actor.aabb, actor);
return;
}
}
}
public void DestroyProxy() {
for (int i = 0; i < e_actorCount; ++i) {
int j = MathUtils.abs(rand.nextInt() % e_actorCount);
Actor actor = m_actors[j];
if (actor.proxyId != null) {
m_tree.destroyProxy(actor.proxyId);
actor.proxyId = null;
return;
}
}
}
public void MoveProxy() {
for (int i = 0; i < e_actorCount; ++i) {
int j = MathUtils.abs(rand.nextInt() % e_actorCount);
Actor actor = m_actors[j];
if (actor.proxyId == null) {
continue;
}
AABB aabb0 = new AABB(actor.aabb);
MoveAABB(actor.aabb);
Vec2 displacement = actor.aabb.getCenter().sub(aabb0.getCenter());
m_tree.moveProxy(actor.proxyId, new AABB(actor.aabb), displacement);
return;
}
}
public void Action() {
int choice = MathUtils.abs(rand.nextInt() % 20);
switch (choice) {
case 0:
CreateProxy();
break;
case 1:
DestroyProxy();
break;
default:
MoveProxy();
}
}
public void Query() {
m_tree.query(this, m_queryAABB);
for (int i = 0; i < e_actorCount; ++i) {
if (m_actors[i].proxyId == null) {
continue;
}
boolean overlap = AABB.testOverlap(m_queryAABB, m_actors[i].aabb);
assert (overlap == m_actors[i].overlap);
}
}
public void RayCast() {
m_rayActor = null;
RayCastInput input = new RayCastInput();
input.set(m_rayCastInput);
// Ray cast against the dynamic tree.
m_tree.raycast(this, input);
// Brute force ray cast.
Actor bruteActor = null;
RayCastOutput bruteOutput = new RayCastOutput();
for (int i = 0; i < e_actorCount; ++i) {
if (m_actors[i].proxyId == null) {
continue;
}
RayCastOutput output = new RayCastOutput();
boolean hit = m_actors[i].aabb.raycast(output, input,
getWorld().getPool());
if (hit) {
bruteActor = m_actors[i];
bruteOutput = output;
input.maxFraction = output.fraction;
//input.set(m_rayCastInput);
}
}
if (bruteActor != null) {
assert (MathUtils.abs(bruteOutput.fraction
- m_rayCastOutput.fraction) <= Settings.EPSILON);
}
}
/**
* @see org.jbox2d.testbed.framework.TestbedTest#getTestName()
*/
@Override
public String getTestName() {
return "Dynamic Tree";
}
}
| {'content_hash': 'f34cc68dd613b6e6b1f48f3019602f0a', 'timestamp': '', 'source': 'github', 'line_count': 348, 'max_line_length': 100, 'avg_line_length': 24.43103448275862, 'alnum_prop': 0.661844271936015, 'repo_name': 'col726/game-engine-CMZ', 'id': '4229d48799cc54ec89351c68bd5e1a4402fb08b1', 'size': '10025', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'jbox2d-testbed/src/main/java/org/jbox2d/testbed/tests/DynamicTreeTest.java', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'C', 'bytes': '7'}, {'name': 'C++', 'bytes': '7'}, {'name': 'Java', 'bytes': '1152873'}, {'name': 'JavaScript', 'bytes': '373480'}, {'name': 'Shell', 'bytes': '2062'}]} |
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Debug = UnityEngine.Debug;
using Random = UnityEngine.Random;
public class GUIManager : MonoBehaviour {
public BrainScript Brain;
public GUIText GameOverText, ScoreText, RunningScoreText, RunningRoundText, RoundTimeText, EndGameText, RoundCountdownText;
private static GUIManager instance;
private List<Vector3> _movePositions;
private List<string> moves;
private readonly long _moveDisplayTime = 1500;
private readonly long _finalMoveDisplayTime = 3000;
public PrefabCol Prefabs;
// Use this for initialization
void Start () {
instance = this;
GameEventManager.GameStart += GameStart;
GameEventManager.GameOver += GameOver;
GameEventManager.RoundStart += RoundStart;
RunningRoundText.enabled = false;
RunningScoreText.enabled = false;
ScoreText.enabled = false;
GameOverText.enabled = false;
RoundTimeText.enabled = false;
EndGameText.enabled = false;
RoundCountdownText.enabled = false;
_movePositions = new List<Vector3>();
moves = new List<string>();
}
// Update is called once per frame
void Update () {
RunningScoreText.text = "Score: "+Brain.Score;
RunningRoundText.text = "Round "+Brain.Round;
RoundTimeText.text = "Time left: " + Brain.GetTimeLeft();
RoundCountdownText.text = Brain.GetCountdownLeft();
}
private void GameStart()
{
GameOverText.enabled = false;
ScoreText.enabled = false;
RunningScoreText.text = "Score: " + Brain.Score;
RunningRoundText.text = "Round: " + Brain.Round;
RunningRoundText.enabled = true;
RunningScoreText.enabled = true;
moves = new List<string>();
_movePositions = new List<Vector3>();
EndGameText.text = "";
}
private void GameOver()
{
RunningRoundText.enabled = false;
RunningScoreText.enabled = false;
RoundTimeText.enabled = false;
GameOverText.enabled = true;
ScoreText.enabled = true;
EndGameText.enabled = true;
ScoreText.text = "You achieved a score of "+Brain.Score+" points";
}
void StartRound() {
GameEventManager.StartRound();
}
public void EndGameReason(string text)
{
EndGameText.text = text;
}
public void SetNextMove(string move)
{
moves.Add(move);
var pos = GenerateVector();
while (_movePositions.Contains(pos))
{
pos = GenerateVector();
}
_movePositions.Add(pos);
RoundTimeText.enabled = false;
DisplayNewRound();
}
void DisplayNewRound() {
var roundPrefabObj = Instantiate(Prefabs.Round, new Vector3(0.5f, 0.5f, 0f), Quaternion.identity) as GameObject;
FadeoutText fadeoutObj;
if (roundPrefabObj == null || (fadeoutObj = roundPrefabObj.GetComponent<FadeoutText>()) == null) {
Debug.LogError("Prefabs.Round does not have a FadeoutText object attached");
return;
}
roundPrefabObj.guiText.text = "Round " + Brain.Round;
fadeoutObj.TextFaded += (script, obj) => DisplayMoves();
}
private void DisplayMoves(int index = 0) {
if (index < 0) index = 0;
if (index >= moves.Count) {
StartRound();
return;
}
var movePrefabObj = Instantiate(Prefabs.MoveToPerform, _movePositions[index], Quaternion.identity) as GameObject;
FadeoutText fadeoutObj;
if (movePrefabObj == null || (fadeoutObj = movePrefabObj.GetComponent<FadeoutText>()) == null) {
Debug.LogError("Prefabs.MoveToPerform does not have a FadeoutText object attached");
return;
}
movePrefabObj.guiText.text = moves[index];
fadeoutObj.TextFaded += (script, obj) => DisplayMoves(index + 1);
}
private static Vector3 GenerateVector() {
return new Vector3(Random.Range(0.2f, 0.75f), Random.Range(0.2f, 0.75f), 0);
}
public void RemoveCountdown()
{
RoundCountdownText.enabled = false;
RoundTimeText.enabled = true;
}
public void GainedPoints(int points, int moveIndex) {
var startPosition = _movePositions[moveIndex];
var pointsGainedObj = Instantiate(Prefabs.PointsScored, startPosition, Quaternion.identity) as GameObject;
if (pointsGainedObj == null || pointsGainedObj.GetComponent<GUIText>() == null) {
Debug.LogError("Prefabs.PointsScored does not have a GUIText object attached");
return;
}
var movePrefabObj = Instantiate(Prefabs.MoveCorrect, _movePositions[moveIndex], Quaternion.identity) as GameObject;
if (movePrefabObj == null || movePrefabObj.GetComponent<GUIText>() == null) {
Debug.LogError("Prefabs.MoveCorrect does not have a GUIText object attached");
return;
}
pointsGainedObj.guiText.text = "+" + points;
pointsGainedObj.guiText.pixelOffset = new Vector2(0, 15);
movePrefabObj.guiText.text = moves[moveIndex];
}
private void RoundStart()
{
RoundCountdownText.enabled = true;
}
[Serializable]
public struct PrefabCol {
public GameObject Round;
public GameObject MoveToPerform;
public GameObject MoveCorrect;
public GameObject MoveWrong;
public GameObject PointsScored;
}
}
| {'content_hash': '2540cf9abf773011bbe2429fc9570a6f', 'timestamp': '', 'source': 'github', 'line_count': 167, 'max_line_length': 127, 'avg_line_length': 33.43712574850299, 'alnum_prop': 0.6427292263610315, 'repo_name': 'webrokeit/DTU', 'id': 'bf08ea37e7d278856b249166fa406fdf160ba77d', 'size': '5586', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '02515 - Healthcare Technology/Remember training game/Assets/Scripts/GUIManager.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '536528'}, {'name': 'HTML', 'bytes': '3599'}, {'name': 'Java', 'bytes': '45404'}, {'name': 'Perl', 'bytes': '3072'}, {'name': 'Perl6', 'bytes': '33019'}, {'name': 'TeX', 'bytes': '443925'}]} |
/*
* 2012-3 Red Hat Inc. and/or its affiliates and other contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.rtgov.tests.platforms.jbossas.customevent.monitor;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.overlord.rtgov.active.collection.ActiveCollectionManager;
import org.overlord.rtgov.active.collection.ActiveCollectionManagerAccessor;
import org.overlord.rtgov.active.collection.ActiveList;
import org.overlord.rtgov.epn.EPNManager;
import org.overlord.rtgov.epn.EPNManagerAccessor;
import org.overlord.rtgov.epn.EventList;
import org.overlord.rtgov.epn.NotificationListener;
import org.overlord.rtgov.tests.platforms.jbossas.customevent.data.CustomActivityEvent;
/**
* This is the custom event monitor that receives node notifications
* from the EPN, and makes the events available via a REST API.
*
*/
@Path("/monitor")
@ApplicationScoped
public class CustomEventMonitor implements NotificationListener {
private static final String ACS_NAME = "CustomEventsResults";
private static final String CUSTOM_EVENTS_PROCESSED_SUBJECT = "CustomEventsProcessed";
private static final String CUSTOM_EVENTS_RESULTS_SUBJECT = "CustomEventsResults";
private static final Logger LOG=Logger.getLogger(CustomEventMonitor.class.getName());
private EPNManager _epnManager=null;
private ActiveCollectionManager _activeCollectionManager;
private java.util.List<CustomActivityEvent> _customEvents=
new java.util.ArrayList<CustomActivityEvent>();
private ActiveList _customEventsACS=null;
/**
* This is the default constructor.
*/
public CustomEventMonitor() {
try {
_epnManager = EPNManagerAccessor.getEPNManager();
_epnManager.addNotificationListener(CUSTOM_EVENTS_PROCESSED_SUBJECT, this);
_epnManager.addNotificationListener(CUSTOM_EVENTS_RESULTS_SUBJECT, this);
_activeCollectionManager = ActiveCollectionManagerAccessor.getActiveCollectionManager();
_customEventsACS = (ActiveList)_activeCollectionManager.getActiveCollection(ACS_NAME);
LOG.info("Custom Active Collection="+_customEventsACS+" Name="+ACS_NAME);
} catch (Exception e) {
LOG.log(Level.SEVERE, "Failed to initialize custom event monitor", e);
}
}
/**
* This method returns the list of custom activity events
* and then resets the list.
*
* @return The custom activity events
*/
@GET
@Path("/events")
@Produces("application/json")
public java.util.List<CustomActivityEvent> getCustomActivityEvents() {
java.util.List<CustomActivityEvent> ret=new java.util.ArrayList<CustomActivityEvent>(_customEvents);
_customEvents.clear();
return (ret);
}
/**
* This method returns the list of custom events from the active collection.
*
* @return The custom events
*/
@GET
@Path("/acsresults")
@Produces("application/json")
public java.util.List<CustomActivityEvent> getACSResults() {
java.util.List<CustomActivityEvent> ret=new java.util.ArrayList<CustomActivityEvent>();
LOG.info("Returning Custom Active Collection results (size="+_customEventsACS.getSize()+") ac="+_customEventsACS);
for (Object obj : _customEventsACS) {
if (obj instanceof CustomActivityEvent) {
ret.add((CustomActivityEvent)obj);
}
}
return (ret);
}
/**
* {@inheritDoc}
*/
public void notify(String subject, EventList events) {
System.out.println(">>> CUSTOM EVENT MONITOR: ("+subject+")");
for (java.io.Serializable event : events) {
System.out.println("\t"+event);
if (event instanceof CustomActivityEvent) {
_customEvents.add((CustomActivityEvent)event);
}
}
}
}
| {'content_hash': '03666e0c90b1be12b382ad46c4553d52', 'timestamp': '', 'source': 'github', 'line_count': 135, 'max_line_length': 122, 'avg_line_length': 35.02962962962963, 'alnum_prop': 0.6811165151194756, 'repo_name': 'djcoleman/rtgov', 'id': 'd35c73666e43c40c96762c0ff2511cbe7fad0d7b', 'size': '4729', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'tests/with-rtgov/custom_events/custom_events_monitor/src/main/java/org/overlord/rtgov/tests/platforms/jbossas/customevent/monitor/CustomEventMonitor.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '560'}, {'name': 'CSS', 'bytes': '21457'}, {'name': 'HTML', 'bytes': '75224'}, {'name': 'Java', 'bytes': '2777787'}, {'name': 'JavaScript', 'bytes': '31419'}, {'name': 'Shell', 'bytes': '2307'}, {'name': 'XSLT', 'bytes': '13053'}]} |
<!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 (9-Debian) on Thu Sep 28 23:12:54 GMT 2017 -->
<title>API Help (Dollar Core - API for writing dynamic Java 0.4.5195 Test API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="date" content="2017-09-28">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="jquery/jquery-ui.css" title="Style">
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="jquery/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="jquery/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]-->
<script type="text/javascript" src="jquery/jquery-1.10.2.js"></script>
<script type="text/javascript" src="jquery/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="API Help (Dollar Core - API for writing dynamic Java 0.4.5195 Test API)";
}
}
catch(err) {
}
//-->
var pathtoroot = "./";loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="fixedNav">
<!-- ========= 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="dollar/package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li><a href="dollar/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 class="navBarCell1Rev">Help</li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?help-doc.html" target="_top">Frames</a></li>
<li><a href="help-doc.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>
<ul class="navListSearch">
<li><span>SEARCH: </span>
<input type="text" id="search" value=" " disabled="disabled">
<input type="reset" id="reset" value=" " disabled="disabled">
</li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
</div>
<div class="navPadding"> </div>
<script type="text/javascript"><!--
$('.navPadding').css('padding-top', $('.fixedNav').css("height"));
//-->
</script>
<div class="header">
<h1 class="title">How This API Document Is Organized</h1>
<div class="subTitle">This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.</div>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<h2>Package</h2>
<p>Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain six categories:</p>
<ul>
<li>Interfaces (italic)</li>
<li>Classes</li>
<li>Enums</li>
<li>Exceptions</li>
<li>Errors</li>
<li>Annotation Types</li>
</ul>
</li>
<li class="blockList">
<h2>Class/Interface</h2>
<p>Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a class/interface description, summary tables, and detailed member descriptions:</p>
<ul>
<li>Class inheritance diagram</li>
<li>Direct Subclasses</li>
<li>All Known Subinterfaces</li>
<li>All Known Implementing Classes</li>
<li>Class/interface declaration</li>
<li>Class/interface description</li>
</ul>
<ul>
<li>Nested Class Summary</li>
<li>Field Summary</li>
<li>Constructor Summary</li>
<li>Method Summary</li>
</ul>
<ul>
<li>Field Detail</li>
<li>Constructor Detail</li>
<li>Method Detail</li>
</ul>
<p>Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.</p>
</li>
<li class="blockList">
<h2>Annotation Type</h2>
<p>Each annotation type has its own separate page with the following sections:</p>
<ul>
<li>Annotation Type declaration</li>
<li>Annotation Type description</li>
<li>Required Element Summary</li>
<li>Optional Element Summary</li>
<li>Element Detail</li>
</ul>
</li>
<li class="blockList">
<h2>Enum</h2>
<p>Each enum has its own separate page with the following sections:</p>
<ul>
<li>Enum declaration</li>
<li>Enum description</li>
<li>Enum Constant Summary</li>
<li>Enum Constant Detail</li>
</ul>
</li>
<li class="blockList">
<h2>Use</h2>
<p>Each documented package, class and interface has its own Use page. This page describes what packages, classes, methods, constructors and fields use any part of the given class or package. Given a class or interface A, its Use page includes subclasses of A, fields declared as A, methods that return A, and methods and constructors with parameters of type A. You can access this page by first going to the package, class or interface, then clicking on the "Use" link in the navigation bar.</p>
</li>
<li class="blockList">
<h2>Tree (Class Hierarchy)</h2>
<p>There is a <a href="overview-tree.html">Class Hierarchy</a> page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. The classes are organized by inheritance structure starting with <code>java.lang.Object</code>. The interfaces do not inherit from <code>java.lang.Object</code>.</p>
<ul>
<li>When viewing the Overview page, clicking on "Tree" displays the hierarchy for all packages.</li>
<li>When viewing a particular package, class or interface page, clicking "Tree" displays the hierarchy for only that package.</li>
</ul>
</li>
<li class="blockList">
<h2>Deprecated API</h2>
<p>The <a href="deprecated-list.html">Deprecated API</a> page lists all of the API that have been deprecated. A deprecated API is not recommended for use, generally due to improvements, and a replacement API is usually given. Deprecated APIs may be removed in future implementations.</p>
</li>
<li class="blockList">
<h2>Index</h2>
<p>The <a href="index-all.html">Index</a> contains an alphabetic list of all classes, interfaces, constructors, methods, and fields.</p>
</li>
<li class="blockList">
<h2>Prev/Next</h2>
<p>These links take you to the next or previous class, interface, package, or related page.</p>
</li>
<li class="blockList">
<h2>Frames/No Frames</h2>
<p>These links show and hide the HTML frames. All pages are available with or without frames.</p>
</li>
<li class="blockList">
<h2>All Classes</h2>
<p>The <a href="allclasses-noframe.html">All Classes</a> link shows all classes and interfaces except non-static nested types.</p>
</li>
<li class="blockList">
<h2>Serialized Form</h2>
<p>Each serializable or externalizable class has a description of its serialization fields and methods. This information is of interest to re-implementors, not to developers using the API. While there is no link in the navigation bar, you can get to this information by going to any serialized class and clicking "Serialized Form" in the "See also" section of the class description.</p>
</li>
<li class="blockList">
<h2>Constant Field Values</h2>
<p>The <a href="constant-values.html">Constant Field Values</a> page lists the static final fields and their values.</p>
</li>
</ul>
<span class="emphasizedPhrase">This help file applies to API documentation generated using the standard doclet.</span></div>
<!-- ======= 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="dollar/package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li><a href="dollar/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 class="navBarCell1Rev">Help</li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?help-doc.html" target="_top">Frames</a></li>
<li><a href="help-doc.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>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2014–2017. All rights reserved.</small></p>
</body>
</html>
| {'content_hash': 'ac529c5647b3dd354dfab006b015c845', 'timestamp': '', 'source': 'github', 'line_count': 252, 'max_line_length': 497, 'avg_line_length': 39.154761904761905, 'alnum_prop': 0.6998074389378737, 'repo_name': 'neilellis/dollar', 'id': '043cd4125122f6f5d894c7123ed52c91e017be42', 'size': '9867', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'docs/dev/dollar-core/testapidocs/help-doc.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '11224'}, {'name': 'HTML', 'bytes': '28375'}, {'name': 'Java', 'bytes': '619975'}, {'name': 'Shell', 'bytes': '5089'}]} |
package org.assertj.core.api.intarray;
import static org.assertj.core.test.AlwaysEqualComparator.alwaysEqual;
import static org.mockito.Mockito.verify;
import java.util.Comparator;
import org.assertj.core.api.IntArrayAssert;
import org.assertj.core.api.IntArrayAssertBaseTest;
/**
* Tests for <code>{@link IntArrayAssert#isSortedAccordingTo(Comparator)}</code>.
*
* @author Joel Costigliola
*/
class IntArrayAssert_isSortedAccordingToComparator_Test extends IntArrayAssertBaseTest {
private Comparator<Integer> comparator = alwaysEqual();
@Override
protected IntArrayAssert invoke_api_method() {
return assertions.isSortedAccordingTo(comparator);
}
@Override
protected void verify_internal_effects() {
verify(arrays).assertIsSortedAccordingToComparator(getInfo(assertions), getActual(assertions), comparator);
}
}
| {'content_hash': 'ac72eb90732d23b1c829bdff4982534d', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 111, 'avg_line_length': 28.266666666666666, 'alnum_prop': 0.7912735849056604, 'repo_name': 'joel-costigliola/assertj-core', 'id': '9b6d215a435f1a64eecb12c8b435d409bac753da', 'size': '1454', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'src/test/java/org/assertj/core/api/intarray/IntArrayAssert_isSortedAccordingToComparator_Test.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '13752510'}, {'name': 'Shell', 'bytes': '36956'}]} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '50f3d817b95d03cab55cda31e396a14d', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': 'ad6af015083bd07ea7c0c744702375a373ec1156', 'size': '199', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Chlorophyta/Ulvophyceae/Cladophorales/Cladophoraceae/Cladophora/Cladophora aegagropila/ Syn. Chloronitum aegagropila/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
<!DOCTYPE html>
<!--
Copyright (c) 2013 Intel Corporation.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of works must retain the original copyright notice, this list
of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original 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 Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this work without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "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 INTEL CORPORATION 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.
Authors:
Lin Wanming <[email protected]>
Li, Hao <[email protected]>
-->
<html>
<head>
<title>CSS3 Animations Test: CSS3Animations_animation-fill-mode_backwards</title>
<link rel="author" title="Intel" href="http://www.intel.com" />
<link rel="help" href="http://www.w3.org/TR/2012/WD-css3-animations-20120403/#animation-fill-mode-property" />
<meta name="flags" content="" />
<meta name="assert" content="Check if Animations.animation-fill-mode has value backwards" />
<script src="support/support.js"></script>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
</head>
<body>
<div id="log"></div>
<div id="test"></div>
<script>
test(function(){
var div = document.querySelector("#test");
div.style[headProp("animationFillMode")] = "backwards";
var cStyle = GetCurrentStyle("animationFillMode");
assert_equals(cStyle, "backwards", "The value of animation-fill-mode property");
}, document.title);
</script>
</body>
</html>
| {'content_hash': '8ec3adb3f1d490e2760cb1c11d75e160', 'timestamp': '', 'source': 'github', 'line_count': 56, 'max_line_length': 114, 'avg_line_length': 45.94642857142857, 'alnum_prop': 0.7302759424795958, 'repo_name': 'yugang/crosswalk-test-suite', 'id': '3d71200d2f804446be2336506bba70293a1be86f', 'size': '2573', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'webapi/tct-animations-css3-tests/animations/CSS3Animations_animation-fill-mode_backwards.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '3495'}, {'name': 'CSS', 'bytes': '1694855'}, {'name': 'Erlang', 'bytes': '2850'}, {'name': 'Java', 'bytes': '155590'}, {'name': 'JavaScript', 'bytes': '32256550'}, {'name': 'PHP', 'bytes': '43783'}, {'name': 'Perl', 'bytes': '1696'}, {'name': 'Python', 'bytes': '4215706'}, {'name': 'Shell', 'bytes': '638387'}, {'name': 'XSLT', 'bytes': '2143471'}]} |
import requests
from ..config import *
from ..core import *
from .returnvalue import ReturnValue
def load_requestHttp(obj):
req = RequestHttp()
obj.post = req.post
obj.get = req.get
class RequestHttp(object):
def __init__(self):
self.headers = HEADERS.copy() # 请求头
self.csrf_token = "" # token
if SESSION_EN: # 是否开启session回话
self.s = requests.Session()
else:
self.s = requests
def post(self, url=None, dheaders=None, dparams=None):
payload = get_post_param(dparams)
req = self.s.post(url, headers=(dheaders if dheaders != None else self.headers), params = payload)
data = {"ret":""} # ReturnValue 采用回填数据方式
ret = ReturnValue(data, req)
return data["ret"]
def get(self, url=None, dheaders=None, dparams=None):
req = self.s.get(url, headers=(dheaders if dheaders != None else self.headers), params = dparams)
return req
def get_headers(self):
return self.headers;
| {'content_hash': 'fedbc0d88942ab4304a8fb06fd462ade', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 106, 'avg_line_length': 30.647058823529413, 'alnum_prop': 0.6017274472168906, 'repo_name': 'lichengshuang/python', 'id': 'db3ad3696a65920b6a2d107fd8b80fe9d7526ec4', 'size': '1124', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'others/163music/drive/requesthttp.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '321'}, {'name': 'HTML', 'bytes': '68150'}, {'name': 'Python', 'bytes': '420936'}, {'name': 'Shell', 'bytes': '76121'}, {'name': 'Vim script', 'bytes': '27690'}]} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.