text
stringlengths
2
1.04M
meta
dict
package org.lilyproject.repository.impl.test; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.lilyproject.hadooptestfw.TestHelper; import org.lilyproject.repository.api.Repository; import org.lilyproject.repository.impl.BlobStoreAccessRegistry; public class RemoteBlobStoreTest extends AbstractBlobStoreTest { @BeforeClass public static void setUpBeforeClass() throws Exception { TestHelper.setupLogging(); repoSetup.setupCore(); repoSetup.setupRepository(); repoSetup.setupRemoteAccess(); repository = (Repository)repoSetup.getRepositoryManager().getDefaultRepository().getDefaultTable(); typeManager = repoSetup.getTypeManager(); blobManager = repoSetup.getBlobManager(); // Create a blobStoreAccessRegistry for testing purposes testBlobStoreAccessRegistry = new BlobStoreAccessRegistry(repoSetup.getRemoteBlobManager()); testBlobStoreAccessRegistry.setBlobStoreAccessFactory(repoSetup.getRemoteBlobStoreAccessFactory()); blobManager = repoSetup.getRemoteBlobManager(); } @AfterClass public static void tearDownAfterClass() throws Exception { repoSetup.stop(); } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } }
{ "content_hash": "0d4e9d133745c50b50343c5d83b441d5", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 107, "avg_line_length": 30.955555555555556, "alnum_prop": 0.7430007178750897, "repo_name": "NGDATA/lilyproject", "id": "f2193ec0b7157a81dc87e49999ccec9dcde08265", "size": "1993", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "cr/repository/test/src/test/java/org/lilyproject/repository/impl/test/RemoteBlobStoreTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "4869855" }, { "name": "Python", "bytes": "590" }, { "name": "Shell", "bytes": "59196" } ], "symlink_target": "" }
package ca.isda.web; import java.io.IOException; import java.text.DateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import ca.isda.domain.Content; import ca.isda.domain.Staff; import ca.isda.service.ContentService; import ca.isda.service.StaffService; import ca.isda.web.exceptions.PageNotFoundException; /** * Handles static page requests for the application. */ @Controller public class PageController { private static final Logger logger = Logger.getLogger(PageController.class); @Autowired private ContentService contentService; @Autowired private StaffService staffService; @Autowired private ReloadableResourceBundleMessageSource messageSource; /** * Simply selects the home view to render by returning its name. */ @RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET) public String home(Locale locale, Model model) { logger.info("home --> client locale is " + locale); logger.info("Home page !"); Date date = new Date(); DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); String formattedDate = dateFormat.format(date); model.addAttribute("serverTime", formattedDate); // Query Management Team List<Staff> managementTeam = staffService.getManagementTeam(); if (managementTeam == null) { logger.error("Failed to find management team!"); } model.addAttribute("managementTeam", managementTeam); String contentKey = "page.home"; String menuKey = "menu.home"; String content = getContent(contentKey, locale.toString()); // if page is not existing or not enabled, return to error page if (content == null) { logger.debug("Page content for home is not existing!"); throw new PageNotFoundException("home"); } else { model.addAttribute("content", content); String menuText = messageSource.getMessage("menu.home", null, locale); model.addAttribute("menuText", menuText); return "public/home"; } } //@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "IO Exception") @ExceptionHandler(IOException.class) public String ioError() { // Nothing to do return "500"; } @RequestMapping(value = "/about", method = RequestMethod.GET) public String about(Locale locale, Model model) throws IOException { logger.info("about --> client locale is " + locale); logger.info("About page !"); // Content content = contentService.findByKey("about.content", // locale.toString()); // String contentText = content.getContent(); // model.addAttribute("contentText", contentText); // // model.addAttribute("page", "about"); throw new IOException(" Test Spring MVC handle IOException"); // String pageText = messageSource.getMessage("menu.about", null, // locale); // model.addAttribute("pageText", pageText); // return "public/about"; } @RequestMapping(value = "/page/{page}", method = RequestMethod.GET) public String showPage(@PathVariable("page") String page, Locale locale, Model model) { logger.debug(page + " --> client locale is " + locale); String contentKey = "page." + page; String menuKey = "menu." + page; String content = getContent(contentKey, locale.toString()); // if page is not existing or not enabled, return to error page if (content == null) { logger.debug("Page content for " + page + " is not existing!"); throw new PageNotFoundException(page); } else { model.addAttribute("content", content); String menuText = messageSource.getMessage(menuKey, null, locale); model.addAttribute("menuText", menuText); return "public/page"; } } @ExceptionHandler(PageNotFoundException.class) public String handleResourceNotFoundException() { return "public/404"; } private String getContent(String key, String locale) { Content content = contentService.findByKey(key, locale); if (content == null) { return null; } else { return content.getContent(); } } }
{ "content_hash": "4b6e57df4e83e2db431fd5c4061cb583", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 85, "avg_line_length": 30.7248322147651, "alnum_prop": 0.7383136740934906, "repo_name": "vollov/isda-java", "id": "5ac486f90f6ebab222731f34f548fe9850d18e2b", "size": "4578", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/ca/isda/web/PageController.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3350" }, { "name": "HTML", "bytes": "9973" }, { "name": "Java", "bytes": "109539" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:security="http://www.springframework.org/schema/security" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd"> <context:annotation-config /> <!-- DATABASE SETUP --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="username" value="engblog" /> <property name="password" value="engblog" /> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/engblog?characterEncoding=UTF-8" /> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="persistenceUnitName" value="examplePU" /> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="database" value="MYSQL" /> <property name="generateDdl" value="true" /> <property name="showSql" value="true" /> </bean> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <bean id="newsEntryDao" class="com.engblog.www.angularrestspringsecurity.dao.newsentry.JpaNewsEntryDao"> </bean> <bean id="userDao" class="com.engblog.www.angularrestspringsecurity.dao.user.JpaUserDao"> </bean> <!--<bean id="dataBaseInitializer" class="com.engblog.www.angularrestspringsecurity.dao.DataBaseInitializer" init-method="initDataBase">--> <!--<constructor-arg ref="userDao" />--> <!--<constructor-arg ref="newsEntryDao" />--> <!--<constructor-arg ref="passwordEncoder" />--> <!--</bean>--> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- INIT REST COMPONENTS --> <context:component-scan base-package="com.engblog.www.angularrestspringsecurity.rest.resources" /> <bean id="objectMapper" class="org.codehaus.jackson.map.ObjectMapper" /> <!-- SPRING SECURITY SETUP --> <bean id="passwordEncoder" class="org.springframework.security.crypto.password.StandardPasswordEncoder"> <constructor-arg value="ThisIsASecretSoChangeMe" /> </bean> <security:authentication-manager id="authenticationManager"> <security:authentication-provider user-service-ref="userDao"> <security:password-encoder ref="passwordEncoder"></security:password-encoder> </security:authentication-provider> </security:authentication-manager> <security:http realm="Protected API" use-expressions="true" auto-config="false" create-session="stateless" entry-point-ref="unauthorizedEntryPoint" authentication-manager-ref="authenticationManager"> <security:custom-filter ref="authenticationTokenProcessingFilter" position="FORM_LOGIN_FILTER" /> <security:intercept-url pattern="/rest/user/authenticate" access="permitAll" /> <security:intercept-url method="GET" pattern="/rest/news/**" access="hasRole('user')" /> <security:intercept-url method="PUT" pattern="/rest/news/**" access="hasRole('admin')" /> <security:intercept-url method="POST" pattern="/rest/news/**" access="hasRole('admin')" /> <security:intercept-url method="DELETE" pattern="/rest/news/**" access="hasRole('admin')" /> </security:http> <bean id="unauthorizedEntryPoint" class="com.engblog.www.angularrestspringsecurity.rest.UnauthorizedEntryPoint" /> <bean class="com.engblog.www.angularrestspringsecurity.rest.AuthenticationTokenProcessingFilter" id="authenticationTokenProcessingFilter"> <constructor-arg ref="userDao" /> </bean> </beans>
{ "content_hash": "0f8da078d73b0db0ba46fcc00d0824b1", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 140, "avg_line_length": 45.02884615384615, "alnum_prop": 0.7443946188340808, "repo_name": "phoenixzsun/engblog", "id": "eb57cf2095f64e71abb6d9c2e15fd7e0a63f7866", "size": "4683", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/resources/context.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "257" }, { "name": "HTML", "bytes": "4870" }, { "name": "Java", "bytes": "23906" }, { "name": "JavaScript", "bytes": "780344" } ], "symlink_target": "" }
// Copyright © 2013-2022 Andy Goryachev <andy@goryachev.com> package goryachev.swing; import goryachev.common.log.Log; import goryachev.swing.img.jhlabs.GaussianFilter; import goryachev.swing.img.mortennobel.ResampleOp; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; /** * Image scaler utility suitable for generating scaled images and thumbnails. * Generates scaled image with inidividually settable: * <pre> * - outer margin * - wraparound shadow (angled shadow TODO) * - border * - padding * - image */ public class ImageScaler { protected static final Log log = Log.get("ImageScaler"); private int width; private int height; private int margin; private int border; private Color borderColor; private int padding; private Color paddingColor; private Color background; private int shadowAlpha; private int shadowAngle; private int shadowDepth; private CAlignment horizontalAlignment = CAlignment.CENTER; private CAlignment verticalAlignment = CAlignment.CENTER; private boolean trim; private boolean throwException; public ImageScaler() { } /** Set image background, null results in a transparent background. */ public void setBackground(Color c) { background = c; } /** Sets overall output image size */ public void setSize(int width, int height) { this.width = width; this.height = height; } public int getWidth() { return width; } public int getHeight() { return height; } /** Sets outer margin */ public void setMargin(int x) { this.margin = x; } /** Sets one-pixel border of the specified color */ public void setBorder(Color c) { setBorder(c, 1); } /** Sets the thickness and color of the border. */ public void setBorder(Color c, int thickness) { border = thickness; borderColor = c; } /** Sets the thickness and color of the padding between border and the bitmap */ public void setPadding(Color c, int thickness) { paddingColor = c; padding = thickness; } /** Sets shadow depth in pixels. */ public void setShadow(int depth) { setShadow(64, -1, depth); } /** * Sets wraparound shadow parameters. The shadow will wrap around the scaled image. * * @param alpha - shadow alpha (0: fully transparent, 255:fully opaqie) * @param depth - shadow depth */ public void setShadow(int alpha, int depth) { setShadow(alpha, -1, depth); } /** * Sets directional shadow parameters. * * @param alpha - shadow alpha (0: fully transparent, 255:fully opaqie) * @param degrees - shadow angle in degrees (0...359). Negative value would create a wrap-around shadow * @param depth - shadow depth */ public void setShadow(int alpha, int degrees, int depth) { this.shadowAlpha = alpha; this.shadowAngle = degrees; this.shadowDepth = depth; } public int getShadowAngle() { return shadowAngle; } /** Sets vertical image alignment */ public void setVerticalAlignment(CAlignment a) { switch(a) { case TOP: case BOTTOM: case CENTER: verticalAlignment = a; break; default: throw new IllegalArgumentException("top, bottom, center: " + a); } } /** Sets horizontal image alignment */ public void setHorizontalAlignment(CAlignment a) { switch(a) { case LEADING: case TRAILING: case CENTER: horizontalAlignment = a; break; default: throw new IllegalArgumentException("left, right, center: " + a); } } /** Sets scale mode to shrink the image as required to fit into the image area */ public void setScaleModeShrink() { trim = false; } /** Sets scale mode to trim the image as necessary to fill all of the available image area */ public void setScaleModeTrim() { trim = true; } /** Controls whether an exception will be thrown by the scaleImage() method, or to generate an red-filled image in case of an error. */ public void setThrowException(boolean on) { throwException = on; } /** generates a scaled image */ public BufferedImage scaleImage(Image sourceImage) { BufferedImage source; if(sourceImage == null) { source = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); } else { source = ImageTools.toBufferedImage(sourceImage); } BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); try { // background if(background != null) { g.setColor(background); g.fillRect(0, 0, width, height); } // available image area, assuming symmetric shadow and all other parameters int corner = margin + border + padding + shadowDepth; int tw = width - corner - corner; int th = height - corner - corner; if(tw < 1) { throw new Exception("target image width is too small"); } if(th < 1) { throw new Exception("target image height is too small"); } // scale the image double sx = tw / (double)source.getWidth(); double sy = th / (double)source.getHeight(); BufferedImage scaled; boolean fitWidth; if(trim) { if(sx > sy) { fitWidth = true; } else { fitWidth = false; } BufferedImage im = resize(source, tw, th, fitWidth); // crop if(im.getWidth() > tw) { int x = (im.getWidth() - tw) / 2; scaled = im.getSubimage(x, 0, tw, im.getHeight()); } else if(im.getHeight() > th) { int y = (im.getHeight() - th) / 2; scaled = im.getSubimage(0, y, im.getWidth(), th); } else { scaled = im; } } else { int tw2; int th2; double scale = Math.min(sx, sy); if(sx > sy) { fitWidth = false; tw2 = (int)Math.round(image.getWidth() * scale); th2 = th; } else { fitWidth = true; tw2 = tw; th2 = (int)Math.round(image.getHeight() * scale); } scaled = resize(source, tw2, th2, fitWidth); } // scaled image offsets and size int sw = scaled.getWidth(); int sh = scaled.getHeight(); int dx = tw - sw; int dy = th - sh; if(dx > 0) { switch(horizontalAlignment) { case LEADING: dx = 0; break; case TRAILING: break; default: dx /= 2; break; } } else if(dx < 0) { throw new Error("dx=" + dx); } if(dy > 0) { switch(verticalAlignment) { case TOP: dy = 0; break; case BOTTOM: break; default: dy /= 2; break; } } else if(dy < 0) { throw new Error("dy=" + dy); } // shadow if(shadowDepth > 0) { // TODO shadow angle BufferedImage black = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = black.createGraphics(); try { g2.setColor(new Color(0, 0, 0, shadowAlpha)); int x = margin + shadowDepth + dx; int y = margin + shadowDepth + dy; int d = padding + padding + border + border; g2.fillRect(x, y, sw + d, sh + d); } finally { g2.dispose(); } GaussianFilter f = new GaussianFilter(shadowDepth); BufferedImage shadowImage = f.filter(black, null); g.drawImage(shadowImage, 0, 0, null); } // padding if(paddingColor != null) { int pcorner = margin + shadowDepth + border; int padding2 = padding + padding; g.setColor(paddingColor); g.fillRect(pcorner + dx, pcorner + dy, sw + padding2, sh + padding2); } // scaled image g.drawImage(scaled, corner + dx, corner + dy, null); // border if(borderColor != null) { g.setColor(borderColor); for(int i=0; i<border; i++) { int x = margin + shadowDepth + dx + i; int y = margin + shadowDepth + dy + i; int dd = padding + padding + border + border - i - i; g.drawRect(x, y, sw + dd - 1, sh + dd - 1); } } } catch(Exception e) { if(throwException) { throw new Error(e); } // make it obvious log.error(e); g.setColor(Color.red); g.fillRect(0, 0, width, height); } finally { g.dispose(); } return image; } // single-core resize public static BufferedImage resize_OLD(Image image, boolean hasAlpha, int width, int height, boolean fitWidth) { int w = image.getWidth(null); int h = image.getHeight(null); if(fitWidth) { height = h * width / w; } else { width = w * height / h; } BufferedImage im = new BufferedImage(width, height, hasAlpha ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_3BYTE_BGR); Graphics2D g = im.createGraphics(); try { if(fitWidth) { g.drawImage(image.getScaledInstance(width, -1, Image.SCALE_SMOOTH), 0, 0, null); } else { g.drawImage(image.getScaledInstance(-1, height, Image.SCALE_SMOOTH), 0, 0, null); } } finally { g.dispose(); } return im; } /** single-threaded image resize operation */ public static BufferedImage resize(Image image, int width, int height, boolean fitWidth) { return resize(image, width, height, fitWidth, 1); } /** multi-threaded image resize operation */ public static BufferedImage resize(Image image, int width, int height, boolean fitWidth, int numberOfThreads) { int w = image.getWidth(null); int h = image.getHeight(null); if(fitWidth) { height = h * width / w; } else { width = w * height / h; } BufferedImage src = ImageTools.toBufferedImage(image); ResampleOp op = new ResampleOp(width, height); op.setNumberOfThreads(numberOfThreads); //op.setUnsharpenMask(AdvancedResizeOp.UnsharpenMask.VerySharp); return op.filter(src, null); } }
{ "content_hash": "f7f8354c37bce513d45bb6658d9eece5", "timestamp": "", "source": "github", "line_count": 470, "max_line_length": 136, "avg_line_length": 21.642553191489363, "alnum_prop": 0.601651592607157, "repo_name": "andy-goryachev/PasswordSafe", "id": "e045aade11b1d38ad64b5ede9552339d63c38d99", "size": "10173", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/goryachev/swing/ImageScaler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "70" }, { "name": "Java", "bytes": "2262407" } ], "symlink_target": "" }
package com.b2international.snowowl.datastore.request; import com.b2international.snowowl.datastore.request.repository.RepositoryGetRequestBuilder; import com.b2international.snowowl.datastore.request.repository.RepositorySearchRequestBuilder; import com.b2international.snowowl.datastore.request.system.ServerInfoGetRequestBuilder; /** * The central class of Snow Owl's terminology independent Java APIs. * @since 4.5 */ public final class RepositoryRequests { private RepositoryRequests() {} /** * Returns the central class that provides access the server's branching features. * @return central branching class with access to branching features */ public static Branching branching() { return new Branching(); } /** * Returns the central class that provides access the server's revision control * merging features. * @return central merging class with access to merging features */ public static Merging merging() { return new Merging(); } /** * Returns the central class that provides access the server's review features * @return central review class with access to review features */ public static Reviews reviews() { return new Reviews(); } public static MergeReviews mergeReviews() { return new MergeReviews(); } public static CommitInfoRequests commitInfos() { return new CommitInfoRequests(); } public static RepositoryBulkReadRequestBuilder prepareBulkRead() { return new RepositoryBulkReadRequestBuilder(); } public static RepositorySearchRequestBuilder prepareSearch() { return new RepositorySearchRequestBuilder(); } public static RepositoryGetRequestBuilder prepareGet(String repositoryId) { return new RepositoryGetRequestBuilder(repositoryId); } public static ServerInfoGetRequestBuilder prepareGetServerInfo() { return new ServerInfoGetRequestBuilder(); } }
{ "content_hash": "80a6a910f7bf8e55f25ee34768b4da2f", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 95, "avg_line_length": 28.646153846153847, "alnum_prop": 0.7787325456498388, "repo_name": "IHTSDO/snow-owl", "id": "27bba324fefee552a95d7d966a36d8cf18e690fe", "size": "2489", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/com.b2international.snowowl.datastore/src/com/b2international/snowowl/datastore/request/RepositoryRequests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "12031" }, { "name": "CSS", "bytes": "97278" }, { "name": "ECL", "bytes": "27450" }, { "name": "GAP", "bytes": "215641" }, { "name": "Groovy", "bytes": "71763" }, { "name": "HTML", "bytes": "11708" }, { "name": "Java", "bytes": "15201642" }, { "name": "JavaScript", "bytes": "5838380" }, { "name": "Prolog", "bytes": "6673" }, { "name": "Shell", "bytes": "107759" }, { "name": "Xtend", "bytes": "13494" } ], "symlink_target": "" }
<?php namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use AppBundle\Serializer\JsonSerializer; class PromotionController extends AbstractController{ private $promotionService; public function __construct(PromotionService $service){ $this->promotionService = $service; } /** * @Route("/promotion/all", name="getAllOpen") */ public function getAllOpenPromotions(Request $request){ return JsonSerializer::serialize($service->getAllActivePromotions()); } }
{ "content_hash": "abe67fa8e6929f5e117b0e4d6f8eac79", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 77, "avg_line_length": 28.4, "alnum_prop": 0.7056338028169014, "repo_name": "jvbijleveld/ruilen", "id": "721aaf762b171e7b25e7e1ad5555313b88b7e427", "size": "710", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AppBundle/Controller/PromotionController.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "3605" }, { "name": "HTML", "bytes": "4942" }, { "name": "PHP", "bytes": "76892" } ], "symlink_target": "" }
layout: page title : Archive header : Post Archive categories: [AllSites] group: navigation_old nav_home_class: "" nav_blog_class: "" nav_archive_class: "active" nav_tags_class: "" --- {% include JB/setup %} {% assign posts_collate = site.posts %} {% include JB/posts_collate %}
{ "content_hash": "70472fbdc33f5f6ca4281cfbf4e4e8af", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 39, "avg_line_length": 19.928571428571427, "alnum_prop": 0.6953405017921147, "repo_name": "groundh0g/groundh0g.github.io", "id": "f2c69a98ec9e1f72bff8694180873e9c63c54edb", "size": "283", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "archive.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1032" }, { "name": "HTML", "bytes": "32903" }, { "name": "JavaScript", "bytes": "735" }, { "name": "Ruby", "bytes": "11807" } ], "symlink_target": "" }
package com.salesmanager.core.business.services.customer.attribute; import java.util.List; import com.salesmanager.core.business.exception.ServiceException; import com.salesmanager.core.business.services.common.generic.SalesManagerEntityService; import com.salesmanager.core.model.customer.attribute.CustomerOption; import com.salesmanager.core.model.merchant.MerchantStore; import com.salesmanager.core.model.reference.language.Language; public interface CustomerOptionService extends SalesManagerEntityService<Long, CustomerOption> { List<CustomerOption> listByStore(MerchantStore store, Language language) throws ServiceException; void saveOrUpdate(CustomerOption entity) throws ServiceException; CustomerOption getByCode(MerchantStore store, String optionCode); }
{ "content_hash": "27004324d682f586b8a5d990bd6daa7f", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 96, "avg_line_length": 28.178571428571427, "alnum_prop": 0.8453738910012675, "repo_name": "shopizer-ecommerce/shopizer", "id": "aa8969d524f3b385ef695230e08f2efe9bb6a162", "size": "789", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "sm-core/src/main/java/com/salesmanager/core/business/services/customer/attribute/CustomerOptionService.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "203" }, { "name": "FreeMarker", "bytes": "111592" }, { "name": "Java", "bytes": "3600819" } ], "symlink_target": "" }
using Toggl.Core.Analytics; namespace Toggl.Core.UI.Models { public struct OnboardingScrollParameters { public OnboardingScrollAction Action; public OnboardingScrollDirection Direction; public int PageNumber; } }
{ "content_hash": "afa43a5c84476953e745487c7ac4e683", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 51, "avg_line_length": 22.727272727272727, "alnum_prop": 0.72, "repo_name": "toggl/mobileapp", "id": "affd2c0f937b6f6cb653e76c545e1944bbeadbb0", "size": "250", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "Toggl.Core.UI/Models/OnboardingScrollParameters.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "5733490" }, { "name": "Makefile", "bytes": "847" }, { "name": "Objective-C", "bytes": "41986" }, { "name": "Shell", "bytes": "3407" } ], "symlink_target": "" }
from corehq.util.urlvalidate.urlvalidate import ( PossibleSSRFAttempt, validate_user_input_url, ) from corehq.apps.sms.models import SMSBase from corehq.util.metrics import metrics_counter def verify_sms_url(url, msg, backend): try: validate_user_input_url(url) except PossibleSSRFAttempt as e: metrics_counter('commcare.sms.ssrf_attempt', tags={ 'domain': msg.domain, 'src': type(backend).__name__, 'reason': e.reason }) msg.set_system_error(SMSBase.ERROR_FAULTY_GATEWAY_CONFIGURATION) raise
{ "content_hash": "ef3d1571a3aed3a24df4baffbcc6068a", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 72, "avg_line_length": 28.047619047619047, "alnum_prop": 0.6553480475382003, "repo_name": "dimagi/commcare-hq", "id": "ba03b875f1a3ba108e73bbc56cfa6730a8dc9704", "size": "589", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "corehq/messaging/smsbackends/http/sms_sending.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "82928" }, { "name": "Dockerfile", "bytes": "2341" }, { "name": "HTML", "bytes": "2589268" }, { "name": "JavaScript", "bytes": "5889543" }, { "name": "Jinja", "bytes": "3693" }, { "name": "Less", "bytes": "176180" }, { "name": "Makefile", "bytes": "1622" }, { "name": "PHP", "bytes": "2232" }, { "name": "PLpgSQL", "bytes": "66704" }, { "name": "Python", "bytes": "21779773" }, { "name": "Roff", "bytes": "150" }, { "name": "Shell", "bytes": "67473" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.borntodieee.pintugame" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="23" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@drawable/ic_puzzle_game" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".activity.SplashActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".activity.MainActivity" /> <activity android:name=".activity.PuzzleMain" /> <activity android:name="net.youmi.android.AdBrowser" android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout" android:theme="@android:style/Theme.Light.NoTitleBar" > </activity> <service android:name="net.youmi.android.AdService" android:exported="false" > </service> <receiver android:name="net.youmi.android.AdReceiver" > <intent-filter> <action android:name="android.intent.action.PACKAGE_ADDED" /> <data android:scheme="package" /> </intent-filter> </receiver> </application> </manifest>
{ "content_hash": "97b85d1386541804c84a3c0e54ff9495", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 95, "avg_line_length": 39.75, "alnum_prop": 0.6397124887690926, "repo_name": "Borntodieee/pintugame", "id": "f6fcfdec5b8951b06a25eda06bc204695810ab74", "size": "2226", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AndroidManifest.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "47768" } ], "symlink_target": "" }
<?php // Connexion à la base de données try { $dbh = new PDO('mysql:host=mayotte.goulagoula.webcup.fr;dbname=goulagoula', "goulagoula", "[BGbKJb63OF]"); } catch(Exception $e) { die('Erreur : '.$e->getMessage()); } // Insertion du message à l'aide d'une requête préparée $req = $bdd->prepare('INSERT INTO minichat (pseudo, message) VALUES(?, ?)'); $req->execute(array($_POST['pseudo'], $_POST['message'])); // Redirection du visiteur vers la page du minichat header('Location: minichat.php'); ?>
{ "content_hash": "ad315dc34bac3f0defed07fc35137120", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 106, "avg_line_length": 15.727272727272727, "alnum_prop": 0.6551059730250481, "repo_name": "toiha/webcup-2017-goulagoula", "id": "6f8acdbf8c09a8439dda9d9f24678963ad8484ff", "size": "525", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "minichat_post.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "165459" }, { "name": "JavaScript", "bytes": "353970" }, { "name": "PHP", "bytes": "52181" } ], "symlink_target": "" }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.ipmi.protocol.packet.ipmi.command.sol; import org.anarres.ipmi.protocol.client.visitor.IpmiClientIpmiCommandHandler; import org.anarres.ipmi.protocol.client.visitor.IpmiHandlerContext; import org.anarres.ipmi.protocol.packet.ipmi.IpmiCommandName; import org.anarres.ipmi.protocol.packet.ipmi.command.AbstractIpmiConfigurationParametersRequest; /** * [IPMI2] Section 26.3, table 26-4, page 376. * * @author shevek */ public class GetSOLConfigurationParametersRequest extends AbstractIpmiConfigurationParametersRequest { @Override public IpmiCommandName getCommandName() { return IpmiCommandName.GetSOLConfigurationParameters; } @Override public void apply(IpmiClientIpmiCommandHandler handler, IpmiHandlerContext context) { handler.handleGetSOLConfigurationParametersRequest(context, this); } }
{ "content_hash": "a4faf0a30ce2a491f3b8a29067581a50", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 102, "avg_line_length": 34.357142857142854, "alnum_prop": 0.7900207900207901, "repo_name": "shevek/ipmi4j", "id": "41bc09a90f171d28aa97c59f86ca419a8d20b317", "size": "962", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ipmi-protocol/src/main/java/org/anarres/ipmi/protocol/packet/ipmi/command/sol/GetSOLConfigurationParametersRequest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "105" }, { "name": "Java", "bytes": "581884" }, { "name": "Perl", "bytes": "3265" } ], "symlink_target": "" }
<?php $this->breadcrumbs=array( '品牌'=>array('index'), $model->name, ); ?> <?php $this->widget('bootstrap.widgets.TbDetailView',array( 'data'=>$model, 'attributes'=>array( 'id', 'name', array( 'name'=>'logo', 'type'=>'image', 'value'=>CHtml::image(Yii::app()->params['imgPath'].$model->logo), ), 'desc', 'site_url', 'sort_order', array( 'name'=>'is_show', 'value'=>Lookup::item("IsShow",$model->is_show), ), array( 'name'=>'category_id', 'value'=>Category::model()->getAttributeByPk($model->category_id,'name') ), ), )); ?> <div class="form-actions"> <?php $this->widget('bootstrap.widgets.TbButton', array('label' => '编辑','type' => 'primary','size' => 'small','url' => array('update','id'=>$model->id))); ?> <?php $this->widget('bootstrap.widgets.TbButton', array('label' => '新建','type' => 'primary','size' => 'small','url' => array('create'))); ?> </div>
{ "content_hash": "eff329f272c19d8b41c3d88885fc5e8b", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 159, "avg_line_length": 26.794117647058822, "alnum_prop": 0.5718990120746432, "repo_name": "baoweikai/yoyoke", "id": "7aece1c172291bf70a54766719932cb3aa7174d1", "size": "923", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "backend/views/brand/view.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1989286" }, { "name": "JavaScript", "bytes": "5477580" }, { "name": "PHP", "bytes": "6561310" } ], "symlink_target": "" }
package com.github.solairerove.web.rest; import com.github.solairerove.config.DefaultProfileUtil; import io.github.jhipster.config.JHipsterProperties; import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Resource to return information about the currently running Spring profiles. */ @RestController @RequestMapping("/api") public class ProfileInfoResource { private final Environment env; private final JHipsterProperties jHipsterProperties; public ProfileInfoResource(Environment env, JHipsterProperties jHipsterProperties) { this.env = env; this.jHipsterProperties = jHipsterProperties; } @GetMapping("/profile-info") public ProfileInfoVM getActiveProfiles() { String[] activeProfiles = DefaultProfileUtil.getActiveProfiles(env); return new ProfileInfoVM(activeProfiles, getRibbonEnv(activeProfiles)); } private String getRibbonEnv(String[] activeProfiles) { String[] displayOnActiveProfiles = jHipsterProperties.getRibbon().getDisplayOnActiveProfiles(); if (displayOnActiveProfiles == null) { return null; } List<String> ribbonProfiles = new ArrayList<>(Arrays.asList(displayOnActiveProfiles)); List<String> springBootProfiles = Arrays.asList(activeProfiles); ribbonProfiles.retainAll(springBootProfiles); if (!ribbonProfiles.isEmpty()) { return ribbonProfiles.get(0); } return null; } class ProfileInfoVM { private String[] activeProfiles; private String ribbonEnv; ProfileInfoVM(String[] activeProfiles, String ribbonEnv) { this.activeProfiles = activeProfiles; this.ribbonEnv = ribbonEnv; } public String[] getActiveProfiles() { return activeProfiles; } public String getRibbonEnv() { return ribbonEnv; } } }
{ "content_hash": "6121a1ee2f8f4b6819337940ab00c352", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 103, "avg_line_length": 29.63768115942029, "alnum_prop": 0.6953545232273839, "repo_name": "solairerove/woodstock", "id": "eff648a0cc6d83ea35fa8a45d1e2bd46061b054b", "size": "2045", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/github/solairerove/web/rest/ProfileInfoResource.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8951" }, { "name": "HTML", "bytes": "168434" }, { "name": "Java", "bytes": "420344" }, { "name": "JavaScript", "bytes": "272949" } ], "symlink_target": "" }
![awwyiss](https://github.com/espilioto/TFOI/blob/master/TFOI/Resources/logoNoShadow.png?raw=true) # The Finding Of Items A run tracker and logger for The Binding of Isaac: Afterbirth+ ### Download [Here](http://moddingofisaac.com/mod/900/thefindingofitems) ### Features * Seed, character, item, floor + curse, boss and time identification for current run. * Run history analyzing various stats (char, items, bosses, time etc) * Item collection displaying the icon, name, flavor text, detailed stats and run statistics for each one. * Character and boss collections displaying run statistics for each one. #### Usage Windows: Just decompress and run. You may need to update the Microsoft .net Framework. Linux: Unfortunately, WPF didn't work with Wine last time I checked. #### Backstory It all started when I realized that I had played hundreds of hours of Isaac, but had no way to compare or analyze my runs, except for my achievements and the Stats screen of course. But that wasn't even remotely enough. I then remembered a similar app existing for Hearthstone. Off I went to Google, and there it was, the [RebirthItemTracker]. Having that as a base, I started developing TFOI (and using it as a reason to play more Isaac). #### Credits and thanks * [NICALiS] and [Edmund McMillen] for making this awesome game. * [This](https://github.com/Hyphen-ated/RebirthItemTracker>) project that really helped and inspired me. * Rick and his [unpacker](http://svn.gib.me/builds/rebirth/). ~THANK YOU BASED RICK~ * My friend, Eddy Pasterino, for beta testing (usually against his will). ### Development This basically is a text parser that reads the game's log. It identifies certain events (like picking up an item) and presents them to the user, so that anyone can catch up with just a glance. When the run finishes, it inserts the run's data into a local SQLite database. That data will be available to the user through various screens like: * Run log * Item-related data * Boss-related data * Character-related data #### *Todos* * Check out if greed mode can be properly logged * Run entry manipulation * More testing! #### Known bugs * The run timer doesn't stop when the run finishes * The run timer resets if you hit back while doing a run ### License [MIT] [NICALiS]: <http://nicalis.com> [Edmund McMillen]: <https://twitter.com/edmundmcmillen> [RebirthItemTracker]: <https://github.com/Hyphen-ated/RebirthItemTracker> [MIT]:<http://choosealicense.com/licenses/mit/>
{ "content_hash": "f5aff787e2d0e27cb450150566f047e4", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 181, "avg_line_length": 42.93103448275862, "alnum_prop": 0.7578313253012048, "repo_name": "espilioto/TFOI", "id": "a3625b855bb95c87fbb59abcaa04f1a41f5b66ed", "size": "2490", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "705431" }, { "name": "PowerShell", "bytes": "3737" } ], "symlink_target": "" }
//Generated by the Argon Build System #include "btSphereShape.h" #include "BulletCollision/CollisionShapes/btCollisionMargin.h" #include "LinearMath/btQuaternion.h" btVector3 btSphereShape::localGetSupportingVertexWithoutMargin(const btVector3& vec)const { (void)vec; return btVector3(btScalar(0.),btScalar(0.),btScalar(0.)); } void btSphereShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const { (void)vectors; for (int i=0;i<numVectors;i++) { supportVerticesOut[i].setValue(btScalar(0.),btScalar(0.),btScalar(0.)); } } btVector3 btSphereShape::localGetSupportingVertex(const btVector3& vec)const { btVector3 supVertex; supVertex = localGetSupportingVertexWithoutMargin(vec); btVector3 vecnorm = vec; if (vecnorm .length2() < (SIMD_EPSILON*SIMD_EPSILON)) { vecnorm.setValue(btScalar(-1.),btScalar(-1.),btScalar(-1.)); } vecnorm.normalize(); supVertex+= getMargin() * vecnorm; return supVertex; } //broken due to scaling void btSphereShape::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const { const btVector3& center = t.getOrigin(); btVector3 extent(getMargin(),getMargin(),getMargin()); aabbMin = center - extent; aabbMax = center + extent; } void btSphereShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const { btScalar elem = btScalar(0.4) * mass * getMargin()*getMargin(); inertia.setValue(elem,elem,elem); }
{ "content_hash": "74fb2253099287fa84778b4535dc4e59", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 146, "avg_line_length": 24.6, "alnum_prop": 0.7594850948509485, "repo_name": "skylersaleh/ArgonEngine", "id": "b0c7d5ffd874ca67a7679b9c4f8d4f3ba0ae528b", "size": "2411", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/BulletCollision/CollisionShapes/btSphereShape.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "16543634" }, { "name": "C++", "bytes": "4852288" }, { "name": "Objective-C", "bytes": "407873" }, { "name": "Perl", "bytes": "3982" }, { "name": "Shell", "bytes": "1002" } ], "symlink_target": "" }
<?php namespace Skl\BlogBundle\Bigbrother; use Symfony\Component\EventDispatcher\Event; class MessagePostEvent extends Event { protected $message; protected $user; protected $autorise; public function __construct($message, UserInterface $user) { $this->message = $message; $this->user = $user; } // Le listener doit avoir accès au message public function getMessage() { return $this->message; } // Le listener doit pouvoir modifier le message public function setMessage($message) { return $this->message = $message; } // Le listener doit avoir accès à l'utilisateur public function getUser() { return $this->user; } }
{ "content_hash": "c7806fc25ebdc4b6d8c9282226b43586", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 62, "avg_line_length": 18.871794871794872, "alnum_prop": 0.6372282608695652, "repo_name": "nassafou/serApp", "id": "066d4c17caaa6181f6a612df3d9c30288eb4c87e", "size": "739", "binary": false, "copies": "1", "ref": "refs/heads/youssouf", "path": "src/Skl/BlogBundle/Bigbrother/MessagePostEvent.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "2647" }, { "name": "CSS", "bytes": "879830" }, { "name": "HTML", "bytes": "1946497" }, { "name": "JavaScript", "bytes": "711932" }, { "name": "PHP", "bytes": "91818" }, { "name": "PowerShell", "bytes": "936" }, { "name": "Python", "bytes": "11468" }, { "name": "Ruby", "bytes": "2370" }, { "name": "Shell", "bytes": "700" } ], "symlink_target": "" }
import flask import flask_wtf import wtforms import auth import util from main import app TESTS = [ 'pageres', 'responsive', 'grid', 'heading', 'paragraph', 'font', 'table', 'form', 'button', 'alert', 'badge', 'label', 'filter', 'pagination', 'social', ] class TestForm(flask_wtf.Form): name = wtforms.StringField( 'Text', [wtforms.validators.required()], filters=[util.strip_filter], description='This is a very important field', ) number = wtforms.IntegerField('Integer', [wtforms.validators.optional()]) email = wtforms.StringField( 'Email', [wtforms.validators.optional(), wtforms.validators.email()], filters=[util.email_filter], ) date = wtforms.DateField('Date', [wtforms.validators.optional()]) textarea = wtforms.TextAreaField('Textarea') boolean = wtforms.BooleanField( 'Render it as Markdown', [wtforms.validators.optional()], ) password = wtforms.PasswordField( 'Password', [wtforms.validators.optional(), wtforms.validators.length(min=6)], ) password_visible = wtforms.StringField( 'Password visible', [wtforms.validators.optional(), wtforms.validators.length(min=6)], description='Visible passwords for the win!' ) prefix = wtforms.StringField('Prefix', [wtforms.validators.optional()]) suffix = wtforms.StringField('Suffix', [wtforms.validators.required()]) both = wtforms.IntegerField('Both', [wtforms.validators.required()]) select = wtforms.SelectField( 'Language', [wtforms.validators.optional()], choices=[(s, s.title()) for s in ['english', 'greek', 'spanish']] ) checkboxes = wtforms.SelectMultipleField( 'User permissions', [wtforms.validators.required()], choices=[(c, c.title()) for c in ['admin', 'moderator', 'slave']] ) radios = wtforms.SelectField( 'Choose your weapon', [wtforms.validators.optional()], choices=[(r, r.title()) for r in ['gun', 'knife', 'chainsaw', 'sword']] ) public = wtforms.StringField('Public Key', [wtforms.validators.optional()]) private = wtforms.StringField('Private Key', [wtforms.validators.optional()]) recaptcha = flask_wtf.RecaptchaField() @app.route('/admin/test/<test>/', methods=['GET', 'POST']) @app.route('/admin/test/', methods=['GET', 'POST']) @auth.admin_required def admin_test(test=None): if test and test not in TESTS: flask.abort(404) form = TestForm() if form.validate_on_submit(): pass return flask.render_template( 'admin/test/test_one.html' if test else 'admin/test/test.html', title='Test: %s' % test.title() if test else 'Test', html_class='test', form=form, test=test, tests=TESTS, back_url_for='admin_test' if test else None, )
{ "content_hash": "4f8f8c0fc4d3bc86836d36621a9968eb", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 79, "avg_line_length": 28.144329896907216, "alnum_prop": 0.667032967032967, "repo_name": "dhstack/gae-init", "id": "0cfd702b5e6b6a013dcb1a74cd6fd304e2eb1d5b", "size": "2747", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "main/control/test.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15187" }, { "name": "CoffeeScript", "bytes": "16124" }, { "name": "HTML", "bytes": "67399" }, { "name": "JavaScript", "bytes": "43082" }, { "name": "Python", "bytes": "187401" } ], "symlink_target": "" }
using System; using System.Collections.Generic; namespace Universe.SqlTrace { public class TraceGroupsReport<TKey> : Dictionary<TKey, SqlGroupCounters<TKey>> { private SqlCounters _Summary; public readonly TraceColumns GroupingField; public SqlCounters Summary { get { if (_Summary == null) { SqlCounters ret = new SqlCounters(); foreach (SqlGroupCounters<TKey> value in Values) ret = ret + value.Counters; _Summary = ret; } return _Summary; } } public override string ToString() { return "Groups by " + GroupingField + ", Count: " + this.Count; } } }
{ "content_hash": "326038ea44e61054471cbffeb5d3bada", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 83, "avg_line_length": 24.441176470588236, "alnum_prop": 0.4981949458483754, "repo_name": "devizer/Universe.SqlTrace", "id": "4ca2a80704457ac7a23cc9122bdb2c9725406a61", "size": "833", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Universe.SqlTrace/TraceGroupsReport.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "7551" }, { "name": "C#", "bytes": "130446" }, { "name": "PowerShell", "bytes": "18130" }, { "name": "Shell", "bytes": "1836" }, { "name": "TSQL", "bytes": "6843" } ], "symlink_target": "" }
#include "OldAircraftRoadItem.h" OldAircraftRoadItem::OldAircraftRoadItem(uint32 id) : OldItem(ItemTypes::aircraftRoadItem, id) { } OldAircraftRoadItem::~OldAircraftRoadItem() { } bool OldAircraftRoadItem::save(DataBuffer* dataBuffer) const { DEBUG_DB(mc2dbg << " OldAircraftRoadItem::save()" << endl;) return (OldItem::save(dataBuffer)); } char* OldAircraftRoadItem::toString() { char tmpStr[1024]; strcpy(tmpStr, OldItem::toString()); sprintf(itemAsString, "***** AircraftRoadItem\n%s", tmpStr); return itemAsString; } bool OldAircraftRoadItem::createFromDataBuffer(DataBuffer *dataBuffer, OldGenericMap* theMap) { m_type = ItemTypes::aircraftRoadItem; return (OldItem::createFromDataBuffer(dataBuffer, theMap)); } void OldAircraftRoadItem::writeMifHeader(ofstream& mifFile) { OldItem::writeGenericMifHeader(1, mifFile); mifFile << "IBI_TYPE char(40)\r\n" << "DATA" << endl; } void OldAircraftRoadItem::printMidMif(ofstream& midFile, ofstream& mifFile, OldItemNames* namePointer) { OldItem::printMidMif(midFile, mifFile, namePointer); }
{ "content_hash": "df286a416e4c9de03552d167e97411bf", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 70, "avg_line_length": 20.892857142857142, "alnum_prop": 0.6888888888888889, "repo_name": "wayfinder/Wayfinder-Server", "id": "ed13fd2c8527a8a04590d72660bab34b620f600a", "size": "2698", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Server/MapGen/src/OldAircraftRoadItem.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "305133" }, { "name": "C++", "bytes": "31013369" }, { "name": "Java", "bytes": "398162" }, { "name": "Perl", "bytes": "1192824" }, { "name": "Python", "bytes": "28913" }, { "name": "R", "bytes": "712964" }, { "name": "Shell", "bytes": "388202" } ], "symlink_target": "" }
package com.hazelcast.map; /** * Determines if the object implementing this interface is locked or not. */ @FunctionalInterface public interface LockAware { /** * @return true if the object is locked, false otherwise, null if N/A */ Boolean isLocked(); }
{ "content_hash": "089e0851e331401535b6b1e594bc7745", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 73, "avg_line_length": 17.5, "alnum_prop": 0.6785714285714286, "repo_name": "mdogan/hazelcast", "id": "d1a96a8f456e77d2f5e26703fa205b3dd5b56bba", "size": "905", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "hazelcast/src/main/java/com/hazelcast/map/LockAware.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1862" }, { "name": "C", "bytes": "3721" }, { "name": "Java", "bytes": "45797218" }, { "name": "Shell", "bytes": "30002" } ], "symlink_target": "" }
dray_sort\wipe_remove recyclerview Android N编译版本 仅供学生参考不要copy
{ "content_hash": "c96bef3d0fe5488e0a2d5f24aba4fcb8", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 34, "avg_line_length": 20.666666666666668, "alnum_prop": 0.8709677419354839, "repo_name": "PerterJu/DragSwipeRecyclerView", "id": "a6df4e8f207e4abfad463b536754b58db4cfdec7", "size": "110", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "494145" } ], "symlink_target": "" }
package org.apache.pig.test; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.pig.impl.PigContext; import org.apache.pig.ExecType; import org.apache.pig.PigServer; import org.apache.pig.data.Tuple; import org.apache.pig.impl.io.FileLocalizer; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.apache.pig.impl.util.LogUtils; import org.apache.pig.impl.util.PropertiesUtil; import org.apache.pig.impl.util.Utils; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class TestPigServer { private PigServer pig = null; static MiniCluster cluster = MiniCluster.buildCluster(); private File stdOutRedirectedFile; @Before public void setUp() throws Exception{ pig = new PigServer(ExecType.MAPREDUCE, cluster.getProperties()); stdOutRedirectedFile = new File("stdout.redirected"); // Create file if it does not exist try { if(!stdOutRedirectedFile.createNewFile()) Assert.fail("Unable to create input files"); } catch (IOException e) { Assert.fail("UAssert.assertTruee to create input files:" + e.getMessage()); } } @After public void tearDown() throws Exception{ pig = null; stdOutRedirectedFile.delete(); } @AfterClass public static void oneTimeTearDown() throws Exception { cluster.shutDown(); } private final static String FILE_SEPARATOR = System.getProperty("file.separator"); // make sure that name is included or not (depending on flag "included") // in the given list of stings private static void verifyStringContained(List<URL> list, String name, boolean included) { Iterator<URL> iter = list.iterator(); boolean nameIsSubstring = false; int count = 0; while (iter.hasNext()) { if (iter.next().toString().contains(name)) { nameIsSubstring = true; ++count; } } if (included) { Assert.assertTrue(nameIsSubstring); Assert.assertTrue(count == 1); } else { Assert.assertFalse(nameIsSubstring); } } // creates an empty jar file private static void createFakeJarFile(String location, String name) throws IOException { Assert.assertFalse((new File(name)).canRead()); System.err. println("Location: " + location); new File(location).mkdirs(); Assert.assertTrue((new File(location + FILE_SEPARATOR + name)). createNewFile()); } // dynamically add more resources to the system class loader private static void registerNewResource(String file) throws Exception { URL urlToAdd = new File(file).toURI().toURL(); URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Method addMethod = URLClassLoader.class. getDeclaredMethod("addURL", new Class[]{URL.class}); addMethod.setAccessible(true); addMethod.invoke(sysLoader, new Object[]{urlToAdd}); } /** * The jar file to register is not present */ @Test public void testRegisterJarFileNotPresent() throws Throwable { // resister a jar file that does not exist String jarName = "BadFileNameTestJarNotPresent.jar"; // jar name is not present to start with verifyStringContained(pig.getPigContext().extraJars, jarName, false); boolean exceptionRaised = false; try { pig.registerJar(jarName); } catch (IOException e) { exceptionRaised = true; } Assert.assertTrue(exceptionRaised); verifyStringContained(pig.getPigContext().extraJars, jarName, false); } /** * Jar file to register is not present in the system resources * in this case name of jar file is relative to current working dir */ @Test public void testRegisterJarLocalDir() throws Throwable { String dir1 = "test1_register_jar_local"; String dir2 = "test2_register_jar_local"; String jarLocation = dir1 + FILE_SEPARATOR + dir2 + FILE_SEPARATOR; String jarName = "TestRegisterJarLocal.jar"; createFakeJarFile(jarLocation, jarName); verifyStringContained(pig.getPigContext().extraJars, jarName, false); boolean exceptionRaised = false; try { pig.registerJar(jarLocation + jarName); } catch (IOException e) { exceptionRaised = true; } Assert.assertFalse(exceptionRaised); verifyStringContained(pig.getPigContext().extraJars, jarName, true); // clean-up Assert.assertTrue((new File(jarLocation + jarName)).delete()); (new File(dir1 + FILE_SEPARATOR + dir2)).delete(); (new File(dir1)).delete(); } /** * Jar file is located via system resources * Test verifies that even with multiple resources matching, * only one of them is registered. */ @Test public void testRegisterJarFromResources () throws Throwable { String dir = "test_register_jar_res_dir"; String subDir1 = "test_register_jar_res_sub_dir1"; String subDir2 = "test_register_jar_res_sub_dir2"; String jarName = "TestRegisterJarFromRes.jar"; String jarLocation1 = dir + FILE_SEPARATOR + subDir1 + FILE_SEPARATOR; String jarLocation2 = dir + FILE_SEPARATOR + subDir2 + FILE_SEPARATOR; createFakeJarFile(jarLocation1, jarName); createFakeJarFile(jarLocation2, jarName); verifyStringContained(pig.getPigContext().extraJars, jarName, false); registerNewResource(jarLocation1); registerNewResource(jarLocation2); boolean exceptionRaised = false; try { pig.registerJar(jarName); } catch (IOException e) { exceptionRaised = true; } Assert.assertFalse(exceptionRaised); verifyStringContained(pig.getPigContext().extraJars, jarName, true); // clean-up Assert.assertTrue((new File(jarLocation1 + jarName)).delete()); Assert.assertTrue((new File(jarLocation2 + jarName)).delete()); (new File(jarLocation1)).delete(); (new File(jarLocation2)).delete(); (new File(dir)).delete(); } /** * Use a resource inside a jar file. * Verify that the containing jar file is registered correctly. * @throws Exception */ @Test public void testRegisterJarResourceInJar() throws Throwable { String dir = "test_register_jar_res_in_jar"; String subDir = "sub_dir"; String jarName = "TestRegisterJarNonEmpty.jar"; String className = "TestRegisterJar"; String javaSrc = "package " + subDir + "; class " + className + " { }"; // create dirs (new File(dir + FILE_SEPARATOR + subDir)).mkdirs(); // generate java file FileOutputStream outStream = new FileOutputStream(new File(dir + FILE_SEPARATOR + subDir + FILE_SEPARATOR + className + ".java")); OutputStreamWriter outWriter = new OutputStreamWriter(outStream); outWriter.write(javaSrc); outWriter.close(); // compile int status; status = Util.executeJavaCommand("javac " + dir + FILE_SEPARATOR + subDir + FILE_SEPARATOR + className + ".java"); Assert.assertTrue(status==0); // remove src file (new File(dir + FILE_SEPARATOR + subDir + FILE_SEPARATOR + className + ".java")).delete(); // generate jar file status = Util.executeJavaCommand("jar -cf " + dir + FILE_SEPARATOR + jarName + " " + "-C " + dir + " " + subDir); Assert.assertTrue(status==0); // remove class file and sub_dir (new File(dir + FILE_SEPARATOR + subDir + FILE_SEPARATOR + className + ".class")).delete(); (new File(dir + FILE_SEPARATOR + subDir)).delete(); // register resource registerNewResource(dir + FILE_SEPARATOR + jarName); // load the specific resource boolean exceptionRaised = false; try { pig.registerJar("sub_dir/TestRegisterJar.class"); } catch (IOException e) { exceptionRaised = true; } // verify proper jar file is located Assert.assertFalse(exceptionRaised); verifyStringContained(pig.getPigContext().extraJars, jarName, true); // clean up Jar file and test dir (new File(dir + FILE_SEPARATOR + jarName)).delete(); (new File(dir)).delete(); } @Test public void testRegisterJarGlobbingRelative() throws Throwable { String dir = "test1_register_jar_globbing_relative"; String jarLocation = dir + FILE_SEPARATOR; String jar1Name = "TestRegisterJarGlobbing1.jar"; String jar2Name = "TestRegisterJarGlobbing2.jar"; createFakeJarFile(jarLocation, jar1Name); createFakeJarFile(jarLocation, jar2Name); boolean exceptionRaised = false; try { pig.registerJar(jarLocation + "TestRegisterJarGlobbing*.jar"); } catch (IOException e) { exceptionRaised = true; } Assert.assertFalse(exceptionRaised); verifyStringContained(pig.getPigContext().extraJars, jar1Name, true); verifyStringContained(pig.getPigContext().extraJars, jar2Name, true); // clean-up Assert.assertTrue((new File(jarLocation + jar1Name)).delete()); Assert.assertTrue((new File(jarLocation + jar2Name)).delete()); (new File(dir)).delete(); } @Test public void testRegisterJarGlobbingAbsolute() throws Throwable { String dir = "test1_register_jar_globbing_absolute"; String jarLocation = dir + FILE_SEPARATOR; String jar1Name = "TestRegisterJarGlobbing1.jar"; String jar2Name = "TestRegisterJarGlobbing2.jar"; createFakeJarFile(jarLocation, jar1Name); createFakeJarFile(jarLocation, jar2Name); boolean exceptionRaised = false; String currentDir = System.getProperty("user.dir"); try { pig.registerJar(new File(currentDir, dir) + FILE_SEPARATOR + "TestRegisterJarGlobbing*.jar"); } catch (IOException e) { exceptionRaised = true; } Assert.assertFalse(exceptionRaised); verifyStringContained(pig.getPigContext().extraJars, jar1Name, true); verifyStringContained(pig.getPigContext().extraJars, jar2Name, true); // clean-up Assert.assertTrue((new File(jarLocation + jar1Name)).delete()); Assert.assertTrue((new File(jarLocation + jar2Name)).delete()); (new File(dir)).delete(); } @Test public void testDescribeLoad() throws Throwable { PrintStream console = System.out; PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(stdOutRedirectedFile))); pig.registerQuery("a = load 'a' as (field1: int, field2: float, field3: chararray );") ; System.setOut(out); pig.dumpSchema("a") ; out.close(); // Remember this! System.setOut(console); String s; InputStream fileWithStdOutContents = new DataInputStream( new BufferedInputStream( new FileInputStream(stdOutRedirectedFile))); BufferedReader reader = new BufferedReader(new InputStreamReader(fileWithStdOutContents)); while ((s = reader.readLine()) != null) { Assert.assertTrue(s.equals("a: {field1: int,field2: float,field3: chararray}") == true); } reader.close(); } @Test public void testDescribeFilter() throws Throwable { PrintStream console = System.out; PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(stdOutRedirectedFile))); pig.registerQuery("a = load 'a' as (field1: int, field2: float, field3: chararray );") ; pig.registerQuery("b = filter a by field1 > 10;") ; System.setOut(out); pig.dumpSchema("b") ; out.close(); // Remember this! System.setOut(console); String s; InputStream fileWithStdOutContents = new DataInputStream( new BufferedInputStream( new FileInputStream(stdOutRedirectedFile))); BufferedReader reader = new BufferedReader(new InputStreamReader(fileWithStdOutContents)); while ((s = reader.readLine()) != null) { Assert.assertTrue(s.equals("b: {field1: int,field2: float,field3: chararray}") == true); } fileWithStdOutContents.close(); } @Test public void testDescribeDistinct() throws Throwable { PrintStream console = System.out; PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(stdOutRedirectedFile))); pig.registerQuery("a = load 'a' as (field1: int, field2: float, field3: chararray );") ; pig.registerQuery("b = distinct a ;") ; System.setOut(out); pig.dumpSchema("b") ; out.close(); // Remember this! System.setOut(console); String s; InputStream fileWithStdOutContents = new DataInputStream( new BufferedInputStream( new FileInputStream(stdOutRedirectedFile))); BufferedReader reader = new BufferedReader(new InputStreamReader(fileWithStdOutContents)); while ((s = reader.readLine()) != null) { Assert.assertTrue(s.equals("b: {field1: int,field2: float,field3: chararray}") == true); } fileWithStdOutContents.close(); } @Test public void testDescribeSort() throws Throwable { PrintStream console = System.out; PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(stdOutRedirectedFile))); pig.registerQuery("a = load 'a' as (field1: int, field2: float, field3: chararray );") ; pig.registerQuery("b = order a by * desc;") ; System.setOut(out); pig.dumpSchema("b") ; out.close(); // Remember this! System.setOut(console); String s; InputStream fileWithStdOutContents = new DataInputStream( new BufferedInputStream( new FileInputStream(stdOutRedirectedFile))); BufferedReader reader = new BufferedReader(new InputStreamReader(fileWithStdOutContents)); while ((s = reader.readLine()) != null) { Assert.assertTrue(s.equals("b: {field1: int,field2: float,field3: chararray}") == true); } fileWithStdOutContents.close(); } @Test public void testDescribeLimit() throws Throwable { PrintStream console = System.out; PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(stdOutRedirectedFile))); pig.registerQuery("a = load 'a' as (field1: int, field2: float, field3: chararray );") ; pig.registerQuery("b = limit a 10;") ; System.setOut(out); pig.dumpSchema("b") ; out.close(); // Remember this! System.setOut(console); String s; InputStream fileWithStdOutContents = new DataInputStream( new BufferedInputStream( new FileInputStream(stdOutRedirectedFile))); BufferedReader reader = new BufferedReader(new InputStreamReader(fileWithStdOutContents)); while ((s = reader.readLine()) != null) { Assert.assertTrue(s.equals("b: {field1: int,field2: float,field3: chararray}") == true); } fileWithStdOutContents.close(); } @Test public void testDescribeForeach() throws Throwable { PrintStream console = System.out; PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(stdOutRedirectedFile))); pig.registerQuery("a = load 'a' as (field1: int, field2: float, field3: chararray );") ; pig.registerQuery("b = foreach a generate field1 + 10;") ; System.setOut(out); pig.dumpSchema("b") ; out.close(); System.setOut(console); String s; InputStream fileWithStdOutContents = new DataInputStream( new BufferedInputStream( new FileInputStream(stdOutRedirectedFile))); BufferedReader reader = new BufferedReader(new InputStreamReader(fileWithStdOutContents)); while ((s = reader.readLine()) != null) { Assert.assertTrue(s.equals("b: {int}") == true); } fileWithStdOutContents.close(); } @Test public void testDescribeForeachFail() throws Throwable { pig.registerQuery("a = load 'a' as (field1: int, field2: float, field3: chararray );") ; pig.registerQuery("b = foreach a generate field1 + 10;") ; try { pig.dumpSchema("c") ; Assert.fail("Error expected"); } catch (Exception e) { Assert.assertTrue(e.getMessage().contains("Unable to describe schema for alias c")); } } @Test public void testDescribeForeachNoSchema() throws Throwable { PrintStream console = System.out; PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(stdOutRedirectedFile))); pig.registerQuery("a = load 'a' ;") ; pig.registerQuery("b = foreach a generate *;") ; System.setOut(out); pig.dumpSchema("b") ; out.close(); System.setOut(console); String s; InputStream fileWithStdOutContents = new DataInputStream( new BufferedInputStream( new FileInputStream(stdOutRedirectedFile))); BufferedReader reader = new BufferedReader(new InputStreamReader(fileWithStdOutContents)); while ((s = reader.readLine()) != null) { Assert.assertTrue(s.equals("Schema for b unknown.")); } fileWithStdOutContents.close(); } @Test public void testDescribeCogroup() throws Throwable { PrintStream console = System.out; PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(stdOutRedirectedFile))); pig.registerQuery("a = load 'a' as (field1: int, field2: float, field3: chararray );") ; pig.registerQuery("b = load 'b' as (field4, field5: double, field6: chararray );") ; pig.registerQuery("c = cogroup a by field1, b by field4;") ; System.setOut(out); pig.dumpSchema("c") ; out.close(); System.setOut(console); String s; InputStream fileWithStdOutContents = new DataInputStream( new BufferedInputStream( new FileInputStream(stdOutRedirectedFile))); BufferedReader reader = new BufferedReader(new InputStreamReader(fileWithStdOutContents)); while ((s = reader.readLine()) != null) { Assert.assertTrue(s.equals("c: {group: int,a: {(field1: int,field2: float,field3: chararray)},b: {(field4: bytearray,field5: double,field6: chararray)}}") == true); } fileWithStdOutContents.close(); } @Test public void testDescribeCross() throws Throwable { PrintStream console = System.out; PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(stdOutRedirectedFile))); pig.registerQuery("a = load 'a' as (field1: int, field2: float, field3: chararray );") ; pig.registerQuery("b = load 'b' as (field4, field5: double, field6: chararray );") ; pig.registerQuery("c = cross a, b;") ; System.setOut(out); pig.dumpSchema("c") ; out.close(); System.setOut(console); String s; InputStream fileWithStdOutContents = new DataInputStream( new BufferedInputStream( new FileInputStream(stdOutRedirectedFile))); BufferedReader reader = new BufferedReader(new InputStreamReader(fileWithStdOutContents)); while ((s = reader.readLine()) != null) { Assert.assertTrue(s.equals("c: {a::field1: int,a::field2: float,a::field3: chararray,b::field4: bytearray,b::field5: double,b::field6: chararray}") == true); } fileWithStdOutContents.close(); } @Test public void testDescribeJoin() throws Throwable { PrintStream console = System.out; PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(stdOutRedirectedFile))); pig.registerQuery("a = load 'a' as (field1: int, field2: float, field3: chararray );") ; pig.registerQuery("b = load 'b' as (field4, field5: double, field6: chararray );") ; pig.registerQuery("c = join a by field1, b by field4;") ; System.setOut(out); pig.dumpSchema("c") ; out.close(); System.setOut(console); String s; InputStream fileWithStdOutContents = new DataInputStream( new BufferedInputStream( new FileInputStream(stdOutRedirectedFile))); BufferedReader reader = new BufferedReader(new InputStreamReader(fileWithStdOutContents)); while ((s = reader.readLine()) != null) { Assert.assertEquals("c: {a::field1: int,a::field2: float,a::field3: chararray,b::field4: bytearray,b::field5: double,b::field6: chararray}", s ); } fileWithStdOutContents.close(); } @Test public void testDescribeUnion() throws Throwable { PrintStream console = System.out; PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(stdOutRedirectedFile))); pig.registerQuery("a = load 'a' as (field1: int, field2: float, field3: chararray );") ; pig.registerQuery("b = load 'b' as (field4, field5: double, field6: chararray );") ; pig.registerQuery("c = union a, b;") ; System.setOut(out); pig.dumpSchema("c") ; out.close(); System.setOut(console); String s; InputStream fileWithStdOutContents = new DataInputStream( new BufferedInputStream( new FileInputStream(stdOutRedirectedFile))); BufferedReader reader = new BufferedReader(new InputStreamReader(fileWithStdOutContents)); while ((s = reader.readLine()) != null) { Assert.assertTrue(s.equals("c: {field1: int,field2: double,field3: chararray}") == true); } fileWithStdOutContents.close(); } @Test public void testDescribeComplex() throws Throwable { PrintStream console = System.out; PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(stdOutRedirectedFile))); pig.registerQuery("a = load 'a' as (site: chararray, count: int, itemCounts: bag { itemCountsTuple: tuple (type: chararray, typeCount: int, f: float, m: map[]) } ) ;") ; pig.registerQuery("b = foreach a generate site, count, FLATTEN(itemCounts);") ; System.setOut(out); pig.dumpSchema("b") ; out.close(); System.setOut(console); String s; InputStream fileWithStdOutContents = new DataInputStream( new BufferedInputStream( new FileInputStream(stdOutRedirectedFile))); BufferedReader reader = new BufferedReader(new InputStreamReader(fileWithStdOutContents)); while ((s = reader.readLine()) != null) { // strip away the initial schema alias and the // curlies surrounding the schema to construct // the schema object from the schema string s = s.replaceAll("^.*\\{", ""); s = s.replaceAll("\\}$", ""); Schema actual = Utils.getSchemaFromString( s); Schema expected = Utils.getSchemaFromString( "site: chararray,count: int," + "itemCounts::type: chararray,itemCounts::typeCount: int," + "itemCounts::f: float,itemCounts::m: map[ ]"); Assert.assertEquals(expected, actual); } fileWithStdOutContents.close(); } @Test public void testParamSubstitution() throws Exception{ // using params map PigServer pig=new PigServer(ExecType.LOCAL); Map<String,String> params=new HashMap<String, String>(); params.put("input", "test/org/apache/pig/test/data/passwd"); File scriptFile=Util.createFile(new String[]{"a = load '$input' using PigStorage(':');"}); pig.registerScript(scriptFile.getAbsolutePath(),params); Iterator<Tuple> iter=pig.openIterator("a"); int index=0; List<Tuple> expectedTuples=Util.readFile2TupleList("test/org/apache/pig/test/data/passwd", ":"); while(iter.hasNext()){ Tuple tuple=iter.next(); Assert.assertEquals(tuple.get(0).toString(), expectedTuples.get(index).get(0).toString()); index++; } // using param file pig=new PigServer(ExecType.LOCAL); List<String> paramFile=new ArrayList<String>(); paramFile.add(Util.createFile(new String[]{"input=test/org/apache/pig/test/data/passwd2"}).getAbsolutePath()); pig.registerScript(scriptFile.getAbsolutePath(),paramFile); iter=pig.openIterator("a"); index=0; expectedTuples=Util.readFile2TupleList("test/org/apache/pig/test/data/passwd2", ":"); while(iter.hasNext()){ Tuple tuple=iter.next(); Assert.assertEquals(tuple.get(0).toString(), expectedTuples.get(index).get(0).toString()); index++; } // using both param value and param file, param value should override param file pig=new PigServer(ExecType.LOCAL); pig.registerScript(scriptFile.getAbsolutePath(),params,paramFile); iter=pig.openIterator("a"); index=0; expectedTuples=Util.readFile2TupleList("test/org/apache/pig/test/data/passwd", ":"); while(iter.hasNext()){ Tuple tuple=iter.next(); Assert.assertEquals(tuple.get(0).toString(), expectedTuples.get(index).get(0).toString()); index++; } } // build the pig script from in-memory, and wrap it as ByteArrayInputStream @Test public void testRegisterScriptFromStream() throws Exception{ // using params map PigServer pig=new PigServer(ExecType.LOCAL); Map<String,String> params=new HashMap<String, String>(); params.put("input", "test/org/apache/pig/test/data/passwd"); String script="a = load '$input' using PigStorage(':');"; pig.registerScript(new ByteArrayInputStream(script.getBytes("UTF-8")),params); Iterator<Tuple> iter=pig.openIterator("a"); int index=0; List<Tuple> expectedTuples=Util.readFile2TupleList("test/org/apache/pig/test/data/passwd", ":"); while(iter.hasNext()){ Tuple tuple=iter.next(); Assert.assertEquals(tuple.get(0).toString(), expectedTuples.get(index).get(0).toString()); index++; } // using param file pig=new PigServer(ExecType.LOCAL); List<String> paramFile=new ArrayList<String>(); paramFile.add(Util.createFile(new String[]{"input=test/org/apache/pig/test/data/passwd2"}).getAbsolutePath()); pig.registerScript(new ByteArrayInputStream(script.getBytes("UTF-8")),paramFile); iter=pig.openIterator("a"); index=0; expectedTuples=Util.readFile2TupleList("test/org/apache/pig/test/data/passwd2", ":"); while(iter.hasNext()){ Tuple tuple=iter.next(); Assert.assertEquals(tuple.get(0).toString(), expectedTuples.get(index).get(0).toString()); index++; } // using both param value and param file, param value should override param file pig=new PigServer(ExecType.LOCAL); pig.registerScript(new ByteArrayInputStream(script.getBytes("UTF-8")),params,paramFile); iter=pig.openIterator("a"); index=0; expectedTuples=Util.readFile2TupleList("test/org/apache/pig/test/data/passwd", ":"); while(iter.hasNext()){ Tuple tuple=iter.next(); Assert.assertEquals(tuple.get(0).toString(), expectedTuples.get(index).get(0).toString()); index++; } } @Test public void testPigProperties() throws Throwable { File propertyFile = new File("pig.properties"); File cliPropertyFile = new File("commandLine_pig.properties"); Properties properties = PropertiesUtil.loadDefaultProperties(); Assert.assertTrue(properties.getProperty("pig.spill.gc.activation.size").equals("40000000")); Assert.assertTrue(properties.getProperty("test123")==null); PrintWriter out = new PrintWriter(new FileWriter(propertyFile)); out.println("test123=properties"); out.close(); properties = PropertiesUtil.loadDefaultProperties(); Assert.assertTrue(properties.getProperty("test123").equals("properties")); out = new PrintWriter(new FileWriter(cliPropertyFile)); out.println("test123=cli_properties"); out.close(); properties = PropertiesUtil.loadDefaultProperties(); PropertiesUtil.loadPropertiesFromFile(properties, "commandLine_pig.properties"); Assert.assertTrue(properties.getProperty("test123").equals("cli_properties")); propertyFile.delete(); cliPropertyFile.delete(); } @Test public void testPigTempDir() throws Throwable { File propertyFile = new File("pig.properties"); PrintWriter out = new PrintWriter(new FileWriter(propertyFile)); out.println("pig.temp.dir=/opt/temp"); out.close(); Properties properties = PropertiesUtil.loadDefaultProperties(); PigContext pigContext=new PigContext(ExecType.LOCAL, properties); pigContext.connect(); FileLocalizer.setInitialized(false); String tempPath= FileLocalizer.getTemporaryPath(pigContext).toString(); Assert.assertTrue(tempPath.startsWith("file:/opt/temp")); propertyFile.delete(); FileLocalizer.setInitialized(false); } @Test public void testDescribeForEachFlatten() throws Throwable { pig.registerQuery("a = load 'a';") ; pig.registerQuery("b = group a by $0;") ; pig.registerQuery("c = foreach b generate flatten(a);") ; Schema s = pig.dumpSchema("c") ; Assert.assertTrue(s==null); } @Test // PIG-2059 public void test1() throws Throwable { pig.setValidateEachStatement(true); pig.registerQuery("A = load 'x' as (u, v);") ; try { pig.registerQuery("B = foreach A generate $2;") ; } catch(FrontendException ex) { String msg = "Out of bound access. " + "Trying to access non-existent column: 2"; Util.checkMessageInException(ex, msg); return; } Assert.fail( "Query is supposed to fail." ); } }
{ "content_hash": "a46720e485e0a53542008f16e28acf6b", "timestamp": "", "source": "github", "line_count": 782, "max_line_length": 177, "avg_line_length": 41.16496163682864, "alnum_prop": 0.6334068528470691, "repo_name": "dmeister/pig-cll-gz", "id": "92f3a595d8d4b289c1e4b43fc499b18796c5c996", "size": "32996", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/org/apache/pig/test/TestPigServer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "12684343" }, { "name": "JavaScript", "bytes": "4954" }, { "name": "Perl", "bytes": "1313474" }, { "name": "Python", "bytes": "3312" }, { "name": "Shell", "bytes": "68160" } ], "symlink_target": "" }
package org.buildmlearn.learnfrommap.questionmodule; import java.io.Serializable; import java.util.Locale; import org.buildmlearn.learnfrommap.questionmodule.GeneratedQuestion.Type; import uk.ac.shef.wit.simmetrics.similaritymetrics.JaroWinkler; import android.annotation.SuppressLint; import android.content.Context; public class UserAnsweredData implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private String mQuestion; private String mAnswer; private String mUserAnswer; private GeneratedQuestion.Type mQuestionType; private String mAnswerType; private String[] mOptions; private boolean mIsAnswered; private boolean mIsCorrect; private int mPoints; private String mState; private String mCountry; public UserAnsweredData(Context mContext, String mQuestion, String mAnswer, String mUserAnswer, Type mQuestionType, String mAnswerType) { super(); this.mQuestion = mQuestion; this.mAnswer = mAnswer; this.mUserAnswer = mUserAnswer; this.mQuestionType = mQuestionType; this.mAnswerType = mAnswerType; if(mQuestionType == Type.Pin) { if(mUserAnswer.length() > 0) { } else { this.mPoints = 0; mIsCorrect = false; } } else { if(mUserAnswer.length() > 0) { evaluateFill(); } else { this.mPoints = 0; mIsCorrect = false; } } } public void evaluatePin(boolean isCorrect) { if(isCorrect) { this.mPoints = 10; mIsCorrect = true; } else { this.mPoints = 0; mIsCorrect = false; } } public UserAnsweredData(String mQuestion, String mAnswer, String mUserAnswer, Type mQuestionType, String mAnswerType, String[] mOptions, boolean isAnswered) { super(); this.mQuestion = mQuestion; this.mAnswer = mAnswer; this.mUserAnswer = mUserAnswer; this.mQuestionType = mQuestionType; this.mAnswerType = mAnswerType; this.mOptions = mOptions; this.mIsAnswered = isAnswered; if(this.mIsAnswered) { if(this.mAnswer.equals(this.mUserAnswer)) { this.mPoints = 10; this.mIsCorrect = true; } else { this.mPoints = 0; this.mIsCorrect = false; } } else { this.mPoints = 0; this.mIsCorrect = false; } } public String getmQuestion() { return mQuestion; } public void setmQuestion(String mQuestion) { this.mQuestion = mQuestion; } public String getmAnswer() { return mAnswer; } public void setmAnswer(String mAnswer) { this.mAnswer = mAnswer; } public String getmUserAnswer() { return mUserAnswer; } public void setmUserAnswer(String mUserAnswer) { this.mUserAnswer = mUserAnswer; } public GeneratedQuestion.Type getmQuestionType() { return mQuestionType; } public void setmQuestionType(GeneratedQuestion.Type mQuestionType) { this.mQuestionType = mQuestionType; } public String getmAnswerType() { return mAnswerType; } public void setmAnswerType(String mAnswerType) { this.mAnswerType = mAnswerType; } public String[] getmOptions() { return mOptions; } public void setmOptions(String[] mOptions) { this.mOptions = mOptions; } public boolean isAnswered() { return mIsAnswered; } public String getState() { return mState; } public void setState(String mState) { this.mState = mState; } public String getCountry() { return mCountry; } public void setCountry(String mCountry) { this.mCountry = mCountry; } private void evaluateFill() { if(this.mQuestionType == Type.Fill) { double result = CompareStrings(mUserAnswer, mAnswer); if(result > .95) { this.mIsCorrect = true; this.mPoints = 10; } else { this.mIsCorrect = false; this.mPoints = 0; } } } @SuppressLint("DefaultLocale") public static double CompareStrings(String stringA, String stringB) { stringA = stringA.toLowerCase(Locale.getDefault()); stringB = stringB.toLowerCase(Locale.getDefault()); JaroWinkler algorithm = new JaroWinkler(); return algorithm.getSimilarity(stringA, stringB); } public boolean isAnswerCorrect() { return mIsCorrect; } public int getmPoints() { return mPoints; } }
{ "content_hash": "da48b0a76ffbf9bbed44fbbb65349169", "timestamp": "", "source": "github", "line_count": 230, "max_line_length": 76, "avg_line_length": 17.97826086956522, "alnum_prop": 0.7037484885126964, "repo_name": "BuildmLearn/Mobile-applications", "id": "5efe2ab67a90228f7cb1c4202b4abcaa0186f977", "size": "4135", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Learn from Map/App/LearnFromMap/src/org/buildmlearn/learnfrommap/questionmodule/UserAnsweredData.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "59708" }, { "name": "CSS", "bytes": "24304" }, { "name": "HTML", "bytes": "8691643" }, { "name": "Java", "bytes": "1354082" }, { "name": "JavaScript", "bytes": "4495" }, { "name": "Makefile", "bytes": "1916" } ], "symlink_target": "" }
package org.mortbay.jetty.client; public class AsyncSslHttpExchangeTest extends SslHttpExchangeTest { protected void setUp() throws Exception { _scheme="https://"; startServer(); _httpClient=new HttpClient(); _httpClient.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL); _httpClient.setMaxConnectionsPerAddress(2); _httpClient.start(); } }
{ "content_hash": "b3dbf0fdd0fa06406fc77ba49614cfce", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 74, "avg_line_length": 25.4375, "alnum_prop": 0.683046683046683, "repo_name": "napcs/qedserver", "id": "e3a2e3c749c2a9896c284c0a3b855098bc208b2f", "size": "1222", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "jetty/extras/client/src/test/java/org/mortbay/jetty/client/AsyncSslHttpExchangeTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "16295" }, { "name": "CSS", "bytes": "14847" }, { "name": "Groovy", "bytes": "7099" }, { "name": "HTML", "bytes": "14346" }, { "name": "Java", "bytes": "5514807" }, { "name": "JavaScript", "bytes": "34952" }, { "name": "Ruby", "bytes": "53583" }, { "name": "Shell", "bytes": "68984" }, { "name": "XSLT", "bytes": "7153" } ], "symlink_target": "" }
title: "Developing an LADM-compliant Mobile Data Collector for Accelerating Participatory Cadastral Mapping and Registration Activities" collection: publications permalink: /publication/2019-ladm-datacollector date: 2019-10-03 venue: '8th Land Administration Domain Model Workshop' paper: 'https://repository.tudelft.nl/islandora/object/uuid:5dee1fef-1f9d-435d-a6b4-903a0a38d6ed/datastream/OBJ/download' link: 'https://repository.tudelft.nl/islandora/object/uuid:5dee1fef-1f9d-435d-a6b4-903a0a38d6ed' citation: 'Trias Aditya, I Ari Sucaya, Fajar Adi Nugroho, Han Han Lukman Syahid, Dany Laksono. 2019. &quot;Developing an LADM-compliant Mobile Data Collector for Accelerating Participatory Cadastral Mapping and Registration Activities.&quot; <i>8th Land Administration Domain Model Workshop</i>. LADM2019' ---
{ "content_hash": "072770dfadf2bc9e8549a5c0271b2b13", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 305, "avg_line_length": 81.1, "alnum_prop": 0.8212083847102343, "repo_name": "danylaksono/danylaksono.github.io", "id": "02b20411ca02bd814e4a984b788cfc92b6ede4df", "size": "816", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_publications/2019-ladm-datacollector.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5867" }, { "name": "HTML", "bytes": "62585800" }, { "name": "JavaScript", "bytes": "54181" }, { "name": "Jupyter Notebook", "bytes": "35458" }, { "name": "Python", "bytes": "13905" }, { "name": "Ruby", "bytes": "720" }, { "name": "SCSS", "bytes": "68188" } ], "symlink_target": "" }
package org.openapitools.model; import java.net.URI; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.ArrayList; import java.util.List; import org.openapitools.model.FreeStyleBuild; import org.openapitools.model.FreeStyleProjectactions; import org.openapitools.model.FreeStyleProjecthealthReport; import org.openapitools.model.NullSCM; import org.openapitools.jackson.nullable.JsonNullable; import java.time.OffsetDateTime; import javax.validation.Valid; import javax.validation.constraints.*; import io.swagger.v3.oas.annotations.media.Schema; import java.util.*; import javax.annotation.Generated; /** * FreeStyleProject */ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "2022-06-04T08:12:04.098807Z[Etc/UTC]") public class FreeStyleProject { @JsonProperty("_class") private String propertyClass; @JsonProperty("name") private String name; @JsonProperty("url") private String url; @JsonProperty("color") private String color; @JsonProperty("actions") @Valid private List<FreeStyleProjectactions> actions = null; @JsonProperty("description") private String description; @JsonProperty("displayName") private String displayName; @JsonProperty("displayNameOrNull") private String displayNameOrNull; @JsonProperty("fullDisplayName") private String fullDisplayName; @JsonProperty("fullName") private String fullName; @JsonProperty("buildable") private Boolean buildable; @JsonProperty("builds") @Valid private List<FreeStyleBuild> builds = null; @JsonProperty("firstBuild") private FreeStyleBuild firstBuild; @JsonProperty("healthReport") @Valid private List<FreeStyleProjecthealthReport> healthReport = null; @JsonProperty("inQueue") private Boolean inQueue; @JsonProperty("keepDependencies") private Boolean keepDependencies; @JsonProperty("lastBuild") private FreeStyleBuild lastBuild; @JsonProperty("lastCompletedBuild") private FreeStyleBuild lastCompletedBuild; @JsonProperty("lastFailedBuild") private String lastFailedBuild; @JsonProperty("lastStableBuild") private FreeStyleBuild lastStableBuild; @JsonProperty("lastSuccessfulBuild") private FreeStyleBuild lastSuccessfulBuild; @JsonProperty("lastUnstableBuild") private String lastUnstableBuild; @JsonProperty("lastUnsuccessfulBuild") private String lastUnsuccessfulBuild; @JsonProperty("nextBuildNumber") private Integer nextBuildNumber; @JsonProperty("queueItem") private String queueItem; @JsonProperty("concurrentBuild") private Boolean concurrentBuild; @JsonProperty("scm") private NullSCM scm; public FreeStyleProject propertyClass(String propertyClass) { this.propertyClass = propertyClass; return this; } /** * Get propertyClass * @return propertyClass */ @Schema(name = "_class", required = false) public String getPropertyClass() { return propertyClass; } public void setPropertyClass(String propertyClass) { this.propertyClass = propertyClass; } public FreeStyleProject name(String name) { this.name = name; return this; } /** * Get name * @return name */ @Schema(name = "name", required = false) public String getName() { return name; } public void setName(String name) { this.name = name; } public FreeStyleProject url(String url) { this.url = url; return this; } /** * Get url * @return url */ @Schema(name = "url", required = false) public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public FreeStyleProject color(String color) { this.color = color; return this; } /** * Get color * @return color */ @Schema(name = "color", required = false) public String getColor() { return color; } public void setColor(String color) { this.color = color; } public FreeStyleProject actions(List<FreeStyleProjectactions> actions) { this.actions = actions; return this; } public FreeStyleProject addActionsItem(FreeStyleProjectactions actionsItem) { if (this.actions == null) { this.actions = new ArrayList<>(); } this.actions.add(actionsItem); return this; } /** * Get actions * @return actions */ @Valid @Schema(name = "actions", required = false) public List<FreeStyleProjectactions> getActions() { return actions; } public void setActions(List<FreeStyleProjectactions> actions) { this.actions = actions; } public FreeStyleProject description(String description) { this.description = description; return this; } /** * Get description * @return description */ @Schema(name = "description", required = false) public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public FreeStyleProject displayName(String displayName) { this.displayName = displayName; return this; } /** * Get displayName * @return displayName */ @Schema(name = "displayName", required = false) public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public FreeStyleProject displayNameOrNull(String displayNameOrNull) { this.displayNameOrNull = displayNameOrNull; return this; } /** * Get displayNameOrNull * @return displayNameOrNull */ @Schema(name = "displayNameOrNull", required = false) public String getDisplayNameOrNull() { return displayNameOrNull; } public void setDisplayNameOrNull(String displayNameOrNull) { this.displayNameOrNull = displayNameOrNull; } public FreeStyleProject fullDisplayName(String fullDisplayName) { this.fullDisplayName = fullDisplayName; return this; } /** * Get fullDisplayName * @return fullDisplayName */ @Schema(name = "fullDisplayName", required = false) public String getFullDisplayName() { return fullDisplayName; } public void setFullDisplayName(String fullDisplayName) { this.fullDisplayName = fullDisplayName; } public FreeStyleProject fullName(String fullName) { this.fullName = fullName; return this; } /** * Get fullName * @return fullName */ @Schema(name = "fullName", required = false) public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public FreeStyleProject buildable(Boolean buildable) { this.buildable = buildable; return this; } /** * Get buildable * @return buildable */ @Schema(name = "buildable", required = false) public Boolean getBuildable() { return buildable; } public void setBuildable(Boolean buildable) { this.buildable = buildable; } public FreeStyleProject builds(List<FreeStyleBuild> builds) { this.builds = builds; return this; } public FreeStyleProject addBuildsItem(FreeStyleBuild buildsItem) { if (this.builds == null) { this.builds = new ArrayList<>(); } this.builds.add(buildsItem); return this; } /** * Get builds * @return builds */ @Valid @Schema(name = "builds", required = false) public List<FreeStyleBuild> getBuilds() { return builds; } public void setBuilds(List<FreeStyleBuild> builds) { this.builds = builds; } public FreeStyleProject firstBuild(FreeStyleBuild firstBuild) { this.firstBuild = firstBuild; return this; } /** * Get firstBuild * @return firstBuild */ @Valid @Schema(name = "firstBuild", required = false) public FreeStyleBuild getFirstBuild() { return firstBuild; } public void setFirstBuild(FreeStyleBuild firstBuild) { this.firstBuild = firstBuild; } public FreeStyleProject healthReport(List<FreeStyleProjecthealthReport> healthReport) { this.healthReport = healthReport; return this; } public FreeStyleProject addHealthReportItem(FreeStyleProjecthealthReport healthReportItem) { if (this.healthReport == null) { this.healthReport = new ArrayList<>(); } this.healthReport.add(healthReportItem); return this; } /** * Get healthReport * @return healthReport */ @Valid @Schema(name = "healthReport", required = false) public List<FreeStyleProjecthealthReport> getHealthReport() { return healthReport; } public void setHealthReport(List<FreeStyleProjecthealthReport> healthReport) { this.healthReport = healthReport; } public FreeStyleProject inQueue(Boolean inQueue) { this.inQueue = inQueue; return this; } /** * Get inQueue * @return inQueue */ @Schema(name = "inQueue", required = false) public Boolean getInQueue() { return inQueue; } public void setInQueue(Boolean inQueue) { this.inQueue = inQueue; } public FreeStyleProject keepDependencies(Boolean keepDependencies) { this.keepDependencies = keepDependencies; return this; } /** * Get keepDependencies * @return keepDependencies */ @Schema(name = "keepDependencies", required = false) public Boolean getKeepDependencies() { return keepDependencies; } public void setKeepDependencies(Boolean keepDependencies) { this.keepDependencies = keepDependencies; } public FreeStyleProject lastBuild(FreeStyleBuild lastBuild) { this.lastBuild = lastBuild; return this; } /** * Get lastBuild * @return lastBuild */ @Valid @Schema(name = "lastBuild", required = false) public FreeStyleBuild getLastBuild() { return lastBuild; } public void setLastBuild(FreeStyleBuild lastBuild) { this.lastBuild = lastBuild; } public FreeStyleProject lastCompletedBuild(FreeStyleBuild lastCompletedBuild) { this.lastCompletedBuild = lastCompletedBuild; return this; } /** * Get lastCompletedBuild * @return lastCompletedBuild */ @Valid @Schema(name = "lastCompletedBuild", required = false) public FreeStyleBuild getLastCompletedBuild() { return lastCompletedBuild; } public void setLastCompletedBuild(FreeStyleBuild lastCompletedBuild) { this.lastCompletedBuild = lastCompletedBuild; } public FreeStyleProject lastFailedBuild(String lastFailedBuild) { this.lastFailedBuild = lastFailedBuild; return this; } /** * Get lastFailedBuild * @return lastFailedBuild */ @Schema(name = "lastFailedBuild", required = false) public String getLastFailedBuild() { return lastFailedBuild; } public void setLastFailedBuild(String lastFailedBuild) { this.lastFailedBuild = lastFailedBuild; } public FreeStyleProject lastStableBuild(FreeStyleBuild lastStableBuild) { this.lastStableBuild = lastStableBuild; return this; } /** * Get lastStableBuild * @return lastStableBuild */ @Valid @Schema(name = "lastStableBuild", required = false) public FreeStyleBuild getLastStableBuild() { return lastStableBuild; } public void setLastStableBuild(FreeStyleBuild lastStableBuild) { this.lastStableBuild = lastStableBuild; } public FreeStyleProject lastSuccessfulBuild(FreeStyleBuild lastSuccessfulBuild) { this.lastSuccessfulBuild = lastSuccessfulBuild; return this; } /** * Get lastSuccessfulBuild * @return lastSuccessfulBuild */ @Valid @Schema(name = "lastSuccessfulBuild", required = false) public FreeStyleBuild getLastSuccessfulBuild() { return lastSuccessfulBuild; } public void setLastSuccessfulBuild(FreeStyleBuild lastSuccessfulBuild) { this.lastSuccessfulBuild = lastSuccessfulBuild; } public FreeStyleProject lastUnstableBuild(String lastUnstableBuild) { this.lastUnstableBuild = lastUnstableBuild; return this; } /** * Get lastUnstableBuild * @return lastUnstableBuild */ @Schema(name = "lastUnstableBuild", required = false) public String getLastUnstableBuild() { return lastUnstableBuild; } public void setLastUnstableBuild(String lastUnstableBuild) { this.lastUnstableBuild = lastUnstableBuild; } public FreeStyleProject lastUnsuccessfulBuild(String lastUnsuccessfulBuild) { this.lastUnsuccessfulBuild = lastUnsuccessfulBuild; return this; } /** * Get lastUnsuccessfulBuild * @return lastUnsuccessfulBuild */ @Schema(name = "lastUnsuccessfulBuild", required = false) public String getLastUnsuccessfulBuild() { return lastUnsuccessfulBuild; } public void setLastUnsuccessfulBuild(String lastUnsuccessfulBuild) { this.lastUnsuccessfulBuild = lastUnsuccessfulBuild; } public FreeStyleProject nextBuildNumber(Integer nextBuildNumber) { this.nextBuildNumber = nextBuildNumber; return this; } /** * Get nextBuildNumber * @return nextBuildNumber */ @Schema(name = "nextBuildNumber", required = false) public Integer getNextBuildNumber() { return nextBuildNumber; } public void setNextBuildNumber(Integer nextBuildNumber) { this.nextBuildNumber = nextBuildNumber; } public FreeStyleProject queueItem(String queueItem) { this.queueItem = queueItem; return this; } /** * Get queueItem * @return queueItem */ @Schema(name = "queueItem", required = false) public String getQueueItem() { return queueItem; } public void setQueueItem(String queueItem) { this.queueItem = queueItem; } public FreeStyleProject concurrentBuild(Boolean concurrentBuild) { this.concurrentBuild = concurrentBuild; return this; } /** * Get concurrentBuild * @return concurrentBuild */ @Schema(name = "concurrentBuild", required = false) public Boolean getConcurrentBuild() { return concurrentBuild; } public void setConcurrentBuild(Boolean concurrentBuild) { this.concurrentBuild = concurrentBuild; } public FreeStyleProject scm(NullSCM scm) { this.scm = scm; return this; } /** * Get scm * @return scm */ @Valid @Schema(name = "scm", required = false) public NullSCM getScm() { return scm; } public void setScm(NullSCM scm) { this.scm = scm; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FreeStyleProject freeStyleProject = (FreeStyleProject) o; return Objects.equals(this.propertyClass, freeStyleProject.propertyClass) && Objects.equals(this.name, freeStyleProject.name) && Objects.equals(this.url, freeStyleProject.url) && Objects.equals(this.color, freeStyleProject.color) && Objects.equals(this.actions, freeStyleProject.actions) && Objects.equals(this.description, freeStyleProject.description) && Objects.equals(this.displayName, freeStyleProject.displayName) && Objects.equals(this.displayNameOrNull, freeStyleProject.displayNameOrNull) && Objects.equals(this.fullDisplayName, freeStyleProject.fullDisplayName) && Objects.equals(this.fullName, freeStyleProject.fullName) && Objects.equals(this.buildable, freeStyleProject.buildable) && Objects.equals(this.builds, freeStyleProject.builds) && Objects.equals(this.firstBuild, freeStyleProject.firstBuild) && Objects.equals(this.healthReport, freeStyleProject.healthReport) && Objects.equals(this.inQueue, freeStyleProject.inQueue) && Objects.equals(this.keepDependencies, freeStyleProject.keepDependencies) && Objects.equals(this.lastBuild, freeStyleProject.lastBuild) && Objects.equals(this.lastCompletedBuild, freeStyleProject.lastCompletedBuild) && Objects.equals(this.lastFailedBuild, freeStyleProject.lastFailedBuild) && Objects.equals(this.lastStableBuild, freeStyleProject.lastStableBuild) && Objects.equals(this.lastSuccessfulBuild, freeStyleProject.lastSuccessfulBuild) && Objects.equals(this.lastUnstableBuild, freeStyleProject.lastUnstableBuild) && Objects.equals(this.lastUnsuccessfulBuild, freeStyleProject.lastUnsuccessfulBuild) && Objects.equals(this.nextBuildNumber, freeStyleProject.nextBuildNumber) && Objects.equals(this.queueItem, freeStyleProject.queueItem) && Objects.equals(this.concurrentBuild, freeStyleProject.concurrentBuild) && Objects.equals(this.scm, freeStyleProject.scm); } @Override public int hashCode() { return Objects.hash(propertyClass, name, url, color, actions, description, displayName, displayNameOrNull, fullDisplayName, fullName, buildable, builds, firstBuild, healthReport, inQueue, keepDependencies, lastBuild, lastCompletedBuild, lastFailedBuild, lastStableBuild, lastSuccessfulBuild, lastUnstableBuild, lastUnsuccessfulBuild, nextBuildNumber, queueItem, concurrentBuild, scm); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class FreeStyleProject {\n"); sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" url: ").append(toIndentedString(url)).append("\n"); sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" actions: ").append(toIndentedString(actions)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" displayName: ").append(toIndentedString(displayName)).append("\n"); sb.append(" displayNameOrNull: ").append(toIndentedString(displayNameOrNull)).append("\n"); sb.append(" fullDisplayName: ").append(toIndentedString(fullDisplayName)).append("\n"); sb.append(" fullName: ").append(toIndentedString(fullName)).append("\n"); sb.append(" buildable: ").append(toIndentedString(buildable)).append("\n"); sb.append(" builds: ").append(toIndentedString(builds)).append("\n"); sb.append(" firstBuild: ").append(toIndentedString(firstBuild)).append("\n"); sb.append(" healthReport: ").append(toIndentedString(healthReport)).append("\n"); sb.append(" inQueue: ").append(toIndentedString(inQueue)).append("\n"); sb.append(" keepDependencies: ").append(toIndentedString(keepDependencies)).append("\n"); sb.append(" lastBuild: ").append(toIndentedString(lastBuild)).append("\n"); sb.append(" lastCompletedBuild: ").append(toIndentedString(lastCompletedBuild)).append("\n"); sb.append(" lastFailedBuild: ").append(toIndentedString(lastFailedBuild)).append("\n"); sb.append(" lastStableBuild: ").append(toIndentedString(lastStableBuild)).append("\n"); sb.append(" lastSuccessfulBuild: ").append(toIndentedString(lastSuccessfulBuild)).append("\n"); sb.append(" lastUnstableBuild: ").append(toIndentedString(lastUnstableBuild)).append("\n"); sb.append(" lastUnsuccessfulBuild: ").append(toIndentedString(lastUnsuccessfulBuild)).append("\n"); sb.append(" nextBuildNumber: ").append(toIndentedString(nextBuildNumber)).append("\n"); sb.append(" queueItem: ").append(toIndentedString(queueItem)).append("\n"); sb.append(" concurrentBuild: ").append(toIndentedString(concurrentBuild)).append("\n"); sb.append(" scm: ").append(toIndentedString(scm)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
{ "content_hash": "ef123ed97fdd621b1b9a54be85c01e8d", "timestamp": "", "source": "github", "line_count": 740, "max_line_length": 388, "avg_line_length": 26.82027027027027, "alnum_prop": 0.7083186375774676, "repo_name": "cliffano/swaggy-jenkins", "id": "c9dacb1a953f3fef4bb186ad2d87ad9bfb4b9557", "size": "19847", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "clients/spring/generated/src/main/java/org/openapitools/model/FreeStyleProject.java", "mode": "33188", "license": "mit", "language": [ { "name": "Ada", "bytes": "569823" }, { "name": "Apex", "bytes": "741346" }, { "name": "Batchfile", "bytes": "14792" }, { "name": "C", "bytes": "971274" }, { "name": "C#", "bytes": "5131336" }, { "name": "C++", "bytes": "7799032" }, { "name": "CMake", "bytes": "20609" }, { "name": "CSS", "bytes": "4873" }, { "name": "Clojure", "bytes": "129018" }, { "name": "Crystal", "bytes": "864941" }, { "name": "Dart", "bytes": "876777" }, { "name": "Dockerfile", "bytes": "7385" }, { "name": "Eiffel", "bytes": "424642" }, { "name": "Elixir", "bytes": "139252" }, { "name": "Elm", "bytes": "187067" }, { "name": "Emacs Lisp", "bytes": "191" }, { "name": "Erlang", "bytes": "373074" }, { "name": "F#", "bytes": "556012" }, { "name": "Gherkin", "bytes": "951" }, { "name": "Go", "bytes": "345227" }, { "name": "Groovy", "bytes": "89524" }, { "name": "HTML", "bytes": "2367424" }, { "name": "Haskell", "bytes": "680841" }, { "name": "Java", "bytes": "12164874" }, { "name": "JavaScript", "bytes": "1959006" }, { "name": "Kotlin", "bytes": "1280953" }, { "name": "Lua", "bytes": "322316" }, { "name": "Makefile", "bytes": "11882" }, { "name": "Nim", "bytes": "65818" }, { "name": "OCaml", "bytes": "94665" }, { "name": "Objective-C", "bytes": "464903" }, { "name": "PHP", "bytes": "4383673" }, { "name": "Perl", "bytes": "743304" }, { "name": "PowerShell", "bytes": "678274" }, { "name": "Python", "bytes": "5529523" }, { "name": "QMake", "bytes": "6915" }, { "name": "R", "bytes": "840841" }, { "name": "Raku", "bytes": "10945" }, { "name": "Ruby", "bytes": "328360" }, { "name": "Rust", "bytes": "1735375" }, { "name": "Scala", "bytes": "1387368" }, { "name": "Shell", "bytes": "407167" }, { "name": "Swift", "bytes": "342562" }, { "name": "TypeScript", "bytes": "3060093" } ], "symlink_target": "" }
package org.innovateuk.ifs.project.correspondenceaddress.viewmodel; import org.innovateuk.ifs.project.projectdetails.viewmodel.BasicProjectDetailsViewModel; import org.innovateuk.ifs.project.resource.ProjectResource; /** * The view model that backs the project address */ public class ProjectDetailsAddressViewModel implements BasicProjectDetailsViewModel { private Long applicationId; private Long projectId; private String projectName; private boolean collaborativeProject; private boolean ktpCompetition; public ProjectDetailsAddressViewModel(ProjectResource projectResource, boolean ktpCompetition) { this.projectId = projectResource.getId(); this.projectName = projectResource.getName(); this.applicationId = projectResource.getApplication(); this.collaborativeProject = projectResource.isCollaborativeProject(); this.ktpCompetition = ktpCompetition; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public Long getProjectId() { return projectId; } public Long getApplicationId() { return applicationId; } public boolean isCollaborativeProject() { return collaborativeProject; } public boolean isKtpCompetition() { return ktpCompetition; } }
{ "content_hash": "8b1ec21a95d62e762c0bf3deb738c6b7", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 100, "avg_line_length": 30.06382978723404, "alnum_prop": 0.7338995046001415, "repo_name": "InnovateUKGitHub/innovation-funding-service", "id": "45d45eeac9f8da4b85b30b825227c2533a7018f8", "size": "1413", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "ifs-web-service/ifs-project-setup-service/src/main/java/org/innovateuk/ifs/project/correspondenceaddress/viewmodel/ProjectDetailsAddressViewModel.java", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "1972" }, { "name": "HTML", "bytes": "6342985" }, { "name": "Java", "bytes": "26591674" }, { "name": "JavaScript", "bytes": "269444" }, { "name": "Python", "bytes": "58983" }, { "name": "RobotFramework", "bytes": "3317394" }, { "name": "SCSS", "bytes": "100274" }, { "name": "Shell", "bytes": "60248" } ], "symlink_target": "" }
<!-- TODO: Write a brief abstract explaining this sample --> This sample demonstrates how to add operations onto the undo/redo stack. <a href="https://pro.arcgis.com/en/pro-app/sdk/" target="_blank">View it live</a> <!-- TODO: Fill this section below with metadata about this sample--> ``` Language: C# Subject: Framework Contributor: ArcGIS Pro SDK Team <arcgisprosdk@esri.com> Organization: Esri, https://www.esri.com Date: 06/10/2022 ArcGIS Pro: 3.0 Visual Studio: 2022 .NET Target Framework: net6.0-windows ``` ## Resources [Community Sample Resources](https://github.com/Esri/arcgis-pro-sdk-community-samples#resources) ### Samples Data * Sample data for ArcGIS Pro SDK Community Samples can be downloaded from the [Releases](https://github.com/Esri/arcgis-pro-sdk-community-samples/releases) page. ## How to use the sample <!-- TODO: Explain how this sample can be used. To use images in this section, create the image file in your sample project's screenshots folder. Use relative url to link to this image using this syntax: ![My sample Image](FacePage/SampleImage.png) --> ArcGIS Pro does not contain a single undo/redo operation stack for the application; it has multiple undo/redo stacks. Each pane and dockpane decides how it's own operations are managed. In many cases, each pane and dockpane has it's own OperationManager; however in some cases they may elect to share a single OperationManager. For example, operations added to map A are not visible to map B (becuase they have different OperationManagers), but two panes showing the same map will show the same operations as they share the same OperationManager. When a window becomes active, its OperationManager is requested and connected to the undo/redo user interface. This sample contains a dockpane which has its own OperationManager. The two buttons at the top of the dockpane illustrate how to create an undo/redo operation and add it to the OperationManager. The third button at the top of the dockpane illustrates a compositeOperation which allows many operations to be grouped into a single composite operation. The 4 buttons at the bottom of the dockpane manipulate the undo/redo stack - performing undo and redo actions; remove undo actions and clearing the stacks. 1. Open this solution in Visual Studio. 2. Click the Build menu. Then select Build Solution. 3. Click Start button to open ArcGIS Pro. ArcGIS Pro will open. 4. Open a project containing data. 5. Click on the Add-in tab and see that 2 buttons are added to a Undo_Redo group. 6. Click the "Show Sample DockPane" button in the Undo_Redo group. The Sample dockpane will be displayed 7. Ensure that a map is open. 8. Use the Fixed Zoom In and Fixed Zoom Out buttons to see zoom in and zoom out operations added to the undo stack for the sample dockpane. 9. Use the Undo and Redo buttons to undo and redo the operations. Use the Remove Operation button to pop an operation (without undoing it). Use the Clear All Operations button to clear all the operations of a particular category from the stack. ![UI](Screenshots/Screen.png) <!-- End --> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="https://esri.github.io/arcgis-pro-sdk/images/ArcGISPro.png" alt="ArcGIS Pro SDK for Microsoft .NET Framework" height = "20" width = "20" align="top" > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [Home](https://github.com/Esri/arcgis-pro-sdk/wiki) | <a href="https://pro.arcgis.com/en/pro-app/latest/sdk/api-reference" target="_blank">API Reference</a> | [Requirements](https://github.com/Esri/arcgis-pro-sdk/wiki#requirements) | [Download](https://github.com/Esri/arcgis-pro-sdk/wiki#installing-arcgis-pro-sdk-for-net) | <a href="https://github.com/esri/arcgis-pro-sdk-community-samples" target="_blank">Samples</a>
{ "content_hash": "d49980888162f2624c644c19ce968584", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 516, "avg_line_length": 67.08474576271186, "alnum_prop": 0.7357251136937848, "repo_name": "Esri/arcgis-pro-sdk-community-samples", "id": "54a470089739049c3d20f878c736b20250ef810a", "size": "3971", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Framework/UndoRedo/UndoRedo (C#).md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "6521661" }, { "name": "CSS", "bytes": "4426" }, { "name": "HTML", "bytes": "9928" }, { "name": "Python", "bytes": "3248" }, { "name": "Visual Basic .NET", "bytes": "31990" }, { "name": "XSLT", "bytes": "11612" } ], "symlink_target": "" }
@interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
{ "content_hash": "1d9bedd779c51f6ddba15686feb14b14", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 76, "avg_line_length": 20.058823529411764, "alnum_prop": 0.6979472140762464, "repo_name": "nicholasxjy/ios-learn", "id": "c3df11ff6918e338fcc50d42afda8d54e085d41a", "size": "513", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "FacebookPopDemo/FacebookPopDemo/ViewController.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "78273" }, { "name": "C++", "bytes": "104978" }, { "name": "Matlab", "bytes": "64" }, { "name": "Objective-C", "bytes": "518100" }, { "name": "Objective-C++", "bytes": "188596" }, { "name": "Ruby", "bytes": "208" }, { "name": "Shell", "bytes": "7104" }, { "name": "Swift", "bytes": "10119" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "e5db2643c881a0dcb22623b99d62f6a0", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "94110caf83c58a86192ab945e00bf5a7fe4cf384", "size": "192", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Gesneriaceae/Cyrtandromoea/Cyrtandromoea subsessilis/ Syn. Cyrtandromoea acuminata/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System; using System.Text; namespace Outlander.Core.Client.Tests { public class InMemoryScriptLog : IScriptLog { public StringBuilder Builder = new StringBuilder(); public event EventHandler<ScriptLogInfo> Info = delegate { }; public event EventHandler<ScriptLogInfo> NotifyStarted = delegate { }; public event EventHandler<ScriptLogInfo> NotifyAborted = delegate { }; public void Started(string name, DateTime startTime) { Builder.AppendLine("{0} started".ToFormat(name)); } public void Log(string name, string data, int lineNumber) { Builder.AppendLine(data); } public void Aborted(string name, DateTime startTime, TimeSpan runtime) { Builder.AppendLine("{0} finished".ToFormat(name)); } } }
{ "content_hash": "0cd26b7cd6f9726277572b3fb4baf107", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 72, "avg_line_length": 25.620689655172413, "alnum_prop": 0.7348586810228802, "repo_name": "joemcbride/outlander", "id": "d537ab9e2a8b6f67fe300a91b67c011bacb185a3", "size": "743", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Pathfinder.Core.Client.Tests/Scripting/InMemoryScriptLog.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "399564" }, { "name": "Shell", "bytes": "2581" } ], "symlink_target": "" }
[![Build Status](https://travis-ci.org/cogumbreiro/habanero-coq.svg?branch=master)](https://travis-ci.org/cogumbreiro/habanero-coq) [![pipeline status](https://gitlab.com/cogumbreiro/habanero-coq/badges/master/pipeline.svg)](https://gitlab.com/cogumbreiro/habanero-coq/commits/master) # Coq Formalization of the Habanero programming model Formalization of the [Habanero programming model](https://wiki.rice.edu/confluence/display/HABANERO/Habanero-Java) programming model. We focus primarily on the formalization of [safety](https://en.wikipedia.org/wiki/Type_safety) properties, such as deadlock freedom and race freedom. The overarching goal of the project is to provide theoretical framework, read a Coq library, for the verification of synchronization mechanisms. # Publications * Formalization of Habanero Phasers using Coq. Tiago Cogumbreiro, Jun Shirako, and Vivek Sarkar. JLAMP, 90:50–60, 2017. [**[Download PDF]**](http://cogumbreiro.github.io/assets/cogumbreiro-formalizing-phasers.pdf) [**[Online interpreter]**](https://cogumbreiro.github.io/jlamp17/) * Formalization of phase ordering. Tiago Cogumbreiro, Jun Shirako, and Vivek Sarkar. In Proceedings of PLACES'16, 2016. [**[Download PDF]**](https://github.com/cogumbreiro/habanero-coq/blob/places16/README.md) # Overview We are currently working on: * deadlock-free subset of phaser operations * async-finish # Using Make sure you have [OPAM] installed. To setup the requirements of this software do: ``` ./configure.sh # to install dependencies and setup the environment ``` # Dependencies * [OPAM] for the development. * [Aniceto](https://bitbucket.org/cogumbreiro/aniceto-coq) (installed automatically) [OPAM]: https://opam.ocaml.org/
{ "content_hash": "fc7b5df79c07ed78f709c890e92d6ee7", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 280, "avg_line_length": 42.9, "alnum_prop": 0.7762237762237763, "repo_name": "cogumbreiro/habanero-coq", "id": "8e95c1fc809c115413883f04a78f9d9767d3a530", "size": "1718", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "1684" }, { "name": "Coq", "bytes": "464127" }, { "name": "JavaScript", "bytes": "2388" }, { "name": "Makefile", "bytes": "2197" }, { "name": "OCaml", "bytes": "22783" }, { "name": "Shell", "bytes": "957" }, { "name": "Standard ML", "bytes": "144" } ], "symlink_target": "" }
echo "You can build an eclipse project via a workspace from the command line" #: echo "eclipsc.exe -noSplash -data "D:\Source\MyProject\workspace" -application org.eclipse.jdt.apt.core.aptBuild It uses the jdt apt plugin to build your workspace automatically. This is also known as a 'Headless Build'. Damn hard to figure out. If you're not using a win32 exe, try this: " java -cp startup.jar -noSplash -data "D:\Source\MyProject\workspace" -application org.eclipse.jdt.apt.core.aptBuild echo "or:" java -jar org.eclipse.jdt.core_3.4.0<qualifier>.jar -classpath rt.jar A.java echo "or" java -jar ecj.jar -classpath rt.jar A.java
{ "content_hash": "dafdbe5379983763eff874783801c38c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 175, "avg_line_length": 48.61538461538461, "alnum_prop": 0.7610759493670886, "repo_name": "bayvictor/distributed-polling-system", "id": "8a365981979a5561fd1b57a4691afaf2b17ab0bf", "size": "632", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bin/cmd_line_eclipse_build.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3145" }, { "name": "Emacs Lisp", "bytes": "112935" }, { "name": "HTML", "bytes": "27759" }, { "name": "PHP", "bytes": "18" }, { "name": "Python", "bytes": "2037487" }, { "name": "Roff", "bytes": "83316" }, { "name": "Ruby", "bytes": "1988" }, { "name": "Shell", "bytes": "2175654" }, { "name": "Vim script", "bytes": "125" } ], "symlink_target": "" }
package br.ufsc.ftsm; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import com.google.common.collect.Multimap; import com.google.common.collect.MultimapBuilder; import com.google.common.collect.Ordering; import br.ufsc.core.trajectory.SemanticTrajectory; import br.ufsc.core.trajectory.Trajectory; import br.ufsc.db.source.DataRetriever; import br.ufsc.db.source.DataSource; import br.ufsc.db.source.DataSourceType; import br.ufsc.ftsm.base.TrajectorySimilarityCalculator; import br.ufsc.ftsm.related.UMS; import br.ufsc.lehmann.msm.artigo.problems.BasicSemantic; import br.ufsc.lehmann.msm.artigo.problems.SanFranciscoCabDatabaseReader; public class TopK { // private static DataSource source; // private static DataRetriever retriever; public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { // source = new DataSource("postgres", "postgis", "localhost", 5432, "postgis", DataSourceType.PGSQL, "crawdad", // null, "geom"); // retriever = source.getRetriever(); // testMethod("DTW",new DTWDistanceCalculator(), createTaxicabGroundtruth1TSToAirportDeparture(),T); // testMethod("DTW",new DTWDistanceCalculator(), createTaxicabGroundtruth2TSToUS(),T); // testMethod("DTW",new DTWDistanceCalculator(), createTaxicabGroundtruth3USToAirport(),T); // testMethod("DTW",new DTWDistanceCalculator(), createTaxicabGroundtruth4TSToAirportArrival(),T); // testMethod("DTW",new DTWDistanceCalculator(), createTaxicabGroundtruth5AirportArrivalToUS(),T); // testMethod("DTW",new DTWDistanceCalculator(), createTaxicabGroundtruth6TSToP39(),T); // testMethod("DTW",new DTWDistanceCalculator(), createTaxicabGroundtruth7USToP39(),T); // testMethod("UMSOnlyAlikeness3Pt",new UMSOnlyAlikeness3Pt(), createTaxicabGroundtruth1TSToAirportDeparture(),T); // testMethod("UMSOnlyAlikeness3Pt",new UMSOnlyAlikeness3Pt(), createTaxicabGroundtruth2TSToUS(),T); // testMethod("UMSOnlyAlikeness3Pt",new UMSOnlyAlikeness3Pt(), createTaxicabGroundtruth3USToAirport(),T); // testMethod("UMSOnlyAlikeness3Pt",new UMSOnlyAlikeness3Pt(), createTaxicabGroundtruth4TSToAirportArrival(),T); // testMethod("UMSOnlyAlikeness3Pt",new UMSOnlyAlikeness3Pt(), createTaxicabGroundtruth5AirportArrivalToUS(),T); // testMethod("UMSOnlyAlikeness3Pt",new UMSOnlyAlikeness3Pt(), createTaxicabGroundtruth6TSToP39(),T); // testMethod("UMSOnlyAlikeness3Pt",new UMSOnlyAlikeness3Pt(), createTaxicabGroundtruth7USToP39(),T); // testMethod("DTW",new DTWDistanceCalculator(), createTaxicabGroundtruth8P39ToTS(),T); // testMethod("UMSOA3",new UMSOnlyAlikeness3Pt(), createTaxicabGroundtruth8P39ToTS(),T); // testMethod("UMSNSF",new UMSNewSharenessFixed(), createTaxicabGroundtruth8P39ToTS(),T); // // retriever.prepareFetchTrajectoryStatement(); // testMethod("DTW",new DTWDistanceCalculator(), createGeolife1to6(),T); // testMethod("SDTW",new SDTW(), createGeolife1to6(),T); // testMethod("UMS",new UMSMathSimple(), createTaxicabGroundtruth6TSToP39(),T); // testMethod("UMS",new UMS(), GT.CD1.getTrajectories(),T); // testMethod("UMS",new UMSSpeed(), GT.CD1.getTrajectories(),T); String stopsTable = "stops_moves.sanfrancisco_taxicab_airport_mall_pier_park_fisherman_stop"; String movesTable = "stops_moves.sanfrancisco_taxicab_airport_mall_pier_park_fisherman_move"; String pointsTable = "taxi.sanfrancisco_taxicab_airport_mall_pier_park_fisherman_cleaned"; List<SemanticTrajectory> T = new SanFranciscoCabDatabaseReader(false, null, null, null, stopsTable, movesTable, pointsTable).read(); Multimap<String, SemanticTrajectory> Gs = MultimapBuilder.hashKeys().arrayListValues().build(); BasicSemantic<String> groundtruth = new BasicSemantic<>(SanFranciscoCabDatabaseReader.ROADS_WITH_DIRECTION.getIndex()); T.stream().forEach(t -> { Gs.put(groundtruth.getData(t, 0), t); }); Gs.asMap().entrySet().stream().forEach(e -> { if(e.getKey() != null) { System.out.println(e.getKey()); testMethod("UMS", new UMS(), new ArrayList<SemanticTrajectory>(e.getValue()), T); } }); // testMethod("UMS Speed",new UMSSpeed(),GT.CD5.getTrajectories(),T); // testMethod("UMS",new UMS(), GT.CD6.getTrajectories(),T); // testMethod("UMS Speed",new UMSSpeed(),GT.CD6.getTrajectories(),T); // // testMethod("UMS",new UMS(), GT.CD7.getTrajectories(),T); // testMethod("UMS Speed",new UMSSpeed(), GT.CD7.getTrajectories(),T); // // testMethod("UMS",new UMS(), GT.CD2.getTrajectories(),T); // testMethod("UMS Speed",new UMSSpeed(),GT.CD2.getTrajectories(),T); // // testMethod("UMS",new UMS(), GT.CD3.getTrajectories(),T); // testMethod("UMS Speed",new UMSSpeed(),GT.CD3.getTrajectories(),T); // // testMethod("UMS",new UMS(), GT.CD4.getTrajectories(),T); // testMethod("UMS Speed",new UMSSpeed(), GT.CD4.getTrajectories(),T); // // // testMethod("UMS",new UMSSamsung(), GT.CD1.getTrajectories(),T); // testMethod("EDwP",new EditDistance(), GT.CD1.getTrajectories(),T); } private static void testMethod(String name, TrajectorySimilarityCalculator<SemanticTrajectory> tdc, List<SemanticTrajectory> G, List<SemanticTrajectory> T) { List<List<Double>> precisionAll = new ArrayList<List<Double>>(); System.out.println("############### Method: " + name + " GT: " + G.size()); long start = System.currentTimeMillis(); int k = 0; for (SemanticTrajectory t1 : G) { // CircleTrajectory e = CreateCircle.createEllipticalTrajectory(t1); // ETrajectory e = CreateEllipseJTS.createEllipticalTrajectory(t1); List<Score> scoreList = new ArrayList<Score>(); System.out.print(k + " "); k++; for (SemanticTrajectory t2 : T) { // Trajectory t2 = retriever.fastFetchTrajectory(tid2); // ETrajectory e2 = // CreateEllipseJTS.createPreparedEllipticalTrajectory(t2); double similarity = // ((UMSMSimilarityContinuityV2)tdc).getDistance(e,t2); tdc.getSimilarity(t1, t2);// *-1; Score score = new Score(similarity, t2); scoreList.add(score); // System.out.println(similarity); } precisionAll.add(calculatePrecision(scoreList, G.stream().map(s -> ((Number) s.getTrajectoryId()).intValue()).collect(Collectors.toList()))); } List<Double> avgPrecision = new ArrayList<Double>(); double sizePrecisionList = precisionAll.get(0).size(); for (int i = 0; i < sizePrecisionList; i++) { double precision = 0.0; for (List<Double> precisionList : precisionAll) { precision += precisionList.get(i); } avgPrecision.add(precision / sizePrecisionList); } for (Double d : avgPrecision) { System.out.println(d); } long end = System.currentTimeMillis(); System.out.println("Elapsed time (ms): " + (end - start)); } private static List<Double> calculatePrecision(List<Score> scoreList, List<Integer> groundtruth) { scoreList = Ordering.natural().greatestOf(scoreList, scoreList.size()); int groundtruthSize = groundtruth.size(); ArrayList<Double> result = new ArrayList<Double>(); double i = 0; double j = 0; while (j < groundtruthSize && i < scoreList.size()) { if (groundtruth.contains(scoreList.get((int) i).getTrajectory().getTrajectoryId())) { j++; result.add(j / (i + 1)); } i++; } return result; } }
{ "content_hash": "8522e68d62587b2b53059efe6defb098", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 144, "avg_line_length": 45.59756097560975, "alnum_prop": 0.717838994383525, "repo_name": "lehmann/ArtigoMSM_UFSC", "id": "c9c7d2884d0928f4a7e88a8011c107233afb771b", "size": "7478", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "artigo/src/main/java/br/ufsc/ftsm/TopK.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1955895" }, { "name": "Jupyter Notebook", "bytes": "46474" } ], "symlink_target": "" }
@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^<target^>` where ^<target^> is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled echo. coverage to run coverage check of the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) REM Check if sphinx-build is available and fallback to Python version if any %SPHINXBUILD% 2> nul if errorlevel 9009 goto sphinx_python goto sphinx_ok :sphinx_python set SPHINXBUILD=python -m sphinx.__init__ %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) :sphinx_ok if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\django-djconfig.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django-djconfig.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "coverage" ( %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage if errorlevel 1 exit /b 1 echo. echo.Testing of coverage in the sources finished, look at the ^ results in %BUILDDIR%/coverage/python.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end
{ "content_hash": "f7331fe6c9945227a88835141deedef2", "timestamp": "", "source": "github", "line_count": 263, "max_line_length": 79, "avg_line_length": 26.61216730038023, "alnum_prop": 0.7046720960137163, "repo_name": "nitely/django-djconfig", "id": "cd55bf4fd4f93f46bf9b7378922ae62fc18d77a8", "size": "6999", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/make.bat", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1157" }, { "name": "Makefile", "bytes": "253" }, { "name": "Python", "bytes": "46294" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "8011ba74d09e6b448b89c7b9a27054c1", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "6270afab3da41494263b540696acc84be1ba1cc1", "size": "196", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Bromeliaceae/Guzmania/Guzmania vinacea/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
class GithubDailyUpdate::Report attr_accessor :reporters def initialize(options = {}) client = ::Octokit::Client.new @reporters = [ GithubDailyUpdate::Reporter::Merged.new(client, options), GithubDailyUpdate::Reporter::OpenPulls.new(client, options) ] end def generate @reporters.map { |r| r.generate } end end
{ "content_hash": "ce3e02a9c49a42b1f9e17935bb4fab73", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 65, "avg_line_length": 23.4, "alnum_prop": 0.6809116809116809, "repo_name": "jhubert/github-daily-update", "id": "3beb548769b815d778d5d3fb4625a6237ff9a8a9", "size": "386", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/github_daily_update/report.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "6338" } ], "symlink_target": "" }
const Flint = require('../../../') const mocks = require('../../mocks') const populateDB = require('../../populatedb') const supertest = require('supertest') const mongoose = require('mongoose') exports.before = async function before (plugins = []) { const flintServer = new Flint({ listen: false, plugins }) const server = await flintServer.startServer() const agent = supertest.agent(server) await populateDB() return agent } exports.setNonAdmin = async function setNonAdmin (agent) { const res = await agent .post('/graphql') .send({ query: `mutation ($_id: ID!, $data: UserInput!) { updateUser (_id: $_id, data: $data) { usergroup { _id slug } } }`, variables: { _id: mocks.users[0]._id, data: { email: mocks.users[0].email, username: mocks.users[0].username, usergroup: mocks.usergroups[2]._id } } }) expect(res.body).toEqual({ data: { updateUser: { usergroup: { _id: mocks.usergroups[2]._id, slug: mocks.usergroups[2].slug } } } }) } exports.setAdmin = function setAdmin () { const User = mongoose.model('User') return User.findByIdAndUpdate(mocks.users[0]._id, { $set: { usergroup: mocks.usergroups[0]._id } }).exec() }
{ "content_hash": "af7bf8ad18acfea8df8af5ce1a89760f", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 59, "avg_line_length": 24.8, "alnum_prop": 0.5659824046920822, "repo_name": "JasonEtco/flintcms", "id": "b754d9bf384b0181f01239c66dc22ef481f0e307", "size": "1364", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/server/apps/common.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "92543" }, { "name": "HTML", "bytes": "4887" }, { "name": "JavaScript", "bytes": "486494" } ], "symlink_target": "" }
(function(app) { app.merge({ config:{ // =require script.Configuration.js }, initiate: function() { var configuration = app.config, local = app.localStorage; var process = function() { // =require script.Initiate.process.js }; var route = function() { // =require script.Initiate.route.js }; var template = function() { // =require script.Initiate.template.js }; var terminal = function() { // =require script.Initiate.terminal.js }; new Promise(function(resolve, reject) { local.select('setting').select('query').select('todo'); // NOTE: Private if (local.name.setting.hasOwnProperty('build')) { if (local.name.setting.build == configuration.build) { // NOTE: ONLOAD configuration.requireUpdate = 0; } else { // NOTE: ONUPDATE configuration.requireUpdate = 2; } } else { // NOTE: ONINSTALL configuration.requireUpdate = 1; // NOTE: Private } if (configuration.requireUpdate) { local.name.setting.version = configuration.version; local.name.setting.build = configuration.build; local.update('setting'); } process().then(function(e) { if (e === true) return template(); return e; }).then(function(e) { if (e === true) { resolve(); } else { reject(e); } }); }).then(function() { app.hashChange(function() { terminal().then(function(e) { // NOTE: if page error if (e !== true)console.log('page error',e); }); }); }, function(e) { if (typeof e === 'object' && e.hasOwnProperty('message')) { app.notification(e.message); } else if (typeof e === 'string') { app.notification(e); } }); }, // NOTE: <dialog> used in page dialog: { container:function(){ return app.elementSelect('div#dialog'); } }, // NOTE: <nav> used in device, dataLink, dataContent nav: { container:function(){ return app.elementSelect('nav'); }, // NOTE: Private }, // NOTE: <header> used in device, dataLink, dataContent header: { container:function(){ return app.elementSelect('header'); } }, // NOTE: <main> used in page main: { container:function(){ return app.elementSelect('main'); } }, // NOTE: <footer> used in none footer: { container:function(){ return app.elementSelect('footer'); } }, // Toggle:{ }, // NOTE: Common // =require script.Common.js }); }(scriptive("app")));
{ "content_hash": "97a78b8ff8674dd38807104e25b3bb56", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 67, "avg_line_length": 28.257425742574256, "alnum_prop": 0.5112123335669236, "repo_name": "scriptive/core", "id": "02892b076f61cef81d5ed1eac417080749ecd2b2", "size": "2854", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "asset/js/script.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package apple.uikit; import apple.NSObject; import apple.foundation.NSArray; import apple.foundation.NSCoder; import apple.foundation.NSDictionary; import apple.foundation.NSMethodSignature; import apple.foundation.NSSet; import apple.foundation.protocol.NSSecureCoding; import apple.uikit.protocol.NSTextLocation; import org.moe.natj.c.ann.FunctionPtr; import org.moe.natj.general.NatJ; import org.moe.natj.general.Pointer; import org.moe.natj.general.ann.Generated; import org.moe.natj.general.ann.Library; import org.moe.natj.general.ann.Mapped; import org.moe.natj.general.ann.MappedReturn; import org.moe.natj.general.ann.NFloat; import org.moe.natj.general.ann.NInt; import org.moe.natj.general.ann.NUInt; import org.moe.natj.general.ann.Owned; import org.moe.natj.general.ann.Runtime; import org.moe.natj.general.ptr.VoidPtr; import org.moe.natj.objc.Class; import org.moe.natj.objc.ObjCRuntime; import org.moe.natj.objc.SEL; import org.moe.natj.objc.ann.ObjCClassBinding; import org.moe.natj.objc.ann.ProtocolClassMethod; import org.moe.natj.objc.ann.Selector; import org.moe.natj.objc.map.ObjCObjectMapper; @Generated @Library("UIKit") @Runtime(ObjCRuntime.class) @ObjCClassBinding public class NSTextSelection extends NSObject implements NSSecureCoding { static { NatJ.register(); } @Generated protected NSTextSelection(Pointer peer) { super(peer); } @Generated @Selector("accessInstanceVariablesDirectly") public static native boolean accessInstanceVariablesDirectly(); /** * Either upstream or downstream selection. NSTextSelectionAffinityDownstream by default. For a 0-length selection, * it describes the visual location of the text cursor between the head of line containing the selection location * (downstream) or tail of the previous line (upstream). For a selection with contents, it describes the logical * direction of non-anchored edge of the selection. */ @Generated @Selector("affinity") @NInt public native long affinity(); @Generated @Owned @Selector("alloc") public static native NSTextSelection alloc(); @Owned @Generated @Selector("allocWithZone:") public static native NSTextSelection allocWithZone(VoidPtr zone); /** * Represents the anchor position offset from the beginning of a line fragment in the visual order for the initial * tap or mouse down. That is from the left for a horizontal line fragment and from the top for a vertical. * Navigating between lines uses this point when the current line fragment associated with the selection is shorter * than the next line visited. 0.0 by default. */ @Generated @Selector("anchorPositionOffset") @NFloat public native double anchorPositionOffset(); @Generated @Selector("automaticallyNotifiesObserversForKey:") public static native boolean automaticallyNotifiesObserversForKey(String key); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:") public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:") public static native void cancelPreviousPerformRequestsWithTargetSelectorObject( @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector, @Mapped(ObjCObjectMapper.class) Object anArgument); @Generated @Selector("classFallbacksForKeyedArchiver") public static native NSArray<String> classFallbacksForKeyedArchiver(); @Generated @Selector("classForKeyedUnarchiver") public static native Class classForKeyedUnarchiver(); @Generated @Selector("debugDescription") public static native String debugDescription_static(); @Generated @Selector("description") public static native String description_static(); @Generated @Selector("encodeWithCoder:") public native void encodeWithCoder(NSCoder coder); /** * The granularity of the selection. NSTextSelectionGranularityByCharacter by default. Extending operations should * modify the selection by the granularity. */ @Generated @Selector("granularity") @NInt public native long granularity(); @Generated @Selector("hash") @NUInt public static native long hash_static(); @Generated @Selector("init") public native NSTextSelection init(); @Generated @Selector("initWithCoder:") public native NSTextSelection initWithCoder(NSCoder coder); @Generated @Selector("initWithLocation:affinity:") public native NSTextSelection initWithLocationAffinity(@Mapped(ObjCObjectMapper.class) NSTextLocation location, @NInt long affinity); @Generated @Selector("initWithRange:affinity:granularity:") public native NSTextSelection initWithRangeAffinityGranularity(NSTextRange range, @NInt long affinity, @NInt long granularity); /** * textRanges should be ordered and not overlapping. Otherwise, textRanges would get normalized by reordered and * merging overlapping ranges. */ @Generated @Selector("initWithRanges:affinity:granularity:") public native NSTextSelection initWithRangesAffinityGranularity(NSArray<? extends NSTextRange> textRanges, @NInt long affinity, @NInt long granularity); @Generated @Selector("instanceMethodForSelector:") @FunctionPtr(name = "call_instanceMethodForSelector_ret") public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector); @Generated @Selector("instanceMethodSignatureForSelector:") public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector); @Generated @Selector("instancesRespondToSelector:") public static native boolean instancesRespondToSelector(SEL aSelector); /** * Indicates whether the selection should be interpreted as logical or visual. */ @Generated @Selector("isLogical") public native boolean isLogical(); @Generated @Selector("isSubclassOfClass:") public static native boolean isSubclassOfClass(Class aClass); /** * Transient text selection during drag handling */ @Generated @Selector("isTransient") public native boolean isTransient(); @Generated @Selector("keyPathsForValuesAffectingValueForKey:") public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key); @Generated @Owned @Selector("new") public static native NSTextSelection new_objc(); @Generated @Selector("resolveClassMethod:") public static native boolean resolveClassMethod(SEL sel); @Generated @Selector("resolveInstanceMethod:") public static native boolean resolveInstanceMethod(SEL sel); /** * Specifies the secondary character location when user taps/clicks at a directional boundary. Setting non-nil * location has a side effect of making -logical=NO. */ @Generated @Selector("secondarySelectionLocation") @MappedReturn(ObjCObjectMapper.class) public native NSTextLocation secondarySelectionLocation(); /** * Represents the anchor position offset from the beginning of a line fragment in the visual order for the initial * tap or mouse down. That is from the left for a horizontal line fragment and from the top for a vertical. * Navigating between lines uses this point when the current line fragment associated with the selection is shorter * than the next line visited. 0.0 by default. */ @Generated @Selector("setAnchorPositionOffset:") public native void setAnchorPositionOffset(@NFloat double value); /** * Indicates whether the selection should be interpreted as logical or visual. */ @Generated @Selector("setLogical:") public native void setLogical(boolean value); /** * Specifies the secondary character location when user taps/clicks at a directional boundary. Setting non-nil * location has a side effect of making -logical=NO. */ @Generated @Selector("setSecondarySelectionLocation:") public native void setSecondarySelectionLocation(@Mapped(ObjCObjectMapper.class) NSTextLocation value); /** * The template attributes used for characters replacing the contents of this selection. */ @Generated @Selector("setTypingAttributes:") public native void setTypingAttributes(NSDictionary<String, ?> value); @Generated @Selector("setVersion:") public static native void setVersion_static(@NInt long aVersion); @Generated @Selector("superclass") public static native Class superclass_static(); @Generated @Selector("supportsSecureCoding") public static native boolean supportsSecureCoding(); @Generated @ProtocolClassMethod("supportsSecureCoding") public boolean _supportsSecureCoding() { return supportsSecureCoding(); } /** * Represents an array of disjoint logical ranges in the selection. The array must be logically ordered. When * editing, all ranges in a text selection constitute a single insertion point. */ @Generated @Selector("textRanges") public native NSArray<? extends NSTextRange> textRanges(); /** * Returns a copy of this selection, replacing this instance's textRanges property with textRanges but keeping all * other attributes the same. */ @Generated @Selector("textSelectionWithTextRanges:") public native NSTextSelection textSelectionWithTextRanges(NSArray<? extends NSTextRange> textRanges); /** * The template attributes used for characters replacing the contents of this selection. */ @Generated @Selector("typingAttributes") public native NSDictionary<String, ?> typingAttributes(); @Generated @Selector("version") @NInt public static native long version_static(); }
{ "content_hash": "3f381d2abd755b755c3b0420b1de5ac1", "timestamp": "", "source": "github", "line_count": 291, "max_line_length": 119, "avg_line_length": 34.59450171821306, "alnum_prop": 0.7355716698122579, "repo_name": "multi-os-engine/moe-core", "id": "92b5c55ebc23a99d622c648eb8ddf83885aea046", "size": "10067", "binary": false, "copies": "1", "ref": "refs/heads/moe-master", "path": "moe.apple/moe.platform.ios/src/main/java/apple/uikit/NSTextSelection.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "892337" }, { "name": "C++", "bytes": "155476" }, { "name": "HTML", "bytes": "42061" }, { "name": "Java", "bytes": "46670080" }, { "name": "Objective-C", "bytes": "94699" }, { "name": "Objective-C++", "bytes": "9128" }, { "name": "Perl", "bytes": "35206" }, { "name": "Python", "bytes": "15418" }, { "name": "Shell", "bytes": "10932" } ], "symlink_target": "" }
package hu.ssh.progressbar.replacers; import hu.ssh.progressbar.progress.Progress; import hu.ssh.progressbar.helpers.HumanTimeFormatter; public class TotalTimeReplacer implements Replacer { private static final String IDENTIFIER = ":total"; @Override public final String getReplaceIdentifier() { return IDENTIFIER; } @Override public final String getReplacementForProgress(final Progress progress) { if (!progress.isRemainingTimeReliable()) { return "?"; } return HumanTimeFormatter.formatTime(progress.getTotalTime()); } }
{ "content_hash": "e4d4e6e4a755afd2beff71bca0fbbe69", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 73, "avg_line_length": 22.875, "alnum_prop": 0.7777777777777778, "repo_name": "arguslab/Argus-SAF", "id": "e22f5f3a41c8bbd5e5a43ad247b206ba86416ecb", "size": "903", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jawa/src/main/java/hu/ssh/progressbar/replacers/TotalTimeReplacer.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "1919" }, { "name": "Batchfile", "bytes": "2289" }, { "name": "Java", "bytes": "201169" }, { "name": "Makefile", "bytes": "702" }, { "name": "Python", "bytes": "301479" }, { "name": "Scala", "bytes": "2333283" }, { "name": "Shell", "bytes": "14609" } ], "symlink_target": "" }
class AppListControllerDelegate; class ExtensionAppModelBuilder; class Profile; namespace app_list { class SearchController; } namespace base { class FilePath; } namespace content { class NotificationDetails; class NotificationSource; } namespace gfx { class ImageSkia; } #if defined(USE_ASH) class AppSyncUIStateWatcher; #endif class AppListViewDelegate : public app_list::AppListViewDelegate, public content::NotificationObserver, public ProfileInfoCacheObserver { public: // The delegate will take ownership of the controller. AppListViewDelegate(scoped_ptr<AppListControllerDelegate> controller, Profile* profile); virtual ~AppListViewDelegate(); private: // Registers the current profile for notifications. void RegisterForNotifications(); // Updates the app list's current profile and ProfileMenuItems. void OnProfileChanged(); // Overridden from app_list::AppListViewDelegate: virtual bool ForceNativeDesktop() const OVERRIDE; virtual void SetProfileByPath(const base::FilePath& profile_path) OVERRIDE; virtual void InitModel(app_list::AppListModel* model) OVERRIDE; virtual app_list::SigninDelegate* GetSigninDelegate() OVERRIDE; virtual void GetShortcutPathForApp( const std::string& app_id, const base::Callback<void(const base::FilePath&)>& callback) OVERRIDE; virtual void StartSearch() OVERRIDE; virtual void StopSearch() OVERRIDE; virtual void OpenSearchResult(app_list::SearchResult* result, int event_flags) OVERRIDE; virtual void InvokeSearchResultAction(app_list::SearchResult* result, int action_index, int event_flags) OVERRIDE; virtual void Dismiss() OVERRIDE; virtual void ViewClosing() OVERRIDE; virtual gfx::ImageSkia GetWindowIcon() OVERRIDE; virtual void OpenSettings() OVERRIDE; virtual void OpenHelp() OVERRIDE; virtual void OpenFeedback() OVERRIDE; virtual void ShowForProfileByPath( const base::FilePath& profile_path) OVERRIDE; virtual content::WebContents* GetStartPageContents() OVERRIDE; virtual const Users& GetUsers() const OVERRIDE; // Overridden from content::NotificationObserver: virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE; // Overridden from ProfileInfoCacheObserver: virtual void OnProfileAdded(const base::FilePath& profile_path) OVERRIDE; virtual void OnProfileWasRemoved(const base::FilePath& profile_path, const base::string16& profile_name) OVERRIDE; virtual void OnProfileNameChanged( const base::FilePath& profile_path, const base::string16& old_profile_name) OVERRIDE; scoped_ptr<ExtensionAppModelBuilder> apps_builder_; scoped_ptr<app_list::SearchController> search_controller_; scoped_ptr<AppListControllerDelegate> controller_; Profile* profile_; Users users_; app_list::AppListModel* model_; // Weak. Owned by AppListView. content::NotificationRegistrar registrar_; ChromeSigninDelegate signin_delegate_; #if defined(USE_ASH) scoped_ptr<AppSyncUIStateWatcher> app_sync_ui_state_watcher_; #endif DISALLOW_COPY_AND_ASSIGN(AppListViewDelegate); }; #endif // CHROME_BROWSER_UI_APP_LIST_APP_LIST_VIEW_DELEGATE_H_
{ "content_hash": "66ed04047375c2413664826c2e40f9f6", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 80, "avg_line_length": 35.9375, "alnum_prop": 0.7208695652173913, "repo_name": "cvsuser-chromium/chromium", "id": "4555eef332e63600b0903f590d4bc619d6da9d77", "size": "4192", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chrome/browser/ui/app_list/app_list_view_delegate.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "6973" }, { "name": "Assembly", "bytes": "36421" }, { "name": "C", "bytes": "6924841" }, { "name": "C++", "bytes": "179649999" }, { "name": "CSS", "bytes": "812951" }, { "name": "Java", "bytes": "3768838" }, { "name": "JavaScript", "bytes": "8338074" }, { "name": "Makefile", "bytes": "52980" }, { "name": "Objective-C", "bytes": "819293" }, { "name": "Objective-C++", "bytes": "6453781" }, { "name": "PHP", "bytes": "61320" }, { "name": "Perl", "bytes": "17897" }, { "name": "Python", "bytes": "5640877" }, { "name": "Rebol", "bytes": "262" }, { "name": "Shell", "bytes": "648699" }, { "name": "XSLT", "bytes": "418" }, { "name": "nesC", "bytes": "15926" } ], "symlink_target": "" }
// // GTLQueryCivicInfo.h // // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // Google Civic Information API (civicinfo/v2) // Description: // An API for accessing civic information. // Documentation: // https://developers.google.com/civic-information // Classes: // GTLQueryCivicInfo (5 custom class methods, 10 custom properties) #if GTL_BUILT_AS_FRAMEWORK #import "GTL/GTLQuery.h" #else #import "GTLQuery.h" #endif @interface GTLQueryCivicInfo : GTLQuery // // Parameters valid on all methods. // // Selector specifying which fields to include in a partial response. @property (nonatomic, copy) NSString *fields; // // Method-specific parameters; see the comments below for more information. // @property (nonatomic, copy) NSString *address; @property (nonatomic, assign) long long electionId; @property (nonatomic, assign) BOOL includeOffices; @property (nonatomic, retain) NSArray *levels; // of NSString @property (nonatomic, copy) NSString *ocdId; @property (nonatomic, assign) BOOL officialOnly; @property (nonatomic, copy) NSString *query; @property (nonatomic, assign) BOOL recursive; @property (nonatomic, retain) NSArray *roles; // of NSString #pragma mark - #pragma mark "divisions" methods // These create a GTLQueryCivicInfo object. // Method: civicinfo.divisions.search // Searches for political divisions by their natural name or OCD ID. // Optional: // query: The search query. Queries can cover any parts of a OCD ID or a human // readable division name. All words given in the query are treated as // required patterns. In addition to that, most query operators of the // Apache Lucene library are supported. See // http://lucene.apache.org/core/2_9_4/queryparsersyntax.html // Fetches a GTLCivicInfoDivisionSearchResponse. + (instancetype)queryForDivisionsSearch; #pragma mark - #pragma mark "elections" methods // These create a GTLQueryCivicInfo object. // Method: civicinfo.elections.electionQuery // List of available elections to query. // Fetches a GTLCivicInfoElectionsQueryResponse. + (instancetype)queryForElectionsElectionQuery; // Method: civicinfo.elections.voterInfoQuery // Looks up information relevant to a voter based on the voter's registered // address. // Required: // address: The registered address of the voter to look up. // Optional: // electionId: The unique ID of the election to look up. A list of election // IDs can be obtained at // https://www.googleapis.com/civicinfo/{version}/elections (Default 0) // officialOnly: If set to true, only data from official state sources will be // returned. (Default false) // Fetches a GTLCivicInfoVoterInfoResponse. + (instancetype)queryForElectionsVoterInfoQueryWithAddress:(NSString *)address; #pragma mark - #pragma mark "representatives" methods // These create a GTLQueryCivicInfo object. // Method: civicinfo.representatives.representativeInfoByAddress // Looks up political geography and representative information for a single // address. // Optional: // address: The address to look up. May only be specified if the field ocdId // is not given in the URL. // includeOffices: Whether to return information about offices and officials. // If false, only the top-level district information will be returned. // (Default true) // levels: A list of office levels to filter by. Only offices that serve at // least one of these levels will be returned. Divisions that don't contain // a matching office will not be returned. // kGTLCivicInfoLevelsAdministrativeArea1: "administrativeArea1" // kGTLCivicInfoLevelsAdministrativeArea2: "administrativeArea2" // kGTLCivicInfoLevelsCountry: "country" // kGTLCivicInfoLevelsInternational: "international" // kGTLCivicInfoLevelsLocality: "locality" // kGTLCivicInfoLevelsRegional: "regional" // kGTLCivicInfoLevelsSpecial: "special" // kGTLCivicInfoLevelsSubLocality1: "subLocality1" // kGTLCivicInfoLevelsSubLocality2: "subLocality2" // roles: A list of office roles to filter by. Only offices fulfilling one of // these roles will be returned. Divisions that don't contain a matching // office will not be returned. // kGTLCivicInfoRolesDeputyHeadOfGovernment: "deputyHeadOfGovernment" // kGTLCivicInfoRolesExecutiveCouncil: "executiveCouncil" // kGTLCivicInfoRolesGovernmentOfficer: "governmentOfficer" // kGTLCivicInfoRolesHeadOfGovernment: "headOfGovernment" // kGTLCivicInfoRolesHeadOfState: "headOfState" // kGTLCivicInfoRolesHighestCourtJudge: "highestCourtJudge" // kGTLCivicInfoRolesJudge: "judge" // kGTLCivicInfoRolesLegislatorLowerBody: "legislatorLowerBody" // kGTLCivicInfoRolesLegislatorUpperBody: "legislatorUpperBody" // kGTLCivicInfoRolesSchoolBoard: "schoolBoard" // kGTLCivicInfoRolesSpecialPurposeOfficer: "specialPurposeOfficer" // Fetches a GTLCivicInfoRepresentativeInfoResponse. + (instancetype)queryForRepresentativesRepresentativeInfoByAddress; // Method: civicinfo.representatives.representativeInfoByDivision // Looks up representative information for a single geographic division. // Required: // ocdId: The Open Civic Data division identifier of the division to look up. // Optional: // levels: A list of office levels to filter by. Only offices that serve at // least one of these levels will be returned. Divisions that don't contain // a matching office will not be returned. // kGTLCivicInfoLevelsAdministrativeArea1: "administrativeArea1" // kGTLCivicInfoLevelsAdministrativeArea2: "administrativeArea2" // kGTLCivicInfoLevelsCountry: "country" // kGTLCivicInfoLevelsInternational: "international" // kGTLCivicInfoLevelsLocality: "locality" // kGTLCivicInfoLevelsRegional: "regional" // kGTLCivicInfoLevelsSpecial: "special" // kGTLCivicInfoLevelsSubLocality1: "subLocality1" // kGTLCivicInfoLevelsSubLocality2: "subLocality2" // recursive: If true, information about all divisions contained in the // division requested will be included as well. For example, if querying // ocd-division/country:us/district:dc, this would also return all DC's // wards and ANCs. // roles: A list of office roles to filter by. Only offices fulfilling one of // these roles will be returned. Divisions that don't contain a matching // office will not be returned. // kGTLCivicInfoRolesDeputyHeadOfGovernment: "deputyHeadOfGovernment" // kGTLCivicInfoRolesExecutiveCouncil: "executiveCouncil" // kGTLCivicInfoRolesGovernmentOfficer: "governmentOfficer" // kGTLCivicInfoRolesHeadOfGovernment: "headOfGovernment" // kGTLCivicInfoRolesHeadOfState: "headOfState" // kGTLCivicInfoRolesHighestCourtJudge: "highestCourtJudge" // kGTLCivicInfoRolesJudge: "judge" // kGTLCivicInfoRolesLegislatorLowerBody: "legislatorLowerBody" // kGTLCivicInfoRolesLegislatorUpperBody: "legislatorUpperBody" // kGTLCivicInfoRolesSchoolBoard: "schoolBoard" // kGTLCivicInfoRolesSpecialPurposeOfficer: "specialPurposeOfficer" // Fetches a GTLCivicInfoRepresentativeInfoData. + (instancetype)queryForRepresentativesRepresentativeInfoByDivisionWithOcdId:(NSString *)ocdId; @end
{ "content_hash": "cb811d6fd26c0d2659d8367e34898cfa", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 95, "avg_line_length": 44.8780487804878, "alnum_prop": 0.7544836956521739, "repo_name": "wildsonjr/Google-API-Client", "id": "c1a036333dbe926ae53e874e9ac44945d92c7bf0", "size": "7955", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Source/Services/CivicInfo/Generated/GTLQueryCivicInfo.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "4293" }, { "name": "C++", "bytes": "2926" }, { "name": "Objective-C", "bytes": "6731163" }, { "name": "Ruby", "bytes": "8245" }, { "name": "Shell", "bytes": "3632" } ], "symlink_target": "" }
*Chapter 8 Shiny Dashboards* ------- A simple Shiny App that predicts revenue from user inputted marketing expenditure via a linear regression model. ![app_image](https://github.com/jgendron/com.packtpub.intro.r.bi/blob/master/Chapter8-ShinyDashboards/expenditures-revenue-app-screenshot.png) ####Overview Our scenario for creating such an application is that the marketing group could benefit from a web application to make revenue predictions based on the linear regression model. Some topics utilized by this app are: - creating a `ui.R` and `server.R` file - creating a `sliderInput` widget - rendering a plot within a Shiny app using `renderPlot({})` - using **reactivity** and **variable scoping** ####Installing Required Packages This Shiny app requires 1 package: 1. `install.packages(c('shiny'))` ####Running the App Locally There are 2 ways to run the app: - Running directly from Github: `shiny::runGitHub(repo = 'com.packtpub.intro.r.bi', username = 'jgendron', subdir = 'Chapter8-ShinyDashboards/Ch8-BasicShinyApp/') ` - Cloning the repository to have a local copy: - In RStudio Select "New Project" from "Version Control" - Enter the Clone URL for this repository - `setwd('Chapter8-ShinyDashboards/Ch8-BasicShinyApp')` - `shiny::runApp()` ####Other Resources ... ####About the Author ... (Your name, your background, links to your twitter, github, linkedin, blogs, etc.) License ------- Copyright 2016 Packt Publishing
{ "content_hash": "27e59035e6fe70c2ba1b4ccc6d08e4fa", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 214, "avg_line_length": 29.857142857142858, "alnum_prop": 0.7416267942583732, "repo_name": "757RUG/presentations", "id": "a400f188047d8e196b091254852b3ec357cf7633", "size": "1498", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web-apps-in-r-using-shiny/basic-shiny-app/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3768" }, { "name": "HTML", "bytes": "20062449" }, { "name": "Jupyter Notebook", "bytes": "34761" }, { "name": "Python", "bytes": "14611" }, { "name": "R", "bytes": "90476" } ], "symlink_target": "" }
package apimachinery import ( "context" "fmt" "strconv" "time" appsv1 "k8s.io/api/apps/v1" v1 "k8s.io/api/core/v1" schedulingv1 "k8s.io/api/scheduling/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/util/wait" clientset "k8s.io/client-go/kubernetes" "k8s.io/kubernetes/pkg/quota/v1/evaluator/core" "k8s.io/kubernetes/test/e2e/framework" "k8s.io/kubernetes/test/utils/crd" imageutils "k8s.io/kubernetes/test/utils/image" "github.com/onsi/ginkgo" ) const ( // how long to wait for a resource quota update to occur resourceQuotaTimeout = 30 * time.Second podName = "pfpod" ) var classGold = "gold" var extendedResourceName = "example.com/dongle" var _ = SIGDescribe("ResourceQuota", func() { f := framework.NewDefaultFramework("resourcequota") /* Release: v1.16 Testname: ResourceQuota, object count quota, resourcequotas Description: Create a ResourceQuota. Creation MUST be successful and its ResourceQuotaStatus MUST match to expected used and total allowed resource quota count within namespace. */ framework.ConformanceIt("should create a ResourceQuota and ensure its status is promptly calculated.", func() { ginkgo.By("Counting existing ResourceQuota") c, err := countResourceQuota(f.ClientSet, f.Namespace.Name) framework.ExpectNoError(err) ginkgo.By("Creating a ResourceQuota") quotaName := "test-quota" resourceQuota := newTestResourceQuota(quotaName) _, err = createResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuota) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourceQuotas] = resource.MustParse(strconv.Itoa(c + 1)) err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) }) /* Release: v1.16 Testname: ResourceQuota, object count quota, service Description: Create a ResourceQuota. Creation MUST be successful and its ResourceQuotaStatus MUST match to expected used and total allowed resource quota count within namespace. Create a Service. Its creation MUST be successful and resource usage count against the Service object and resourceQuota object MUST be captured in ResourceQuotaStatus of the ResourceQuota. Delete the Service. Deletion MUST succeed and resource usage count against the Service object MUST be released from ResourceQuotaStatus of the ResourceQuota. */ framework.ConformanceIt("should create a ResourceQuota and capture the life of a service.", func() { ginkgo.By("Counting existing ResourceQuota") c, err := countResourceQuota(f.ClientSet, f.Namespace.Name) framework.ExpectNoError(err) ginkgo.By("Creating a ResourceQuota") quotaName := "test-quota" resourceQuota := newTestResourceQuota(quotaName) _, err = createResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuota) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourceQuotas] = resource.MustParse(strconv.Itoa(c + 1)) err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a Service") service := newTestServiceForQuota("test-service", v1.ServiceTypeClusterIP) service, err = f.ClientSet.CoreV1().Services(f.Namespace.Name).Create(context.TODO(), service, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status captures service creation") usedResources = v1.ResourceList{} usedResources[v1.ResourceQuotas] = resource.MustParse(strconv.Itoa(c + 1)) usedResources[v1.ResourceServices] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting a Service") err = f.ClientSet.CoreV1().Services(f.Namespace.Name).Delete(context.TODO(), service.Name, metav1.DeleteOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released usage") usedResources[v1.ResourceServices] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) }) /* Release: v1.16 Testname: ResourceQuota, object count quota, secret Description: Create a ResourceQuota. Creation MUST be successful and its ResourceQuotaStatus MUST match to expected used and total allowed resource quota count within namespace. Create a Secret. Its creation MUST be successful and resource usage count against the Secret object and resourceQuota object MUST be captured in ResourceQuotaStatus of the ResourceQuota. Delete the Secret. Deletion MUST succeed and resource usage count against the Secret object MUST be released from ResourceQuotaStatus of the ResourceQuota. */ framework.ConformanceIt("should create a ResourceQuota and capture the life of a secret.", func() { ginkgo.By("Discovering how many secrets are in namespace by default") found, unchanged := 0, 0 // On contended servers the service account controller can slow down, leading to the count changing during a run. // Wait up to 5s for the count to stabilize, assuming that updates come at a consistent rate, and are not held indefinitely. wait.Poll(1*time.Second, 30*time.Second, func() (bool, error) { secrets, err := f.ClientSet.CoreV1().Secrets(f.Namespace.Name).List(context.TODO(), metav1.ListOptions{}) framework.ExpectNoError(err) if len(secrets.Items) == found { // loop until the number of secrets has stabilized for 5 seconds unchanged++ return unchanged > 4, nil } unchanged = 0 found = len(secrets.Items) return false, nil }) defaultSecrets := fmt.Sprintf("%d", found) hardSecrets := fmt.Sprintf("%d", found+1) ginkgo.By("Counting existing ResourceQuota") c, err := countResourceQuota(f.ClientSet, f.Namespace.Name) framework.ExpectNoError(err) ginkgo.By("Creating a ResourceQuota") quotaName := "test-quota" resourceQuota := newTestResourceQuota(quotaName) resourceQuota.Spec.Hard[v1.ResourceSecrets] = resource.MustParse(hardSecrets) _, err = createResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuota) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourceQuotas] = resource.MustParse(strconv.Itoa(c + 1)) usedResources[v1.ResourceSecrets] = resource.MustParse(defaultSecrets) err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a Secret") secret := newTestSecretForQuota("test-secret") secret, err = f.ClientSet.CoreV1().Secrets(f.Namespace.Name).Create(context.TODO(), secret, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status captures secret creation") usedResources = v1.ResourceList{} usedResources[v1.ResourceSecrets] = resource.MustParse(hardSecrets) // we expect there to be two secrets because each namespace will receive // a service account token secret by default err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting a secret") err = f.ClientSet.CoreV1().Secrets(f.Namespace.Name).Delete(context.TODO(), secret.Name, metav1.DeleteOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released usage") usedResources[v1.ResourceSecrets] = resource.MustParse(defaultSecrets) err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) }) /* Release: v1.16 Testname: ResourceQuota, object count quota, pod Description: Create a ResourceQuota. Creation MUST be successful and its ResourceQuotaStatus MUST match to expected used and total allowed resource quota count within namespace. Create a Pod with resource request count for CPU, Memory, EphemeralStorage and ExtendedResourceName. Pod creation MUST be successful and respective resource usage count MUST be captured in ResourceQuotaStatus of the ResourceQuota. Create another Pod with resource request exceeding remaining quota. Pod creation MUST fail as the request exceeds ResourceQuota limits. Update the successfully created pod's resource requests. Updation MUST fail as a Pod can not dynamically update its resource requirements. Delete the successfully created Pod. Pod Deletion MUST be scuccessful and it MUST release the allocated resource counts from ResourceQuotaStatus of the ResourceQuota. */ framework.ConformanceIt("should create a ResourceQuota and capture the life of a pod.", func() { ginkgo.By("Counting existing ResourceQuota") c, err := countResourceQuota(f.ClientSet, f.Namespace.Name) framework.ExpectNoError(err) ginkgo.By("Creating a ResourceQuota") quotaName := "test-quota" resourceQuota := newTestResourceQuota(quotaName) _, err = createResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuota) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourceQuotas] = resource.MustParse(strconv.Itoa(c + 1)) err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a Pod that fits quota") podName := "test-pod" requests := v1.ResourceList{} limits := v1.ResourceList{} requests[v1.ResourceCPU] = resource.MustParse("500m") requests[v1.ResourceMemory] = resource.MustParse("252Mi") requests[v1.ResourceEphemeralStorage] = resource.MustParse("30Gi") requests[v1.ResourceName(extendedResourceName)] = resource.MustParse("2") limits[v1.ResourceName(extendedResourceName)] = resource.MustParse("2") pod := newTestPodForQuota(f, podName, requests, limits) pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{}) framework.ExpectNoError(err) podToUpdate := pod ginkgo.By("Ensuring ResourceQuota status captures the pod usage") usedResources[v1.ResourceQuotas] = resource.MustParse(strconv.Itoa(c + 1)) usedResources[v1.ResourcePods] = resource.MustParse("1") usedResources[v1.ResourceCPU] = requests[v1.ResourceCPU] usedResources[v1.ResourceMemory] = requests[v1.ResourceMemory] usedResources[v1.ResourceEphemeralStorage] = requests[v1.ResourceEphemeralStorage] usedResources[v1.ResourceName(v1.DefaultResourceRequestsPrefix+extendedResourceName)] = requests[v1.ResourceName(extendedResourceName)] err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) ginkgo.By("Not allowing a pod to be created that exceeds remaining quota") requests = v1.ResourceList{} requests[v1.ResourceCPU] = resource.MustParse("600m") requests[v1.ResourceMemory] = resource.MustParse("100Mi") pod = newTestPodForQuota(f, "fail-pod", requests, v1.ResourceList{}) _, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{}) framework.ExpectError(err) ginkgo.By("Not allowing a pod to be created that exceeds remaining quota(validation on extended resources)") requests = v1.ResourceList{} limits = v1.ResourceList{} requests[v1.ResourceCPU] = resource.MustParse("500m") requests[v1.ResourceMemory] = resource.MustParse("100Mi") requests[v1.ResourceEphemeralStorage] = resource.MustParse("30Gi") requests[v1.ResourceName(extendedResourceName)] = resource.MustParse("2") limits[v1.ResourceName(extendedResourceName)] = resource.MustParse("2") pod = newTestPodForQuota(f, "fail-pod-for-extended-resource", requests, limits) _, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{}) framework.ExpectError(err) ginkgo.By("Ensuring a pod cannot update its resource requirements") // a pod cannot dynamically update its resource requirements. requests = v1.ResourceList{} requests[v1.ResourceCPU] = resource.MustParse("100m") requests[v1.ResourceMemory] = resource.MustParse("100Mi") requests[v1.ResourceEphemeralStorage] = resource.MustParse("10Gi") podToUpdate.Spec.Containers[0].Resources.Requests = requests _, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Update(context.TODO(), podToUpdate, metav1.UpdateOptions{}) framework.ExpectError(err) ginkgo.By("Ensuring attempts to update pod resource requirements did not change quota usage") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting the pod") err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), podName, *metav1.NewDeleteOptions(0)) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released the pod usage") usedResources[v1.ResourceQuotas] = resource.MustParse(strconv.Itoa(c + 1)) usedResources[v1.ResourcePods] = resource.MustParse("0") usedResources[v1.ResourceCPU] = resource.MustParse("0") usedResources[v1.ResourceMemory] = resource.MustParse("0") usedResources[v1.ResourceEphemeralStorage] = resource.MustParse("0") usedResources[v1.ResourceName(v1.DefaultResourceRequestsPrefix+extendedResourceName)] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) }) /* Release: v1.16 Testname: ResourceQuota, object count quota, configmap Description: Create a ResourceQuota. Creation MUST be successful and its ResourceQuotaStatus MUST match to expected used and total allowed resource quota count within namespace. Create a ConfigMap. Its creation MUST be successful and resource usage count against the ConfigMap object MUST be captured in ResourceQuotaStatus of the ResourceQuota. Delete the ConfigMap. Deletion MUST succeed and resource usage count against the ConfigMap object MUST be released from ResourceQuotaStatus of the ResourceQuota. */ framework.ConformanceIt("should create a ResourceQuota and capture the life of a configMap.", func() { found, unchanged := 0, 0 // On contended servers the service account controller can slow down, leading to the count changing during a run. // Wait up to 15s for the count to stabilize, assuming that updates come at a consistent rate, and are not held indefinitely. wait.Poll(1*time.Second, time.Minute, func() (bool, error) { configmaps, err := f.ClientSet.CoreV1().ConfigMaps(f.Namespace.Name).List(context.TODO(), metav1.ListOptions{}) framework.ExpectNoError(err) if len(configmaps.Items) == found { // loop until the number of configmaps has stabilized for 15 seconds unchanged++ return unchanged > 15, nil } unchanged = 0 found = len(configmaps.Items) return false, nil }) defaultConfigMaps := fmt.Sprintf("%d", found) hardConfigMaps := fmt.Sprintf("%d", found+1) ginkgo.By("Counting existing ResourceQuota") c, err := countResourceQuota(f.ClientSet, f.Namespace.Name) framework.ExpectNoError(err) ginkgo.By("Creating a ResourceQuota") quotaName := "test-quota" resourceQuota := newTestResourceQuota(quotaName) _, err = createResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuota) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourceQuotas] = resource.MustParse(strconv.Itoa(c + 1)) usedResources[v1.ResourceConfigMaps] = resource.MustParse(defaultConfigMaps) err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a ConfigMap") configMap := newTestConfigMapForQuota("test-configmap") configMap, err = f.ClientSet.CoreV1().ConfigMaps(f.Namespace.Name).Create(context.TODO(), configMap, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status captures configMap creation") usedResources = v1.ResourceList{} usedResources[v1.ResourceQuotas] = resource.MustParse(strconv.Itoa(c + 1)) // we expect there to be two configmaps because each namespace will receive // a ca.crt configmap by default. // ref:https://github.com/kubernetes/kubernetes/pull/68812 usedResources[v1.ResourceConfigMaps] = resource.MustParse(hardConfigMaps) err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting a ConfigMap") err = f.ClientSet.CoreV1().ConfigMaps(f.Namespace.Name).Delete(context.TODO(), configMap.Name, metav1.DeleteOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released usage") usedResources[v1.ResourceConfigMaps] = resource.MustParse(defaultConfigMaps) err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) }) /* Release: v1.16 Testname: ResourceQuota, object count quota, replicationController Description: Create a ResourceQuota. Creation MUST be successful and its ResourceQuotaStatus MUST match to expected used and total allowed resource quota count within namespace. Create a ReplicationController. Its creation MUST be successful and resource usage count against the ReplicationController object MUST be captured in ResourceQuotaStatus of the ResourceQuota. Delete the ReplicationController. Deletion MUST succeed and resource usage count against the ReplicationController object MUST be released from ResourceQuotaStatus of the ResourceQuota. */ framework.ConformanceIt("should create a ResourceQuota and capture the life of a replication controller.", func() { ginkgo.By("Counting existing ResourceQuota") c, err := countResourceQuota(f.ClientSet, f.Namespace.Name) framework.ExpectNoError(err) ginkgo.By("Creating a ResourceQuota") quotaName := "test-quota" resourceQuota := newTestResourceQuota(quotaName) _, err = createResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuota) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourceQuotas] = resource.MustParse(strconv.Itoa(c + 1)) usedResources[v1.ResourceReplicationControllers] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a ReplicationController") replicationController := newTestReplicationControllerForQuota("test-rc", "nginx", 0) replicationController, err = f.ClientSet.CoreV1().ReplicationControllers(f.Namespace.Name).Create(context.TODO(), replicationController, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status captures replication controller creation") usedResources = v1.ResourceList{} usedResources[v1.ResourceReplicationControllers] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting a ReplicationController") // Without the delete options, the object isn't actually // removed until the GC verifies that all children have been // detached. ReplicationControllers default to "orphan", which // is different from most resources. (Why? To preserve a common // workflow from prior to the GC's introduction.) err = f.ClientSet.CoreV1().ReplicationControllers(f.Namespace.Name).Delete(context.TODO(), replicationController.Name, metav1.DeleteOptions{ PropagationPolicy: func() *metav1.DeletionPropagation { p := metav1.DeletePropagationBackground return &p }(), }) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released usage") usedResources[v1.ResourceReplicationControllers] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) }) /* Release: v1.16 Testname: ResourceQuota, object count quota, replicaSet Description: Create a ResourceQuota. Creation MUST be successful and its ResourceQuotaStatus MUST match to expected used and total allowed resource quota count within namespace. Create a ReplicaSet. Its creation MUST be successful and resource usage count against the ReplicaSet object MUST be captured in ResourceQuotaStatus of the ResourceQuota. Delete the ReplicaSet. Deletion MUST succeed and resource usage count against the ReplicaSet object MUST be released from ResourceQuotaStatus of the ResourceQuota. */ framework.ConformanceIt("should create a ResourceQuota and capture the life of a replica set.", func() { ginkgo.By("Counting existing ResourceQuota") c, err := countResourceQuota(f.ClientSet, f.Namespace.Name) framework.ExpectNoError(err) ginkgo.By("Creating a ResourceQuota") quotaName := "test-quota" resourceQuota := newTestResourceQuota(quotaName) _, err = createResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuota) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourceQuotas] = resource.MustParse(strconv.Itoa(c + 1)) usedResources[v1.ResourceName("count/replicasets.apps")] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a ReplicaSet") replicaSet := newTestReplicaSetForQuota("test-rs", "nginx", 0) replicaSet, err = f.ClientSet.AppsV1().ReplicaSets(f.Namespace.Name).Create(context.TODO(), replicaSet, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status captures replicaset creation") usedResources = v1.ResourceList{} usedResources[v1.ResourceName("count/replicasets.apps")] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting a ReplicaSet") err = f.ClientSet.AppsV1().ReplicaSets(f.Namespace.Name).Delete(context.TODO(), replicaSet.Name, metav1.DeleteOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released usage") usedResources[v1.ResourceName("count/replicasets.apps")] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) }) /* Release: v1.16 Testname: ResourceQuota, object count quota, pvc Description: Create a ResourceQuota. Creation MUST be successful and its ResourceQuotaStatus MUST match to expected used and total allowed resource quota count within namespace. Create PersistentVolumeClaim (PVC) to request storage capacity of 1G. PVC creation MUST be successful and resource usage count against the PVC and storage object MUST be captured in ResourceQuotaStatus of the ResourceQuota. Delete the PVC. Deletion MUST succeed and resource usage count against its PVC and storage object MUST be released from ResourceQuotaStatus of the ResourceQuota. [NotConformancePromotable] as test suite do not have any e2e at this moment which are explicitly verifying PV and PVC behaviour. */ ginkgo.It("should create a ResourceQuota and capture the life of a persistent volume claim. [sig-storage]", func() { ginkgo.By("Counting existing ResourceQuota") c, err := countResourceQuota(f.ClientSet, f.Namespace.Name) framework.ExpectNoError(err) ginkgo.By("Creating a ResourceQuota") quotaName := "test-quota" resourceQuota := newTestResourceQuota(quotaName) _, err = createResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuota) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourceQuotas] = resource.MustParse(strconv.Itoa(c + 1)) usedResources[v1.ResourcePersistentVolumeClaims] = resource.MustParse("0") usedResources[v1.ResourceRequestsStorage] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a PersistentVolumeClaim") pvc := newTestPersistentVolumeClaimForQuota("test-claim") pvc, err = f.ClientSet.CoreV1().PersistentVolumeClaims(f.Namespace.Name).Create(context.TODO(), pvc, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status captures persistent volume claim creation") usedResources = v1.ResourceList{} usedResources[v1.ResourcePersistentVolumeClaims] = resource.MustParse("1") usedResources[v1.ResourceRequestsStorage] = resource.MustParse("1Gi") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting a PersistentVolumeClaim") err = f.ClientSet.CoreV1().PersistentVolumeClaims(f.Namespace.Name).Delete(context.TODO(), pvc.Name, metav1.DeleteOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released usage") usedResources[v1.ResourcePersistentVolumeClaims] = resource.MustParse("0") usedResources[v1.ResourceRequestsStorage] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) }) /* Release: v1.16 Testname: ResourceQuota, object count quota, storageClass Description: Create a ResourceQuota. Creation MUST be successful and its ResourceQuotaStatus MUST match to expected used and total allowed resource quota count within namespace. Create PersistentVolumeClaim (PVC) with specified storageClass to request storage capacity of 1G. PVC creation MUST be successful and resource usage count against PVC, storageClass and storage object MUST be captured in ResourceQuotaStatus of the ResourceQuota. Delete the PVC. Deletion MUST succeed and resource usage count against PVC, storageClass and storage object MUST be released from ResourceQuotaStatus of the ResourceQuota. [NotConformancePromotable] as test suite do not have any e2e at this moment which are explicitly verifying PV and PVC behaviour. */ ginkgo.It("should create a ResourceQuota and capture the life of a persistent volume claim with a storage class. [sig-storage]", func() { ginkgo.By("Counting existing ResourceQuota") c, err := countResourceQuota(f.ClientSet, f.Namespace.Name) framework.ExpectNoError(err) ginkgo.By("Creating a ResourceQuota") quotaName := "test-quota" resourceQuota := newTestResourceQuota(quotaName) _, err = createResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuota) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourceQuotas] = resource.MustParse(strconv.Itoa(c + 1)) usedResources[v1.ResourcePersistentVolumeClaims] = resource.MustParse("0") usedResources[v1.ResourceRequestsStorage] = resource.MustParse("0") usedResources[core.V1ResourceByStorageClass(classGold, v1.ResourcePersistentVolumeClaims)] = resource.MustParse("0") usedResources[core.V1ResourceByStorageClass(classGold, v1.ResourceRequestsStorage)] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a PersistentVolumeClaim with storage class") pvc := newTestPersistentVolumeClaimForQuota("test-claim") pvc.Spec.StorageClassName = &classGold pvc, err = f.ClientSet.CoreV1().PersistentVolumeClaims(f.Namespace.Name).Create(context.TODO(), pvc, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status captures persistent volume claim creation") usedResources = v1.ResourceList{} usedResources[v1.ResourcePersistentVolumeClaims] = resource.MustParse("1") usedResources[v1.ResourceRequestsStorage] = resource.MustParse("1Gi") usedResources[core.V1ResourceByStorageClass(classGold, v1.ResourcePersistentVolumeClaims)] = resource.MustParse("1") usedResources[core.V1ResourceByStorageClass(classGold, v1.ResourceRequestsStorage)] = resource.MustParse("1Gi") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting a PersistentVolumeClaim") err = f.ClientSet.CoreV1().PersistentVolumeClaims(f.Namespace.Name).Delete(context.TODO(), pvc.Name, metav1.DeleteOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released usage") usedResources[v1.ResourcePersistentVolumeClaims] = resource.MustParse("0") usedResources[v1.ResourceRequestsStorage] = resource.MustParse("0") usedResources[core.V1ResourceByStorageClass(classGold, v1.ResourcePersistentVolumeClaims)] = resource.MustParse("0") usedResources[core.V1ResourceByStorageClass(classGold, v1.ResourceRequestsStorage)] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) }) ginkgo.It("should create a ResourceQuota and capture the life of a custom resource.", func() { ginkgo.By("Creating a Custom Resource Definition") testcrd, err := crd.CreateTestCRD(f) framework.ExpectNoError(err) defer testcrd.CleanUp() countResourceName := "count/" + testcrd.Crd.Spec.Names.Plural + "." + testcrd.Crd.Spec.Group // resourcequota controller needs to take 30 seconds at most to detect the new custom resource. // in order to make sure the resourcequota controller knows this resource, we create one test // resourcequota object, and triggering updates on it until the status is updated. quotaName := "quota-for-" + testcrd.Crd.Spec.Names.Plural _, err = createResourceQuota(f.ClientSet, f.Namespace.Name, &v1.ResourceQuota{ ObjectMeta: metav1.ObjectMeta{Name: quotaName}, Spec: v1.ResourceQuotaSpec{ Hard: v1.ResourceList{ v1.ResourceName(countResourceName): resource.MustParse("0"), }, }, }) framework.ExpectNoError(err) err = updateResourceQuotaUntilUsageAppears(f.ClientSet, f.Namespace.Name, quotaName, v1.ResourceName(countResourceName)) framework.ExpectNoError(err) err = f.ClientSet.CoreV1().ResourceQuotas(f.Namespace.Name).Delete(context.TODO(), quotaName, metav1.DeleteOptions{}) framework.ExpectNoError(err) ginkgo.By("Counting existing ResourceQuota") c, err := countResourceQuota(f.ClientSet, f.Namespace.Name) framework.ExpectNoError(err) ginkgo.By("Creating a ResourceQuota") quotaName = "test-quota" resourceQuota := newTestResourceQuota(quotaName) resourceQuota.Spec.Hard[v1.ResourceName(countResourceName)] = resource.MustParse("1") _, err = createResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuota) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourceQuotas] = resource.MustParse(strconv.Itoa(c + 1)) usedResources[v1.ResourceName(countResourceName)] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a custom resource") resourceClient := testcrd.DynamicClients["v1"] testcr, err := instantiateCustomResource(&unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": testcrd.Crd.Spec.Group + "/" + testcrd.Crd.Spec.Versions[0].Name, "kind": testcrd.Crd.Spec.Names.Kind, "metadata": map[string]interface{}{ "name": "test-cr-1", }, }, }, resourceClient, testcrd.Crd) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status captures custom resource creation") usedResources = v1.ResourceList{} usedResources[v1.ResourceName(countResourceName)] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a second custom resource") _, err = instantiateCustomResource(&unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": testcrd.Crd.Spec.Group + "/" + testcrd.Crd.Spec.Versions[0].Name, "kind": testcrd.Crd.Spec.Names.Kind, "metadata": map[string]interface{}{ "name": "test-cr-2", }, }, }, resourceClient, testcrd.Crd) // since we only give one quota, this creation should fail. framework.ExpectError(err) ginkgo.By("Deleting a custom resource") err = deleteCustomResource(resourceClient, testcr.GetName()) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released usage") usedResources[v1.ResourceName(countResourceName)] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, quotaName, usedResources) framework.ExpectNoError(err) }) /* Release: v1.16 Testname: ResourceQuota, quota scope, Terminating and NotTerminating scope Description: Create two ResourceQuotas, one with 'Terminating' scope and another 'NotTerminating' scope. Request and the limit counts for CPU and Memory resources are set for the ResourceQuota. Creation MUST be successful and their ResourceQuotaStatus MUST match to expected used and total allowed resource quota count within namespace. Create a Pod with specified CPU and Memory ResourceRequirements fall within quota limits. Pod creation MUST be successful and usage count MUST be captured in ResourceQuotaStatus of 'NotTerminating' scoped ResourceQuota but MUST NOT in 'Terminating' scoped ResourceQuota. Delete the Pod. Pod deletion MUST succeed and Pod resource usage count MUST be released from ResourceQuotaStatus of 'NotTerminating' scoped ResourceQuota. Create a pod with specified activeDeadlineSeconds and resourceRequirements for CPU and Memory fall within quota limits. Pod creation MUST be successful and usage count MUST be captured in ResourceQuotaStatus of 'Terminating' scoped ResourceQuota but MUST NOT in 'NotTerminating' scoped ResourceQuota. Delete the Pod. Pod deletion MUST succeed and Pod resource usage count MUST be released from ResourceQuotaStatus of 'Terminating' scoped ResourceQuota. */ framework.ConformanceIt("should verify ResourceQuota with terminating scopes.", func() { ginkgo.By("Creating a ResourceQuota with terminating scope") quotaTerminatingName := "quota-terminating" resourceQuotaTerminating, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScope(quotaTerminatingName, v1.ResourceQuotaScopeTerminating)) framework.ExpectNoError(err) ginkgo.By("Ensuring ResourceQuota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaTerminating.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a ResourceQuota with not terminating scope") quotaNotTerminatingName := "quota-not-terminating" resourceQuotaNotTerminating, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScope(quotaNotTerminatingName, v1.ResourceQuotaScopeNotTerminating)) framework.ExpectNoError(err) ginkgo.By("Ensuring ResourceQuota status is calculated") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotTerminating.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a long running pod") podName := "test-pod" requests := v1.ResourceList{} requests[v1.ResourceCPU] = resource.MustParse("500m") requests[v1.ResourceMemory] = resource.MustParse("200Mi") limits := v1.ResourceList{} limits[v1.ResourceCPU] = resource.MustParse("1") limits[v1.ResourceMemory] = resource.MustParse("400Mi") pod := newTestPodForQuota(f, podName, requests, limits) _, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with not terminating scope captures the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("1") usedResources[v1.ResourceRequestsCPU] = requests[v1.ResourceCPU] usedResources[v1.ResourceRequestsMemory] = requests[v1.ResourceMemory] usedResources[v1.ResourceLimitsCPU] = limits[v1.ResourceCPU] usedResources[v1.ResourceLimitsMemory] = limits[v1.ResourceMemory] err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotTerminating.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with terminating scope ignored the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") usedResources[v1.ResourceRequestsCPU] = resource.MustParse("0") usedResources[v1.ResourceRequestsMemory] = resource.MustParse("0") usedResources[v1.ResourceLimitsCPU] = resource.MustParse("0") usedResources[v1.ResourceLimitsMemory] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaTerminating.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting the pod") err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), podName, *metav1.NewDeleteOptions(0)) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") usedResources[v1.ResourceRequestsCPU] = resource.MustParse("0") usedResources[v1.ResourceRequestsMemory] = resource.MustParse("0") usedResources[v1.ResourceLimitsCPU] = resource.MustParse("0") usedResources[v1.ResourceLimitsMemory] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotTerminating.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a terminating pod") podName = "terminating-pod" pod = newTestPodForQuota(f, podName, requests, limits) activeDeadlineSeconds := int64(3600) pod.Spec.ActiveDeadlineSeconds = &activeDeadlineSeconds _, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with terminating scope captures the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("1") usedResources[v1.ResourceRequestsCPU] = requests[v1.ResourceCPU] usedResources[v1.ResourceRequestsMemory] = requests[v1.ResourceMemory] usedResources[v1.ResourceLimitsCPU] = limits[v1.ResourceCPU] usedResources[v1.ResourceLimitsMemory] = limits[v1.ResourceMemory] err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaTerminating.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with not terminating scope ignored the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") usedResources[v1.ResourceRequestsCPU] = resource.MustParse("0") usedResources[v1.ResourceRequestsMemory] = resource.MustParse("0") usedResources[v1.ResourceLimitsCPU] = resource.MustParse("0") usedResources[v1.ResourceLimitsMemory] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotTerminating.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting the pod") err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), podName, *metav1.NewDeleteOptions(0)) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") usedResources[v1.ResourceRequestsCPU] = resource.MustParse("0") usedResources[v1.ResourceRequestsMemory] = resource.MustParse("0") usedResources[v1.ResourceLimitsCPU] = resource.MustParse("0") usedResources[v1.ResourceLimitsMemory] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaTerminating.Name, usedResources) framework.ExpectNoError(err) }) /* Release: v1.16 Testname: ResourceQuota, quota scope, BestEffort and NotBestEffort scope Description: Create two ResourceQuotas, one with 'BestEffort' scope and another with 'NotBestEffort' scope. Creation MUST be successful and their ResourceQuotaStatus MUST match to expected used and total allowed resource quota count within namespace. Create a 'BestEffort' Pod by not explicitly specifying resource limits and requests. Pod creation MUST be successful and usage count MUST be captured in ResourceQuotaStatus of 'BestEffort' scoped ResourceQuota but MUST NOT in 'NotBestEffort' scoped ResourceQuota. Delete the Pod. Pod deletion MUST succeed and Pod resource usage count MUST be released from ResourceQuotaStatus of 'BestEffort' scoped ResourceQuota. Create a 'NotBestEffort' Pod by explicitly specifying resource limits and requests. Pod creation MUST be successful and usage count MUST be captured in ResourceQuotaStatus of 'NotBestEffort' scoped ResourceQuota but MUST NOT in 'BestEffort' scoped ResourceQuota. Delete the Pod. Pod deletion MUST succeed and Pod resource usage count MUST be released from ResourceQuotaStatus of 'NotBestEffort' scoped ResourceQuota. */ framework.ConformanceIt("should verify ResourceQuota with best effort scope.", func() { ginkgo.By("Creating a ResourceQuota with best effort scope") resourceQuotaBestEffort, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScope("quota-besteffort", v1.ResourceQuotaScopeBestEffort)) framework.ExpectNoError(err) ginkgo.By("Ensuring ResourceQuota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaBestEffort.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a ResourceQuota with not best effort scope") resourceQuotaNotBestEffort, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScope("quota-not-besteffort", v1.ResourceQuotaScopeNotBestEffort)) framework.ExpectNoError(err) ginkgo.By("Ensuring ResourceQuota status is calculated") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotBestEffort.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a best-effort pod") pod := newTestPodForQuota(f, podName, v1.ResourceList{}, v1.ResourceList{}) pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with best effort scope captures the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaBestEffort.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with not best effort ignored the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotBestEffort.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting the pod") err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), pod.Name, *metav1.NewDeleteOptions(0)) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaBestEffort.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a not best-effort pod") requests := v1.ResourceList{} requests[v1.ResourceCPU] = resource.MustParse("500m") requests[v1.ResourceMemory] = resource.MustParse("200Mi") limits := v1.ResourceList{} limits[v1.ResourceCPU] = resource.MustParse("1") limits[v1.ResourceMemory] = resource.MustParse("400Mi") pod = newTestPodForQuota(f, "burstable-pod", requests, limits) pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with not best effort scope captures the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotBestEffort.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with best effort scope ignored the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaBestEffort.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting the pod") err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), pod.Name, *metav1.NewDeleteOptions(0)) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotBestEffort.Name, usedResources) framework.ExpectNoError(err) }) /* Release: v1.16 Testname: ResourceQuota, update and delete Description: Create a ResourceQuota for CPU and Memory quota limits. Creation MUST be successful. When ResourceQuota is updated to modify CPU and Memory quota limits, update MUST succeed with updated values for CPU and Memory limits. When ResourceQuota is deleted, it MUST not be available in the namespace. */ framework.ConformanceIt("should be able to update and delete ResourceQuota.", func() { client := f.ClientSet ns := f.Namespace.Name ginkgo.By("Creating a ResourceQuota") quotaName := "test-quota" resourceQuota := &v1.ResourceQuota{ Spec: v1.ResourceQuotaSpec{ Hard: v1.ResourceList{}, }, } resourceQuota.ObjectMeta.Name = quotaName resourceQuota.Spec.Hard[v1.ResourceCPU] = resource.MustParse("1") resourceQuota.Spec.Hard[v1.ResourceMemory] = resource.MustParse("500Mi") _, err := createResourceQuota(client, ns, resourceQuota) framework.ExpectNoError(err) ginkgo.By("Getting a ResourceQuota") resourceQuotaResult, err := client.CoreV1().ResourceQuotas(ns).Get(context.TODO(), quotaName, metav1.GetOptions{}) framework.ExpectNoError(err) framework.ExpectEqual(resourceQuotaResult.Spec.Hard[v1.ResourceCPU], resource.MustParse("1")) framework.ExpectEqual(resourceQuotaResult.Spec.Hard[v1.ResourceMemory], resource.MustParse("500Mi")) ginkgo.By("Updating a ResourceQuota") resourceQuota.Spec.Hard[v1.ResourceCPU] = resource.MustParse("2") resourceQuota.Spec.Hard[v1.ResourceMemory] = resource.MustParse("1Gi") resourceQuotaResult, err = client.CoreV1().ResourceQuotas(ns).Update(context.TODO(), resourceQuota, metav1.UpdateOptions{}) framework.ExpectNoError(err) framework.ExpectEqual(resourceQuotaResult.Spec.Hard[v1.ResourceCPU], resource.MustParse("2")) framework.ExpectEqual(resourceQuotaResult.Spec.Hard[v1.ResourceMemory], resource.MustParse("1Gi")) ginkgo.By("Verifying a ResourceQuota was modified") resourceQuotaResult, err = client.CoreV1().ResourceQuotas(ns).Get(context.TODO(), quotaName, metav1.GetOptions{}) framework.ExpectNoError(err) framework.ExpectEqual(resourceQuotaResult.Spec.Hard[v1.ResourceCPU], resource.MustParse("2")) framework.ExpectEqual(resourceQuotaResult.Spec.Hard[v1.ResourceMemory], resource.MustParse("1Gi")) ginkgo.By("Deleting a ResourceQuota") err = deleteResourceQuota(client, ns, quotaName) framework.ExpectNoError(err) ginkgo.By("Verifying the deleted ResourceQuota") _, err = client.CoreV1().ResourceQuotas(ns).Get(context.TODO(), quotaName, metav1.GetOptions{}) framework.ExpectEqual(apierrors.IsNotFound(err), true) }) }) var _ = SIGDescribe("ResourceQuota [Feature:ScopeSelectors]", func() { f := framework.NewDefaultFramework("scope-selectors") ginkgo.It("should verify ResourceQuota with best effort scope using scope-selectors.", func() { ginkgo.By("Creating a ResourceQuota with best effort scope") resourceQuotaBestEffort, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScopeSelector("quota-besteffort", v1.ResourceQuotaScopeBestEffort)) framework.ExpectNoError(err) ginkgo.By("Ensuring ResourceQuota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaBestEffort.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a ResourceQuota with not best effort scope") resourceQuotaNotBestEffort, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScopeSelector("quota-not-besteffort", v1.ResourceQuotaScopeNotBestEffort)) framework.ExpectNoError(err) ginkgo.By("Ensuring ResourceQuota status is calculated") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotBestEffort.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a best-effort pod") pod := newTestPodForQuota(f, podName, v1.ResourceList{}, v1.ResourceList{}) pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with best effort scope captures the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaBestEffort.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with not best effort ignored the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotBestEffort.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting the pod") err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), pod.Name, *metav1.NewDeleteOptions(0)) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaBestEffort.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a not best-effort pod") requests := v1.ResourceList{} requests[v1.ResourceCPU] = resource.MustParse("500m") requests[v1.ResourceMemory] = resource.MustParse("200Mi") limits := v1.ResourceList{} limits[v1.ResourceCPU] = resource.MustParse("1") limits[v1.ResourceMemory] = resource.MustParse("400Mi") pod = newTestPodForQuota(f, "burstable-pod", requests, limits) pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with not best effort scope captures the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotBestEffort.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with best effort scope ignored the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaBestEffort.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting the pod") err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), pod.Name, *metav1.NewDeleteOptions(0)) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotBestEffort.Name, usedResources) framework.ExpectNoError(err) }) ginkgo.It("should verify ResourceQuota with terminating scopes through scope selectors.", func() { ginkgo.By("Creating a ResourceQuota with terminating scope") quotaTerminatingName := "quota-terminating" resourceQuotaTerminating, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScopeSelector(quotaTerminatingName, v1.ResourceQuotaScopeTerminating)) framework.ExpectNoError(err) ginkgo.By("Ensuring ResourceQuota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaTerminating.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a ResourceQuota with not terminating scope") quotaNotTerminatingName := "quota-not-terminating" resourceQuotaNotTerminating, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScopeSelector(quotaNotTerminatingName, v1.ResourceQuotaScopeNotTerminating)) framework.ExpectNoError(err) ginkgo.By("Ensuring ResourceQuota status is calculated") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotTerminating.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a long running pod") podName := "test-pod" requests := v1.ResourceList{} requests[v1.ResourceCPU] = resource.MustParse("500m") requests[v1.ResourceMemory] = resource.MustParse("200Mi") limits := v1.ResourceList{} limits[v1.ResourceCPU] = resource.MustParse("1") limits[v1.ResourceMemory] = resource.MustParse("400Mi") pod := newTestPodForQuota(f, podName, requests, limits) _, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with not terminating scope captures the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("1") usedResources[v1.ResourceRequestsCPU] = requests[v1.ResourceCPU] usedResources[v1.ResourceRequestsMemory] = requests[v1.ResourceMemory] usedResources[v1.ResourceLimitsCPU] = limits[v1.ResourceCPU] usedResources[v1.ResourceLimitsMemory] = limits[v1.ResourceMemory] err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotTerminating.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with terminating scope ignored the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") usedResources[v1.ResourceRequestsCPU] = resource.MustParse("0") usedResources[v1.ResourceRequestsMemory] = resource.MustParse("0") usedResources[v1.ResourceLimitsCPU] = resource.MustParse("0") usedResources[v1.ResourceLimitsMemory] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaTerminating.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting the pod") err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), podName, *metav1.NewDeleteOptions(0)) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") usedResources[v1.ResourceRequestsCPU] = resource.MustParse("0") usedResources[v1.ResourceRequestsMemory] = resource.MustParse("0") usedResources[v1.ResourceLimitsCPU] = resource.MustParse("0") usedResources[v1.ResourceLimitsMemory] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotTerminating.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a terminating pod") podName = "terminating-pod" pod = newTestPodForQuota(f, podName, requests, limits) activeDeadlineSeconds := int64(3600) pod.Spec.ActiveDeadlineSeconds = &activeDeadlineSeconds _, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with terminating scope captures the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("1") usedResources[v1.ResourceRequestsCPU] = requests[v1.ResourceCPU] usedResources[v1.ResourceRequestsMemory] = requests[v1.ResourceMemory] usedResources[v1.ResourceLimitsCPU] = limits[v1.ResourceCPU] usedResources[v1.ResourceLimitsMemory] = limits[v1.ResourceMemory] err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaTerminating.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with not terminating scope ignored the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") usedResources[v1.ResourceRequestsCPU] = resource.MustParse("0") usedResources[v1.ResourceRequestsMemory] = resource.MustParse("0") usedResources[v1.ResourceLimitsCPU] = resource.MustParse("0") usedResources[v1.ResourceLimitsMemory] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaNotTerminating.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting the pod") err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), podName, *metav1.NewDeleteOptions(0)) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") usedResources[v1.ResourceRequestsCPU] = resource.MustParse("0") usedResources[v1.ResourceRequestsMemory] = resource.MustParse("0") usedResources[v1.ResourceLimitsCPU] = resource.MustParse("0") usedResources[v1.ResourceLimitsMemory] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaTerminating.Name, usedResources) framework.ExpectNoError(err) }) }) var _ = SIGDescribe("ResourceQuota [Feature:PodPriority]", func() { f := framework.NewDefaultFramework("resourcequota-priorityclass") ginkgo.It("should verify ResourceQuota's priority class scope (quota set to pod count: 1) against a pod with same priority class.", func() { _, err := f.ClientSet.SchedulingV1().PriorityClasses().Create(context.TODO(), &schedulingv1.PriorityClass{ObjectMeta: metav1.ObjectMeta{Name: "pclass1"}, Value: int32(1000)}, metav1.CreateOptions{}) framework.ExpectEqual(err == nil || apierrors.IsAlreadyExists(err), true) hard := v1.ResourceList{} hard[v1.ResourcePods] = resource.MustParse("1") ginkgo.By("Creating a ResourceQuota with priority class scope") resourceQuotaPriorityClass, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScopeForPriorityClass("quota-priorityclass", hard, v1.ScopeSelectorOpIn, []string{"pclass1"})) framework.ExpectNoError(err) ginkgo.By("Ensuring ResourceQuota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a pod with priority class") podName := "testpod-pclass1" pod := newTestPodForQuotaWithPriority(f, podName, v1.ResourceList{}, v1.ResourceList{}, "pclass1") pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with priority class scope captures the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting the pod") err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), pod.Name, *metav1.NewDeleteOptions(0)) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) }) ginkgo.It("should verify ResourceQuota's priority class scope (quota set to pod count: 1) against 2 pods with same priority class.", func() { _, err := f.ClientSet.SchedulingV1().PriorityClasses().Create(context.TODO(), &schedulingv1.PriorityClass{ObjectMeta: metav1.ObjectMeta{Name: "pclass2"}, Value: int32(1000)}, metav1.CreateOptions{}) framework.ExpectEqual(err == nil || apierrors.IsAlreadyExists(err), true) hard := v1.ResourceList{} hard[v1.ResourcePods] = resource.MustParse("1") ginkgo.By("Creating a ResourceQuota with priority class scope") resourceQuotaPriorityClass, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScopeForPriorityClass("quota-priorityclass", hard, v1.ScopeSelectorOpIn, []string{"pclass2"})) framework.ExpectNoError(err) ginkgo.By("Ensuring ResourceQuota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating first pod with priority class should pass") podName := "testpod-pclass2-1" pod := newTestPodForQuotaWithPriority(f, podName, v1.ResourceList{}, v1.ResourceList{}, "pclass2") pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with priority class scope captures the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating 2nd pod with priority class should fail") podName2 := "testpod-pclass2-2" pod2 := newTestPodForQuotaWithPriority(f, podName2, v1.ResourceList{}, v1.ResourceList{}, "pclass2") _, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod2, metav1.CreateOptions{}) framework.ExpectError(err) ginkgo.By("Deleting first pod") err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), pod.Name, *metav1.NewDeleteOptions(0)) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) }) ginkgo.It("should verify ResourceQuota's priority class scope (quota set to pod count: 1) against 2 pods with different priority class.", func() { _, err := f.ClientSet.SchedulingV1().PriorityClasses().Create(context.TODO(), &schedulingv1.PriorityClass{ObjectMeta: metav1.ObjectMeta{Name: "pclass3"}, Value: int32(1000)}, metav1.CreateOptions{}) framework.ExpectEqual(err == nil || apierrors.IsAlreadyExists(err), true) hard := v1.ResourceList{} hard[v1.ResourcePods] = resource.MustParse("1") ginkgo.By("Creating a ResourceQuota with priority class scope") resourceQuotaPriorityClass, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScopeForPriorityClass("quota-priorityclass", hard, v1.ScopeSelectorOpIn, []string{"pclass4"})) framework.ExpectNoError(err) ginkgo.By("Ensuring ResourceQuota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a pod with priority class with pclass3") podName := "testpod-pclass3-1" pod := newTestPodForQuotaWithPriority(f, podName, v1.ResourceList{}, v1.ResourceList{}, "pclass3") pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with priority class scope remains same") usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a 2nd pod with priority class pclass3") podName2 := "testpod-pclass2-2" pod2 := newTestPodForQuotaWithPriority(f, podName2, v1.ResourceList{}, v1.ResourceList{}, "pclass3") pod2, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod2, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with priority class scope remains same") usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting both pods") err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), pod.Name, *metav1.NewDeleteOptions(0)) framework.ExpectNoError(err) err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), pod2.Name, *metav1.NewDeleteOptions(0)) framework.ExpectNoError(err) }) ginkgo.It("should verify ResourceQuota's multiple priority class scope (quota set to pod count: 2) against 2 pods with same priority classes.", func() { _, err := f.ClientSet.SchedulingV1().PriorityClasses().Create(context.TODO(), &schedulingv1.PriorityClass{ObjectMeta: metav1.ObjectMeta{Name: "pclass5"}, Value: int32(1000)}, metav1.CreateOptions{}) framework.ExpectEqual(err == nil || apierrors.IsAlreadyExists(err), true) _, err = f.ClientSet.SchedulingV1().PriorityClasses().Create(context.TODO(), &schedulingv1.PriorityClass{ObjectMeta: metav1.ObjectMeta{Name: "pclass6"}, Value: int32(1000)}, metav1.CreateOptions{}) framework.ExpectEqual(err == nil || apierrors.IsAlreadyExists(err), true) hard := v1.ResourceList{} hard[v1.ResourcePods] = resource.MustParse("2") ginkgo.By("Creating a ResourceQuota with priority class scope") resourceQuotaPriorityClass, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScopeForPriorityClass("quota-priorityclass", hard, v1.ScopeSelectorOpIn, []string{"pclass5", "pclass6"})) framework.ExpectNoError(err) ginkgo.By("Ensuring ResourceQuota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a pod with priority class pclass5") podName := "testpod-pclass5" pod := newTestPodForQuotaWithPriority(f, podName, v1.ResourceList{}, v1.ResourceList{}, "pclass5") pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with priority class is updated with the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating 2nd pod with priority class pclass6") podName2 := "testpod-pclass6" pod2 := newTestPodForQuotaWithPriority(f, podName2, v1.ResourceList{}, v1.ResourceList{}, "pclass6") pod2, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod2, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with priority class scope is updated with the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("2") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting both pods") err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), pod.Name, *metav1.NewDeleteOptions(0)) framework.ExpectNoError(err) err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), pod2.Name, *metav1.NewDeleteOptions(0)) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) }) ginkgo.It("should verify ResourceQuota's priority class scope (quota set to pod count: 1) against a pod with different priority class (ScopeSelectorOpNotIn).", func() { _, err := f.ClientSet.SchedulingV1().PriorityClasses().Create(context.TODO(), &schedulingv1.PriorityClass{ObjectMeta: metav1.ObjectMeta{Name: "pclass7"}, Value: int32(1000)}, metav1.CreateOptions{}) framework.ExpectEqual(err == nil || apierrors.IsAlreadyExists(err), true) hard := v1.ResourceList{} hard[v1.ResourcePods] = resource.MustParse("1") ginkgo.By("Creating a ResourceQuota with priority class scope") resourceQuotaPriorityClass, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScopeForPriorityClass("quota-priorityclass", hard, v1.ScopeSelectorOpNotIn, []string{"pclass7"})) framework.ExpectNoError(err) ginkgo.By("Ensuring ResourceQuota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a pod with priority class pclass7") podName := "testpod-pclass7" pod := newTestPodForQuotaWithPriority(f, podName, v1.ResourceList{}, v1.ResourceList{}, "pclass7") pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with priority class is not used") usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting the pod") err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), pod.Name, *metav1.NewDeleteOptions(0)) framework.ExpectNoError(err) }) ginkgo.It("should verify ResourceQuota's priority class scope (quota set to pod count: 1) against a pod with different priority class (ScopeSelectorOpExists).", func() { _, err := f.ClientSet.SchedulingV1().PriorityClasses().Create(context.TODO(), &schedulingv1.PriorityClass{ObjectMeta: metav1.ObjectMeta{Name: "pclass8"}, Value: int32(1000)}, metav1.CreateOptions{}) framework.ExpectEqual(err == nil || apierrors.IsAlreadyExists(err), true) hard := v1.ResourceList{} hard[v1.ResourcePods] = resource.MustParse("1") ginkgo.By("Creating a ResourceQuota with priority class scope") resourceQuotaPriorityClass, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScopeForPriorityClass("quota-priorityclass", hard, v1.ScopeSelectorOpExists, []string{})) framework.ExpectNoError(err) ginkgo.By("Ensuring ResourceQuota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a pod with priority class pclass8") podName := "testpod-pclass8" pod := newTestPodForQuotaWithPriority(f, podName, v1.ResourceList{}, v1.ResourceList{}, "pclass8") pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with priority class is updated with the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("1") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting the pod") err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), pod.Name, *metav1.NewDeleteOptions(0)) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) }) ginkgo.It("should verify ResourceQuota's priority class scope (cpu, memory quota set) against a pod with same priority class.", func() { _, err := f.ClientSet.SchedulingV1().PriorityClasses().Create(context.TODO(), &schedulingv1.PriorityClass{ObjectMeta: metav1.ObjectMeta{Name: "pclass9"}, Value: int32(1000)}, metav1.CreateOptions{}) framework.ExpectEqual(err == nil || apierrors.IsAlreadyExists(err), true) hard := v1.ResourceList{} hard[v1.ResourcePods] = resource.MustParse("1") hard[v1.ResourceRequestsCPU] = resource.MustParse("1") hard[v1.ResourceRequestsMemory] = resource.MustParse("1Gi") hard[v1.ResourceLimitsCPU] = resource.MustParse("3") hard[v1.ResourceLimitsMemory] = resource.MustParse("3Gi") ginkgo.By("Creating a ResourceQuota with priority class scope") resourceQuotaPriorityClass, err := createResourceQuota(f.ClientSet, f.Namespace.Name, newTestResourceQuotaWithScopeForPriorityClass("quota-priorityclass", hard, v1.ScopeSelectorOpIn, []string{"pclass9"})) framework.ExpectNoError(err) ginkgo.By("Ensuring ResourceQuota status is calculated") usedResources := v1.ResourceList{} usedResources[v1.ResourcePods] = resource.MustParse("0") usedResources[v1.ResourceRequestsCPU] = resource.MustParse("0") usedResources[v1.ResourceRequestsMemory] = resource.MustParse("0Gi") usedResources[v1.ResourceLimitsCPU] = resource.MustParse("0") usedResources[v1.ResourceLimitsMemory] = resource.MustParse("0Gi") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Creating a pod with priority class") podName := "testpod-pclass9" request := v1.ResourceList{} request[v1.ResourceCPU] = resource.MustParse("1") request[v1.ResourceMemory] = resource.MustParse("1Gi") limit := v1.ResourceList{} limit[v1.ResourceCPU] = resource.MustParse("2") limit[v1.ResourceMemory] = resource.MustParse("2Gi") pod := newTestPodForQuotaWithPriority(f, podName, request, limit, "pclass9") pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota with priority class scope captures the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("1") usedResources[v1.ResourceRequestsCPU] = resource.MustParse("1") usedResources[v1.ResourceRequestsMemory] = resource.MustParse("1Gi") usedResources[v1.ResourceLimitsCPU] = resource.MustParse("2") usedResources[v1.ResourceLimitsMemory] = resource.MustParse("2Gi") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) ginkgo.By("Deleting the pod") err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), pod.Name, *metav1.NewDeleteOptions(0)) framework.ExpectNoError(err) ginkgo.By("Ensuring resource quota status released the pod usage") usedResources[v1.ResourcePods] = resource.MustParse("0") usedResources[v1.ResourceRequestsCPU] = resource.MustParse("0") usedResources[v1.ResourceRequestsMemory] = resource.MustParse("0Gi") usedResources[v1.ResourceLimitsCPU] = resource.MustParse("0") usedResources[v1.ResourceLimitsMemory] = resource.MustParse("0Gi") err = waitForResourceQuota(f.ClientSet, f.Namespace.Name, resourceQuotaPriorityClass.Name, usedResources) framework.ExpectNoError(err) }) }) // newTestResourceQuotaWithScopeSelector returns a quota that enforces default constraints for testing with scopeSelectors func newTestResourceQuotaWithScopeSelector(name string, scope v1.ResourceQuotaScope) *v1.ResourceQuota { hard := v1.ResourceList{} hard[v1.ResourcePods] = resource.MustParse("5") switch scope { case v1.ResourceQuotaScopeTerminating, v1.ResourceQuotaScopeNotTerminating: hard[v1.ResourceRequestsCPU] = resource.MustParse("1") hard[v1.ResourceRequestsMemory] = resource.MustParse("500Mi") hard[v1.ResourceLimitsCPU] = resource.MustParse("2") hard[v1.ResourceLimitsMemory] = resource.MustParse("1Gi") } return &v1.ResourceQuota{ ObjectMeta: metav1.ObjectMeta{Name: name}, Spec: v1.ResourceQuotaSpec{Hard: hard, ScopeSelector: &v1.ScopeSelector{ MatchExpressions: []v1.ScopedResourceSelectorRequirement{ { ScopeName: scope, Operator: v1.ScopeSelectorOpExists}, }, }, }, } } // newTestResourceQuotaWithScope returns a quota that enforces default constraints for testing with scopes func newTestResourceQuotaWithScope(name string, scope v1.ResourceQuotaScope) *v1.ResourceQuota { hard := v1.ResourceList{} hard[v1.ResourcePods] = resource.MustParse("5") switch scope { case v1.ResourceQuotaScopeTerminating, v1.ResourceQuotaScopeNotTerminating: hard[v1.ResourceRequestsCPU] = resource.MustParse("1") hard[v1.ResourceRequestsMemory] = resource.MustParse("500Mi") hard[v1.ResourceLimitsCPU] = resource.MustParse("2") hard[v1.ResourceLimitsMemory] = resource.MustParse("1Gi") } return &v1.ResourceQuota{ ObjectMeta: metav1.ObjectMeta{Name: name}, Spec: v1.ResourceQuotaSpec{Hard: hard, Scopes: []v1.ResourceQuotaScope{scope}}, } } // newTestResourceQuotaWithScopeForPriorityClass returns a quota // that enforces default constraints for testing with ResourceQuotaScopePriorityClass scope func newTestResourceQuotaWithScopeForPriorityClass(name string, hard v1.ResourceList, op v1.ScopeSelectorOperator, values []string) *v1.ResourceQuota { return &v1.ResourceQuota{ ObjectMeta: metav1.ObjectMeta{Name: name}, Spec: v1.ResourceQuotaSpec{Hard: hard, ScopeSelector: &v1.ScopeSelector{ MatchExpressions: []v1.ScopedResourceSelectorRequirement{ { ScopeName: v1.ResourceQuotaScopePriorityClass, Operator: op, Values: values, }, }, }, }, } } // newTestResourceQuota returns a quota that enforces default constraints for testing func newTestResourceQuota(name string) *v1.ResourceQuota { hard := v1.ResourceList{} hard[v1.ResourcePods] = resource.MustParse("5") hard[v1.ResourceServices] = resource.MustParse("10") hard[v1.ResourceServicesNodePorts] = resource.MustParse("1") hard[v1.ResourceServicesLoadBalancers] = resource.MustParse("1") hard[v1.ResourceReplicationControllers] = resource.MustParse("10") hard[v1.ResourceQuotas] = resource.MustParse("1") hard[v1.ResourceCPU] = resource.MustParse("1") hard[v1.ResourceMemory] = resource.MustParse("500Mi") hard[v1.ResourceConfigMaps] = resource.MustParse("2") hard[v1.ResourceSecrets] = resource.MustParse("10") hard[v1.ResourcePersistentVolumeClaims] = resource.MustParse("10") hard[v1.ResourceRequestsStorage] = resource.MustParse("10Gi") hard[v1.ResourceEphemeralStorage] = resource.MustParse("50Gi") hard[core.V1ResourceByStorageClass(classGold, v1.ResourcePersistentVolumeClaims)] = resource.MustParse("10") hard[core.V1ResourceByStorageClass(classGold, v1.ResourceRequestsStorage)] = resource.MustParse("10Gi") // test quota on discovered resource type hard[v1.ResourceName("count/replicasets.apps")] = resource.MustParse("5") // test quota on extended resource hard[v1.ResourceName(v1.DefaultResourceRequestsPrefix+extendedResourceName)] = resource.MustParse("3") return &v1.ResourceQuota{ ObjectMeta: metav1.ObjectMeta{Name: name}, Spec: v1.ResourceQuotaSpec{Hard: hard}, } } // newTestPodForQuota returns a pod that has the specified requests and limits func newTestPodForQuota(f *framework.Framework, name string, requests v1.ResourceList, limits v1.ResourceList) *v1.Pod { return &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, Spec: v1.PodSpec{ // prevent disruption to other test workloads in parallel test runs by ensuring the quota // test pods don't get scheduled onto a node NodeSelector: map[string]string{ "x-test.k8s.io/unsatisfiable": "not-schedulable", }, Containers: []v1.Container{ { Name: "pause", Image: imageutils.GetPauseImageName(), Resources: v1.ResourceRequirements{ Requests: requests, Limits: limits, }, }, }, }, } } // newTestPodForQuotaWithPriority returns a pod that has the specified requests, limits and priority class func newTestPodForQuotaWithPriority(f *framework.Framework, name string, requests v1.ResourceList, limits v1.ResourceList, pclass string) *v1.Pod { return &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, Spec: v1.PodSpec{ // prevent disruption to other test workloads in parallel test runs by ensuring the quota // test pods don't get scheduled onto a node NodeSelector: map[string]string{ "x-test.k8s.io/unsatisfiable": "not-schedulable", }, Containers: []v1.Container{ { Name: "pause", Image: imageutils.GetPauseImageName(), Resources: v1.ResourceRequirements{ Requests: requests, Limits: limits, }, }, }, PriorityClassName: pclass, }, } } // newTestPersistentVolumeClaimForQuota returns a simple persistent volume claim func newTestPersistentVolumeClaimForQuota(name string) *v1.PersistentVolumeClaim { return &v1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, Spec: v1.PersistentVolumeClaimSpec{ AccessModes: []v1.PersistentVolumeAccessMode{ v1.ReadWriteOnce, v1.ReadOnlyMany, v1.ReadWriteMany, }, Resources: v1.ResourceRequirements{ Requests: v1.ResourceList{ v1.ResourceName(v1.ResourceStorage): resource.MustParse("1Gi"), }, }, }, } } // newTestReplicationControllerForQuota returns a simple replication controller func newTestReplicationControllerForQuota(name, image string, replicas int32) *v1.ReplicationController { return &v1.ReplicationController{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, Spec: v1.ReplicationControllerSpec{ Replicas: func(i int32) *int32 { return &i }(replicas), Selector: map[string]string{ "name": name, }, Template: &v1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{"name": name}, }, Spec: v1.PodSpec{ Containers: []v1.Container{ { Name: name, Image: image, }, }, }, }, }, } } // newTestReplicaSetForQuota returns a simple replica set func newTestReplicaSetForQuota(name, image string, replicas int32) *appsv1.ReplicaSet { zero := int64(0) return &appsv1.ReplicaSet{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, Spec: appsv1.ReplicaSetSpec{ Replicas: &replicas, Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"name": name}}, Template: v1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{"name": name}, }, Spec: v1.PodSpec{ TerminationGracePeriodSeconds: &zero, Containers: []v1.Container{ { Name: name, Image: image, }, }, }, }, }, } } // newTestServiceForQuota returns a simple service func newTestServiceForQuota(name string, serviceType v1.ServiceType) *v1.Service { return &v1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, Spec: v1.ServiceSpec{ Type: serviceType, Ports: []v1.ServicePort{{ Port: 80, TargetPort: intstr.FromInt(80), }}, }, } } func newTestConfigMapForQuota(name string) *v1.ConfigMap { return &v1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, Data: map[string]string{ "a": "b", }, } } func newTestSecretForQuota(name string) *v1.Secret { return &v1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, Data: map[string][]byte{ "data-1": []byte("value-1\n"), "data-2": []byte("value-2\n"), "data-3": []byte("value-3\n"), }, } } // createResourceQuota in the specified namespace func createResourceQuota(c clientset.Interface, namespace string, resourceQuota *v1.ResourceQuota) (*v1.ResourceQuota, error) { return c.CoreV1().ResourceQuotas(namespace).Create(context.TODO(), resourceQuota, metav1.CreateOptions{}) } // deleteResourceQuota with the specified name func deleteResourceQuota(c clientset.Interface, namespace, name string) error { return c.CoreV1().ResourceQuotas(namespace).Delete(context.TODO(), name, metav1.DeleteOptions{}) } // countResourceQuota counts the number of ResourceQuota in the specified namespace // On contended servers the service account controller can slow down, leading to the count changing during a run. // Wait up to 5s for the count to stabilize, assuming that updates come at a consistent rate, and are not held indefinitely. func countResourceQuota(c clientset.Interface, namespace string) (int, error) { found, unchanged := 0, 0 return found, wait.Poll(1*time.Second, 30*time.Second, func() (bool, error) { resourceQuotas, err := c.CoreV1().ResourceQuotas(namespace).List(context.TODO(), metav1.ListOptions{}) framework.ExpectNoError(err) if len(resourceQuotas.Items) == found { // loop until the number of resource quotas has stabilized for 5 seconds unchanged++ return unchanged > 4, nil } unchanged = 0 found = len(resourceQuotas.Items) return false, nil }) } // wait for resource quota status to show the expected used resources value func waitForResourceQuota(c clientset.Interface, ns, quotaName string, used v1.ResourceList) error { return wait.Poll(framework.Poll, resourceQuotaTimeout, func() (bool, error) { resourceQuota, err := c.CoreV1().ResourceQuotas(ns).Get(context.TODO(), quotaName, metav1.GetOptions{}) if err != nil { return false, err } // used may not yet be calculated if resourceQuota.Status.Used == nil { return false, nil } // verify that the quota shows the expected used resource values for k, v := range used { if actualValue, found := resourceQuota.Status.Used[k]; !found || (actualValue.Cmp(v) != 0) { framework.Logf("resource %s, expected %s, actual %s", k, v.String(), actualValue.String()) return false, nil } } return true, nil }) } // updateResourceQuotaUntilUsageAppears updates the resource quota object until the usage is populated // for the specific resource name. func updateResourceQuotaUntilUsageAppears(c clientset.Interface, ns, quotaName string, resourceName v1.ResourceName) error { return wait.Poll(framework.Poll, 1*time.Minute, func() (bool, error) { resourceQuota, err := c.CoreV1().ResourceQuotas(ns).Get(context.TODO(), quotaName, metav1.GetOptions{}) if err != nil { return false, err } // verify that the quota shows the expected used resource values _, ok := resourceQuota.Status.Used[resourceName] if ok { return true, nil } current := resourceQuota.Spec.Hard[resourceName] current.Add(resource.MustParse("1")) resourceQuota.Spec.Hard[resourceName] = current _, err = c.CoreV1().ResourceQuotas(ns).Update(context.TODO(), resourceQuota, metav1.UpdateOptions{}) // ignoring conflicts since someone else may already updated it. if apierrors.IsConflict(err) { return false, nil } return false, err }) }
{ "content_hash": "16b3e42a3a3635a8ca07a4a0547603a7", "timestamp": "", "source": "github", "line_count": 1729, "max_line_length": 338, "avg_line_length": 50.82706766917293, "alnum_prop": 0.7718365953573054, "repo_name": "tcnghia/kubernetes", "id": "5514ab3f4dffdcd0679d2f376b4893d795940f6a", "size": "88449", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/e2e/apimachinery/resource_quota.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2840" }, { "name": "Go", "bytes": "43146121" }, { "name": "HTML", "bytes": "1199467" }, { "name": "Makefile", "bytes": "75248" }, { "name": "Python", "bytes": "2872917" }, { "name": "Ruby", "bytes": "1780" }, { "name": "Shell", "bytes": "1452321" }, { "name": "sed", "bytes": "11576" } ], "symlink_target": "" }
from openpyxl import load_workbook class Spreadsheet(): '''Creates an Excel spreadsheet containing information built in algo3''' def __init__(self, filename, startdate, tbwschedule, folder): self.folder = folder self.filename = filename self.createdoc() self.writeshifts(tbwschedule) self.writeoffdays() self.writedate(startdate) def createdoc(self): self.wb = load_workbook(self.filename) self.sh = self.wb.get_sheet_by_name('Sheet1') def writeshifts(self, tbwschedule): '''Writes information from Week() to Excel sheet''' for r in tbwschedule: for values in tbwschedule[r]: # Writes Shift start time self.sh.cell(row=r, column=values[0]).value = str(values[1][0]) # Writes shift end time self.sh.cell(row=r, column=values[0]+1).value = str( values[1][1]) # Write in hours worked self.sh.cell(row=r, column=values[0]+2).value = values[1][2] def writeoffdays(self): ''' Adds in OFF days''' for j in range(8, 50): for i in range(4, 29, 3): if self.sh.cell(row=j, column=i).value in ('X', '#'): self.sh.cell(row=j, column=i).value = 'OFF' self.sh.cell(row=j, column=i + 1).value = '' self.sh.cell(row=j, column=i + 2).value = 0 def writedate(self, date): ''' Writes the beginning of week date to Excel''' self.sh.cell(row=4, column=4).value = date self.wb.save(self.folder + '/updated_sched3.xlsx') if __name__ == '__main__': s = Spreadsheet()
{ "content_hash": "fb5b551ca6423a16917b27d928f14ed1", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 79, "avg_line_length": 37.34782608695652, "alnum_prop": 0.5529685681024447, "repo_name": "KCorpse/GSM", "id": "d4ea02c65b21f03fe5f417d195ccc5e3e46b7417", "size": "1718", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "buildoutput.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "17395" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <Configuration> <Appenders> <Console name="STDOUT" target="SYSTEM_OUT"> <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n" /> </Console> </Appenders> <Loggers> <Logger name="com.lrother.accs" level="debug"/> <Root level="error"> <AppenderRef ref="STDOUT" /> </Root> </Loggers> </Configuration>
{ "content_hash": "c0f67c395b5e2e431279d26f68c6dfaf", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 64, "avg_line_length": 25.714285714285715, "alnum_prop": 0.6194444444444445, "repo_name": "lrother/account-service", "id": "465cb96fb7587705f316d208285833a14f931c54", "size": "360", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/resources/log4j2.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "26261" } ], "symlink_target": "" }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Reflection; using Autofac.Extras.Common.Reflection; namespace x.UnitTest { [TestClass] public class UnitTest1 { [TestMethod] public void enumTest() { String enumName = Charter.A.ToString(); Assert.AreEqual("A", enumName); int enumValue = Charter.A.GetHashCode(); Assert.AreEqual(100, enumValue); } } public enum Charter { A = 100, B = 200 } }
{ "content_hash": "d9c2a3356e5d9cbd8864b9aa2fe63b08", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 52, "avg_line_length": 20.37037037037037, "alnum_prop": 0.5854545454545454, "repo_name": "Ju2ender/CSharp-Exercise", "id": "295a0354bb8decd29624e83515ec209075e28313", "size": "552", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "x/test/x.UnitTest/UnitTest1.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "129122" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginTop="2dp" android:paddingStart="@dimen/directions_left_padding" android:paddingEnd="@dimen/directions_right_padding"> <ImageView android:id="@+id/directions_segmentmobility" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_directions_walk_light_blue_a700_24dp" android:contentDescription="@string/img_description"/> <TextView android:id="@+id/directions_description" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="bottom" android:text="@string/directions_direction" style="@style/AppTheme.BlackText" android:layout_marginStart="2dp" android:layout_marginEnd="8dp" android:layout_weight="1" /> <TextView android:id="@+id/directions_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom" android:text="@string/directions_duration" style="@style/AppTheme.BlackText"/> </LinearLayout>
{ "content_hash": "17995fa2f99e9f745f26283893face12", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 72, "avg_line_length": 41.515151515151516, "alnum_prop": 0.6766423357664234, "repo_name": "GIlyass/TouristScheduler", "id": "41f0638f486fe71f6bf42700a91d143e42a38eb7", "size": "1370", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AndroidApp/TEScheduler/TEScheduler/app/src/main/res/layout/element_directions_routesegment.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "280433" } ], "symlink_target": "" }
/* * Created on 23-Sep-2003 * * To change the template for this generated file go to * Window>Preferences>Java>Code Generation>Code and Comments */ package com.ivstuart.tmud.command.info; import com.ivstuart.tmud.command.BaseCommand; import com.ivstuart.tmud.command.CommandProvider; import com.ivstuart.tmud.command.Social; import com.ivstuart.tmud.state.Mob; /** * @author stuarti * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public class CommandList extends BaseCommand { @Override public void execute(Mob mob, String input) { for (Object command : CommandProvider.getCommands()) { if (command instanceof Social) { Social social = (Social) command; mob.out(social.getCmd()); } else { mob.out(command.getClass().getSimpleName()); } } } }
{ "content_hash": "9b212db143a2f894c7a6ea35f9452b5b", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 71, "avg_line_length": 25.08108108108108, "alnum_prop": 0.6810344827586207, "repo_name": "ivstuart/tea-mud", "id": "fc3582134a8f6d867e7f28f177d41f9bd225d5c9", "size": "1547", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/ivstuart/tmud/command/info/CommandList.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1515994" } ], "symlink_target": "" }
<resources> <string name="app_name">metrostore</string> <string name="app_title">Metrostore</string> <string name="action_settings">Settings</string> <string name="btn_start_name">Start</string> <string name="bitrate_placeholder">Tempo</string> <string name="default_bitrate">4</string> <string name="default_tempo">120</string> <string name="list_activity_btn">Songs</string> <string name="back_btn">Back</string> <string name="quoter_btn">1/4</string> <string name="eights_btn">1/8</string> <string name="sixteenths_btn">1/16</string> <string name="triplets_btn">1/3</string> </resources>
{ "content_hash": "3cea68867a9a039935f021559719c898", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 53, "avg_line_length": 40.25, "alnum_prop": 0.6754658385093167, "repo_name": "azee/metrostore", "id": "0ccc2459bbddc67345c22b7a32f4d8751010cc4b", "size": "644", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/values/strings.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "14635" } ], "symlink_target": "" }
package com.kata.businessrules; import org.junit.Before; import org.junit.Test; import com.kata.businessrules.payment.PaymentBehavior; import com.kata.businessrules.products.Product; import static org.mockito.Mockito.*; import java.util.Arrays; public class TestRuleEngineForPaymentBehaviors { private RuleEngine behaviors; private Product product; private PaymentBehavior firstBehaviorThatCanProcessProduct; private PaymentBehavior secondBehaviorThatCanProcessProduct; private PaymentBehavior behaviorThatCannotProcessProduct; private User customer; private void pay() { behaviors.pay(customer, product); } @Before public void setup() { product = ProductFixture.createArbitraryProduct(); firstBehaviorThatCanProcessProduct = PaymentProcessorFixture .thatCanProcess(product); secondBehaviorThatCanProcessProduct = PaymentProcessorFixture .thatCanProcess(product); behaviorThatCannotProcessProduct = PaymentProcessorFixture .thatCanNotProcess(product); customer = mock(User.class); behaviors = new RuleEngineForPaymentBehaviors( Arrays.asList(firstBehaviorThatCanProcessProduct, behaviorThatCannotProcessProduct, secondBehaviorThatCanProcessProduct)); } @Test public void pay_requestIsDispatchedToProperProcessor() { pay(); verify(firstBehaviorThatCanProcessProduct, times(1)).pay(customer, product); verify(secondBehaviorThatCanProcessProduct, times(1)).pay(customer, product); verify(behaviorThatCannotProcessProduct, never()).pay(customer, product); } @Test public void pay_productIsAddedToUsersListOfBoughtProducts() { pay(); verify(customer).purchase(product); } }
{ "content_hash": "dcd3185af368e143db1de31721a2a186", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 69, "avg_line_length": 29.140350877192983, "alnum_prop": 0.8019265502709211, "repo_name": "a-ostrovsky/business_rules_kata", "id": "8e2cd48ca96a3d289f174c001685b59b0543cc75", "size": "1661", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/kata/businessrules/TestRuleEngineForPaymentBehaviors.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "89539" } ], "symlink_target": "" }
 #include <aws/lightsail/model/GetOperationsForResourceResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::Lightsail::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; GetOperationsForResourceResult::GetOperationsForResourceResult() { } GetOperationsForResourceResult::GetOperationsForResourceResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } GetOperationsForResourceResult& GetOperationsForResourceResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("operations")) { Array<JsonView> operationsJsonList = jsonValue.GetArray("operations"); for(unsigned operationsIndex = 0; operationsIndex < operationsJsonList.GetLength(); ++operationsIndex) { m_operations.push_back(operationsJsonList[operationsIndex].AsObject()); } } if(jsonValue.ValueExists("nextPageToken")) { m_nextPageToken = jsonValue.GetString("nextPageToken"); } return *this; }
{ "content_hash": "d173f37e662b2b4bc3233eb41aab4fa9", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 128, "avg_line_length": 26.956521739130434, "alnum_prop": 0.771774193548387, "repo_name": "cedral/aws-sdk-cpp", "id": "15cabc7f753cf9191ce88e864df726f2dde29e36", "size": "1359", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "aws-cpp-sdk-lightsail/source/model/GetOperationsForResourceResult.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "294220" }, { "name": "C++", "bytes": "428637022" }, { "name": "CMake", "bytes": "862025" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "7904" }, { "name": "Java", "bytes": "352201" }, { "name": "Python", "bytes": "106761" }, { "name": "Shell", "bytes": "10891" } ], "symlink_target": "" }
namespace impala { class ArrayValueBuilder; class Compression; class DescriptorTbl; class Expr; class HdfsPartitionDescriptor; class MemPool; class SlotDescriptor; class Status; class TextConverter; class Tuple; class TupleDescriptor; class TPlanNode; class TScanRange; class Codec; /// Intermediate structure used for two pass parsing approach. In the first pass, /// the FieldLocation structs are filled out and contain where all the fields start and /// their lengths. In the second pass, the FieldLocation is used to write out the /// slots. We want to keep this struct as small as possible. struct FieldLocation { /// start of field. This is set to NULL for FieldLocations that are past the /// end of the row in the file. E.g. the file only had 3 cols but the table /// has 10. These then get written out as NULL slots. char* start; /// Encodes the length and whether or not this fields needs to be unescaped. /// If len < 0, then the field needs to be unescaped. int len; static const char* LLVM_CLASS_NAME; }; /// HdfsScanner is the superclass for different hdfs file format parsers. There is /// an instance of the scanner object created for each split, each driven by a different /// thread created by the scan node. The scan node calls: /// 1. Prepare /// 2. ProcessSplit /// 3. Close /// ProcessSplit does not return until the split is complete (or an error) occurred. /// The HdfsScanner works in tandem with the ScannerContext to interleave IO /// and parsing. // /// If a split is compressed, then a decompressor will be created, either during Prepare() /// or at the beginning of ProcessSplit(), and used for decompressing and reading the split. // /// For codegen, the implementation is split into two parts. /// 1. During the Prepare() phase of the ScanNode, the scanner subclass's static /// Codegen() function will be called to perform codegen for that scanner type /// for the specific tuple desc. This codegen'd function is cached in the HdfsScanNode. /// 2. During the GetNext() phase (where we create one Scanner for each scan range), /// the created scanner subclass can retrieve, from the scan node, the codegen'd /// function to use. /// This way, we only codegen once per scanner type, rather than once per scanner object. // /// This class also encapsulates row batch management. Subclasses should call CommitRows() /// after writing to the current row batch, which handles creating row batches, attaching /// resources (IO buffers and mem pools) to the current row batch, and passing row batches /// up to the scan node. Subclasses can also use GetMemory() to help with per-row memory /// management. class HdfsScanner : public Scanner { public: /// Assumed size of an OS file block. Used mostly when reading file format headers, etc. /// This probably ought to be a derived number from the environment. const static int FILE_BLOCK_SIZE = 4096; HdfsScanner(HdfsScanNode* scan_node, RuntimeState* state); virtual ~HdfsScanner(); /// One-time initialisation of state that is constant across scan ranges. virtual Status Prepare(ScannerContext* context); /// Process an entire split, reading bytes from the context's streams. Context is /// initialized with the split data (e.g. template tuple, partition descriptor, etc). /// This function should only return on error or end of scan range. virtual Status ProcessSplit() = 0; /// Release all resources the scanner has allocated. This is the last chance for the /// scanner to attach any resources to the ScannerContext object. virtual void Close(); /// Scanner subclasses must implement these static functions as well. Unfortunately, /// c++ does not allow static virtual functions. /// Issue the initial ranges for 'files'. HdfsFileDesc groups all the splits /// assigned to this scan node by file. This is called before any of the scanner /// subclasses are created to process splits in 'files'. /// The strategy on how to parse the scan ranges depends on the file format. /// - For simple text files, all the splits are simply issued to the io mgr and /// one split == one scan range. /// - For formats with a header, the metadata is first parsed, and then the ranges are /// issued to the io mgr. There is one scan range for the header and one range for /// each split. /// - For columnar formats, the header is parsed and only the relevant byte ranges /// should be issued to the io mgr. This is one range for the metadata and one /// range for each column, for each split. /// This function is how scanners can pick their strategy. /// void IssueInitialRanges(HdfsScanNode* scan_node, /// const std::vector<HdfsFileDesc*>& files); /// Codegen all functions for this scanner. The codegen'd function is specific to /// the scanner subclass but not specific to each scanner object. We don't want to /// codegen the functions for each scanner object. /// llvm::Function* Codegen(HdfsScanNode* scan_node); static const char* LLVM_CLASS_NAME; protected: /// The scan node that started this scanner HdfsScanNode* scan_node_; /// RuntimeState for error reporting RuntimeState* state_; /// Context for this scanner ScannerContext* context_; /// The first stream for context_ ScannerContext::Stream* stream_; /// Clones of the conjuncts ExprContexts in scan_node_->conjuncts_map(). Each scanner /// has its own ExprContexts so the conjuncts can be safely evaluated in parallel. HdfsScanNode::ConjunctsMap scanner_conjuncts_map_; // Convenience reference to scanner_conjuncts_map_[scan_node_->tuple_idx()] for scanners // that do not support nested types. const std::vector<ExprContext*>* scanner_conjunct_ctxs_; /// A template tuple is a partially-materialized tuple with only partition key slots set /// (or other default values, such as NULL for columns missing in a file). The other /// slots are set to NULL. The template tuple must be copied into output tuples before /// any of the other slots are materialized. /// /// Each tuple descriptor (i.e. scan_node_->tuple_desc() and any collection item tuple /// descs) has a template tuple, or NULL if there are no partition key or default slots. /// Template tuples are computed once for each file and valid for the duration of that /// file. They are owned by the HDFS scan node, although each scanner has its own /// template tuples. std::map<const TupleDescriptor*, Tuple*> template_tuple_map_; /// Convenience variable set to the top-level template tuple /// (i.e. template_tuple_map_[scan_node_->tuple_desc()]). Tuple* template_tuple_; /// Current tuple pointer into tuple_mem_. Tuple* tuple_; /// The current row batch being populated. Creating new row batches, attaching context /// resources, and handing off to the scan node is handled by this class in CommitRows(), /// but AttachPool() must be called by scanner subclasses to attach any memory allocated /// by that subclass. All row batches created by this class are transferred to the scan /// node (i.e., all batches are ultimately owned by the scan node). RowBatch* batch_; /// The tuple memory of batch_. uint8_t* tuple_mem_; /// number of errors in current file int num_errors_in_file_; /// Helper class for converting text to other types; boost::scoped_ptr<TextConverter> text_converter_; /// Number of null bytes in the top-level tuple. int32_t num_null_bytes_; /// Contains current parse status to minimize the number of Status objects returned. /// This significantly minimizes the cross compile dependencies for llvm since status /// objects inline a bunch of string functions. Also, status objects aren't extremely /// cheap to create and destroy. Status parse_status_; /// Decompressor class to use, if any. boost::scoped_ptr<Codec> decompressor_; /// The most recently used decompression type. THdfsCompression::type decompression_type_; /// Pool to allocate per data block memory. This should be used with the /// decompressor and any other per data block allocations. boost::scoped_ptr<MemPool> data_buffer_pool_; /// Time spent decompressing bytes. RuntimeProfile::Counter* decompress_timer_; /// Matching typedef for WriteAlignedTuples for codegen. Refer to comments for /// that function. typedef int (*WriteTuplesFn)(HdfsScanner*, MemPool*, TupleRow*, int, FieldLocation*, int, int, int, int); /// Jitted write tuples function pointer. Null if codegen is disabled. WriteTuplesFn write_tuples_fn_; /// Initializes write_tuples_fn_ to the jitted function if codegen is possible. /// - partition - partition descriptor for this scanner/scan range /// - type - type for this scanner /// - scanner_name - debug string name for this scanner (e.g. HdfsTextScanner) Status InitializeWriteTuplesFn(HdfsPartitionDescriptor* partition, THdfsFileFormat::type type, const std::string& scanner_name); /// Set batch_ to a new row batch and update tuple_mem_ accordingly. void StartNewRowBatch(); /// Override of GetSpareCapacity function in Scanner class. Return the spare capacity /// according to the spare capacity and the number of active scanners in real time. It /// will be the minimum value of spare capacity only for this scanner and the total /// spare capacity equally divided by all the active scanners. int64_t GetSpareCapacity(); /// Override of GetThreadSpareCapacity function in Scanner class. Return the spare /// capacity only for this scanner thread. It will be less than or equals to the total /// spare capacity for the process. int64_t GetThreadSpareCapacity(); /// Reset internal state for a new scan range. virtual Status InitNewRange() = 0; /// Gets memory for outputting tuples into batch_. /// *pool is the mem pool that should be used for memory allocated for those tuples. /// *tuple_mem should be the location to output tuples, and /// *tuple_row_mem for outputting tuple rows. /// Returns the maximum number of tuples/tuple rows that can be output (before the /// current row batch is complete and a new one is allocated). /// Memory returned from this call is invalidated after calling CommitRows. Callers must /// call GetMemory again after calling this function. int GetMemory(MemPool** pool, Tuple** tuple_mem, TupleRow** tuple_row_mem); /// Gets memory for outputting tuples into the ArrayValue being constructed via /// 'builder.' Same output params as GetMemory(). Returns the maximum number of tuples /// that can be output, or 0 if OOM. Sets parse_status_ if OOM (parse_status_ should not /// already be set when calling this function to avoid overwriting it). /// /// The returned TupleRow* should not be incremented (i.e. don't call next_row() on /// it). Instead, incrementing *tuple_mem will update *tuple_row_mem to be pointing at /// the next tuple. This also means its unnecessary to call /// (*tuple_row_mem)->SetTuple(). int GetCollectionMemory(ArrayValueBuilder* builder, MemPool** pool, Tuple** tuple_mem, TupleRow** tuple_row_mem); /// Commit num_rows to the current row batch. If this completes, the row batch is /// enqueued with the scan node and StartNewRowBatch() is called. /// Returns Status::OK if the query is not cancelled and hasn't exceeded any mem limits. /// Scanner can call this with 0 rows to flush any pending resources (attached pools /// and io buffers) to minimize memory consumption. Status CommitRows(int num_rows); /// Attach all remaining resources from context_ to batch_ and send batch_ to the scan /// node. This must be called after all rows have been committed and no further /// resources are needed from context_ (in practice this will happen in each scanner /// subclass's Close() implementation). void AddFinalRowBatch(); /// Release all memory in 'pool' to batch_. If commit_batch is true, the row batch /// will be committed. commit_batch should be true if the attached pool is expected /// to be non-trivial (i.e. a decompression buffer) to minimize scanner mem usage. void AttachPool(MemPool* pool, bool commit_batch) { DCHECK(batch_ != NULL); DCHECK(pool != NULL); batch_->tuple_data_pool()->AcquireData(pool, false); if (commit_batch) CommitRows(0); } /// Convenience function for evaluating conjuncts using this scanner's ExprContexts. /// This must always be inlined so we can correctly replace the call to /// ExecNode::EvalConjuncts() during codegen. bool IR_ALWAYS_INLINE EvalConjuncts(TupleRow* row) { return ExecNode::EvalConjuncts(&(*scanner_conjunct_ctxs_)[0], scanner_conjunct_ctxs_->size(), row); } /// Utility method to write out tuples when there are no materialized /// fields (e.g. select count(*) or only partition keys). /// num_tuples - Total number of tuples to write out. /// Returns the number of tuples added to the row batch. int WriteEmptyTuples(RowBatch* row_batch, int num_tuples); /// Write empty tuples and commit them to the context object int WriteEmptyTuples(ScannerContext* context, TupleRow* tuple_row, int num_tuples); /// Processes batches of fields and writes them out to tuple_row_mem. /// - 'pool' mempool to allocate from for auxiliary tuple memory /// - 'tuple_row_mem' preallocated tuple_row memory this function must use. /// - 'fields' must start at the beginning of a tuple. /// - 'num_tuples' number of tuples to process /// - 'max_added_tuples' the maximum number of tuples that should be added to the batch. /// - 'row_start_index' is the number of rows that have already been processed /// as part of WritePartialTuple. /// Returns the number of tuples added to the row batch. This can be less than /// num_tuples/tuples_till_limit because of failed conjuncts. /// Returns -1 if parsing should be aborted due to parse errors. int WriteAlignedTuples(MemPool* pool, TupleRow* tuple_row_mem, int row_size, FieldLocation* fields, int num_tuples, int max_added_tuples, int slots_per_tuple, int row_start_indx); /// Update the decompressor_ object given a compression type or codec name. Depending on /// the old compression type and the new one, it may close the old decompressor and/or /// create a new one of different type. Status UpdateDecompressor(const THdfsCompression::type& compression); Status UpdateDecompressor(const std::string& codec); /// Utility function to report parse errors for each field. /// If errors[i] is nonzero, fields[i] had a parse error. /// row_idx is the idx of the row in the current batch that had the parse error /// Returns false if parsing should be aborted. In this case parse_status_ is set /// to the error. /// This is called from WriteAlignedTuples. bool ReportTupleParseError(FieldLocation* fields, uint8_t* errors, int row_idx); /// Utility function to append an error message for an invalid row. This is called /// from ReportTupleParseError() /// row_idx is the index of the row in the current batch. Subclasses should override /// this function (i.e. text needs to join boundary rows). Since this is only in the /// error path, vtable overhead is acceptable. virtual void LogRowParseError(int row_idx, std::stringstream*); /// Writes out all slots for 'tuple' from 'fields'. 'fields' must be aligned /// to the start of the tuple (e.g. fields[0] maps to slots[0]). /// After writing the tuple, it will be evaluated against the conjuncts. /// - error_fields is an out array. error_fields[i] will be set to true if the ith /// field had a parse error /// - error_in_row is an out bool. It is set to true if any field had parse errors /// Returns whether the resulting tuplerow passed the conjuncts. // /// The parsing of the fields and evaluating against conjuncts is combined in this /// function. This is done so it can be possible to evaluate conjuncts as slots /// are materialized (on partial tuples). // /// This function is replaced by a codegen'd function at runtime. This is /// the reason that the out error parameters are typed uint8_t instead of bool. We need /// to be able to match this function's signature identically for the codegen'd function. /// Bool's as out parameters can get converted to bytes by the compiler and rather than /// implicitly depending on that to happen, we will explicitly type them to bytes. /// TODO: revisit this bool WriteCompleteTuple(MemPool* pool, FieldLocation* fields, Tuple* tuple, TupleRow* tuple_row, Tuple* template_tuple, uint8_t* error_fields, uint8_t* error_in_row); /// Codegen function to replace WriteCompleteTuple. Should behave identically /// to WriteCompleteTuple. static llvm::Function* CodegenWriteCompleteTuple(HdfsScanNode*, LlvmCodeGen*, const std::vector<ExprContext*>& conjunct_ctxs); /// Codegen function to replace WriteAlignedTuples. WriteAlignedTuples is cross compiled /// to IR. This function loads the precompiled IR function, modifies it and returns the /// resulting function. static llvm::Function* CodegenWriteAlignedTuples(HdfsScanNode*, LlvmCodeGen*, llvm::Function* write_tuple_fn); /// Report parse error for column @ desc. If abort_on_error is true, sets /// parse_status_ to the error message. void ReportColumnParseError(const SlotDescriptor* desc, const char* data, int len); /// Initialize a tuple. /// TODO: only copy over non-null slots. /// TODO: InitTuple is called frequently, avoid the if, perhaps via templatization. void InitTuple(const TupleDescriptor* desc, Tuple* template_tuple, Tuple* tuple) { if (template_tuple != NULL) { memcpy(tuple, template_tuple, desc->byte_size()); } else { memset(tuple, 0, sizeof(uint8_t) * desc->num_null_bytes()); } } // TODO: replace this function with above once we can inline constants from // scan_node_->tuple_desc() via codegen void InitTuple(Tuple* template_tuple, Tuple* tuple) { if (template_tuple != NULL) { memcpy(tuple, template_tuple, tuple_byte_size_); } else { memset(tuple, 0, sizeof(uint8_t) * num_null_bytes_); } } inline Tuple* next_tuple(int tuple_byte_size, Tuple* t) const { uint8_t* mem = reinterpret_cast<uint8_t*>(t); return reinterpret_cast<Tuple*>(mem + tuple_byte_size); } inline TupleRow* next_row(TupleRow* r) const { uint8_t* mem = reinterpret_cast<uint8_t*>(r); return reinterpret_cast<TupleRow*>(mem + batch_->row_byte_size()); } // Convenience function for calling the PrintPath() function in // debug-util. 'subpath_idx' can be specified in order to truncate the output to end on // the i-th element of 'path' (inclusive). string PrintPath(const SchemaPath& path, int subpath_idx = -1) const; /// Simple wrapper around scanner_conjunct_ctxs_. Used in the codegen'd version of /// WriteCompleteTuple() because it's easier than writing IR to access /// scanner_conjunct_ctxs_. ExprContext* GetConjunctCtx(int idx) const; }; } #endif
{ "content_hash": "c13059064338f3fb4523dcf7c03213a7", "timestamp": "", "source": "github", "line_count": 397, "max_line_length": 92, "avg_line_length": 48.34760705289673, "alnum_prop": 0.7211628633948108, "repo_name": "cloudera/recordservice", "id": "9113a1fb520e1d2533e6c73c5e0edcb50d52052e", "size": "20188", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "be/src/exec/hdfs-scanner.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "201440" }, { "name": "C++", "bytes": "7926444" }, { "name": "CMake", "bytes": "108959" }, { "name": "CSS", "bytes": "89516" }, { "name": "Groff", "bytes": "1633" }, { "name": "HTML", "bytes": "63" }, { "name": "Java", "bytes": "3900670" }, { "name": "JavaScript", "bytes": "484" }, { "name": "Lex", "bytes": "22041" }, { "name": "Objective-C", "bytes": "990" }, { "name": "PLpgSQL", "bytes": "3646" }, { "name": "Protocol Buffer", "bytes": "630" }, { "name": "Python", "bytes": "1499004" }, { "name": "Shell", "bytes": "183736" }, { "name": "Thrift", "bytes": "251512" }, { "name": "Yacc", "bytes": "82243" } ], "symlink_target": "" }
<div ng-show="slaveshow" class="row fullheight"> <div class="col-xs-9 fullheight"> <slave-terminal ng-style="style"></slave-terminal> </div> <div class="col-xs-3 fullheight termpanel"> <nutty-signin></nutty-signin> <input type="text" class="form-control" placeholder="Description" ng-model="desc" ng-readonly="descro" style="cursor:pointer;color:black;margin-bottom:10px"> <tmux-buttons></tmux-buttons> <scripts-paste></scripts-paste> <nutty-alert></nutty-alert> <nutty-chat></nutty-chat> </div> </div> <div ng-hide="slaveshow" class="row"> <div class="col-xs-3"></div> <div class="col-xs-6"> <alert class="pushdown" type="danger"> <strong style="color:red"> Supported Browser: Chrome-29 </strong> <br>Your Browser: [[Compatibility.browser.browser]]-[[Compatibility.browser.version]] </alert> </div> <div class="col-xs-3"></div> </div>
{ "content_hash": "2c519ae1d6aa30968aaf554786677db0", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 165, "avg_line_length": 37.88461538461539, "alnum_prop": 0.6060913705583756, "repo_name": "harshavardhana/nuttyapp", "id": "411cef1baa5a67f201996a071fc57b0090dd942e", "size": "985", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "public/views/slave.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2971" }, { "name": "Go", "bytes": "3385" }, { "name": "HTML", "bytes": "74279" }, { "name": "JavaScript", "bytes": "234316" } ], "symlink_target": "" }
import EightPuzzleWithHeuristics as Problem #puzzle14a.py: CREATE_INITIAL_STATE = lambda: Problem.State([4, 5, 0, 1, 2, 8, 3, 7, 6])
{ "content_hash": "e751153644b33ea8b8188e3e6a2d0b34", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 73, "avg_line_length": 33.25, "alnum_prop": 0.7218045112781954, "repo_name": "vaibhavi-r/CSE-415", "id": "6a7e79693cab7e6c7fd53ad61a58224e3ba83ed9", "size": "133", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assignment3/puzzle14a.py", "mode": "33188", "license": "mit", "language": [ { "name": "Jupyter Notebook", "bytes": "33117" }, { "name": "Python", "bytes": "151255" } ], "symlink_target": "" }
/** * An AngularJS directive for showcasing features of your website * @version v0.1.2 - 2015-07-15 * @link https://github.com/DaftMonk/angular-tour * @author Tyler Henkel * @license MIT License, http://www.opensource.org/licenses/MIT */ (function (window, document, undefined) { 'use strict'; angular.module('angular-tour', [ 'angular-tour.tpls', 'angular-tour.tour' ]); angular.module('angular-tour.tpls', ['tour/tour.tpl.html']); angular.module('tour/tour.tpl.html', []).run([ '$templateCache', function ($templateCache) { $templateCache.put('tour/tour.tpl.html', '<div class="tour-tip">\n' + ' <span class="tour-arrow tt-{{ ttPlacement }}" ng-hide="centered"></span>\n' + ' <div class="tour-content-wrapper">\n' + ' <p ng-bind="ttContent"></p>\n' + ' <a ng-click="back()" ng-bind="ttBackLabel" ng-show="getCurrentStep()>0" class="small button tour-next-tip"></a>\n' + ' <a ng-click="proceed()" ng-bind="ttNextLabel" class="small button tour-next-tip"></a>\n' + ' <a ng-click="closeTour()" class="tour-close-tip">&times;</a>\n' + ' </div>\n' + '</div>\n' + ''); } ]); angular.module('angular-tour.tour', []).constant('tourConfig', { placement: 'top', animation: true, previousLabel: 'Previous', nextLabel: 'Next', scrollSpeed: 500, offset: 28, backDrop: false, useSourceScope: false }).controller('TourController', [ '$scope', 'orderedList', function ($scope, orderedList) { var self = this, steps = self.steps = orderedList(); // we'll pass these in from the directive self.postTourCallback = angular.noop; self.postStepCallback = angular.noop; self.showStepCallback = angular.noop; self.currentStep = -1; // if currentStep changes, select the new step $scope.$watch(function () { return self.currentStep; }, function (val) { self.select(val); }); self.select = function (nextIndex) { if (!angular.isNumber(nextIndex)) return; self.unselectAllSteps(); var step = steps.get(nextIndex); if (step) { step.ttOpen = true; } // update currentStep if we manually selected this index if (self.currentStep !== nextIndex) { self.currentStep = nextIndex; } if (self.currentStep > -1) self.showStepCallback(); if (nextIndex >= steps.getCount()) { self.postTourCallback(true); } self.postStepCallback(); }; self.addStep = function (step) { if (angular.isNumber(step.index) && !isNaN(step.index)) { steps.set(step.index, step); } else { steps.push(step); } }; self.unselectAllSteps = function () { steps.forEach(function (step) { step.ttOpen = false; }); }; self.cancelTour = function () { self.unselectAllSteps(); self.postTourCallback(false); }; $scope.openTour = function () { // open at first step if we've already finished tour var startStep = self.currentStep >= steps.getCount() || self.currentStep < 0 ? 0 : self.currentStep; self.select(startStep); }; $scope.closeTour = function () { self.cancelTour(); }; $scope.finishTour = function () { self.unselectAllSteps(); self.postTourCallback(true); }; } ]).directive('tour', [ '$parse', 'tourConfig', function ($parse, tourConfig) { return { controller: 'TourController', restrict: 'EA', scope: true, link: function (scope, element, attrs, ctrl) { ctrl.previousStep = []; if (!angular.isDefined(attrs.step)) { throw 'The <tour> directive requires a `step` attribute to bind the current step to.'; } if (angular.isDefined(attrs.backDrop)) { tourConfig.backDrop = attrs.backDrop === 'true'; } var model = $parse(attrs.step); var backDrop = false; // Watch current step view model and update locally scope.$watch(attrs.step, function (newVal) { ctrl.currentStep = newVal; }); ctrl.postTourCallback = function (completed) { angular.element('.tour-backdrop').remove(); backDrop = false; angular.element('.tour-element-active').removeClass('tour-element-active'); if (completed && angular.isDefined(attrs.tourComplete)) { scope.$parent.$eval(attrs.tourComplete); } if (angular.isDefined(attrs.postTour)) { scope.$parent.$eval(attrs.postTour); } }; ctrl.postStepCallback = function () { if (angular.isDefined(attrs.postStep)) { scope.$parent.$eval(attrs.postStep); } }; ctrl.showStepCallback = function () { if (!backDrop && tourConfig.backDrop) { angular.element('body').append(angular.element('<div class="tour-backdrop"></div>')); backDrop = true; } }; // update the current step in the view as well as in our controller scope.setCurrentStep = function (val, goBack) { model.assign(scope.$parent, val); if (!goBack) { ctrl.previousStep.push(ctrl.currentStep); } ctrl.currentStep = val; }; scope.back = function () { scope.setCurrentStep(scope.getPreviousStep(), true); }; scope.skipStep = function () { ctrl.currentStep++; }; scope.getPreviousStep = function () { return ctrl.previousStep.pop(); }; scope.getCurrentStep = function () { return ctrl.currentStep; }; } }; } ]).directive('tourtip', [ '$window', '$compile', '$interpolate', '$timeout', 'scrollTo', 'tourConfig', function ($window, $compile, $interpolate, $timeout, scrollTo, tourConfig) { var startSym = $interpolate.startSymbol(), endSym = $interpolate.endSymbol(); var template = '<div tour-popup></div>'; return { require: '^tour', restrict: 'EA', scope: true, link: function (scope, element, attrs, tourCtrl) { attrs.$observe('tourtip', function (val) { scope.ttContent = val; }); //defaults: tourConfig.placement attrs.$observe('tourtipPlacement', function (val) { scope.ttPlacement = (val || tourConfig.placement).toLowerCase().trim(); scope.centered = scope.ttPlacement.indexOf('center') === 0; }); attrs.$observe('tourtipPreviousLabel', function (val) { scope.ttBackLabel = val || tourConfig.previousLabel; }); attrs.$observe('tourtipNextLabel', function (val) { scope.ttNextLabel = val || tourConfig.nextLabel; }); attrs.$observe('tourtipOffset', function (val) { scope.ttOffset = parseInt(val, 10) || tourConfig.offset; }); //defaults: null attrs.$observe('onShow', function (val) { scope.onStepShow = val || null; }); //defaults: null attrs.$observe('onProceed', function (val) { scope.onStepProceed = val || null; }); //defaults: null attrs.$observe('tourtipElement', function (val) { scope.ttElement = val || null; }); //defaults: tourConfig.useSourceScope attrs.$observe('useSourceScope', function (val) { scope.ttSourceScope = !val ? tourConfig.useSourceScope : val === 'true'; }); //disable scrolling attrs.$observe('disableScrolling', function (val) { scope.disableScrolling = val === 'true'; }); //Init assignments (fix for Angular 1.3+) scope.ttBackLabel = tourConfig.previousLabel; scope.ttNextLabel = tourConfig.nextLabel; scope.ttPlacement = tourConfig.placement.toLowerCase().trim(); scope.centered = false; scope.ttOffset = tourConfig.offset; scope.ttSourceScope = tourConfig.useSourceScope; scope.ttOpen = false; scope.ttAnimation = tourConfig.animation; scope.index = parseInt(attrs.tourtipStep, 10); scope.last = attrs.hasOwnProperty('tourtipLast'); var tourtip = $compile(template)(scope); tourCtrl.addStep(scope); // wrap this in a time out because the tourtip won't compile right away $timeout(function () { scope.$watch('ttOpen', function (val) { if (val) { show(); } else { hide(); } }); }, 500); //determining target scope. It's used only when using virtual steps and there //is some action performed like on-show or on-progress. Without virtual steps //action would performed on element's scope and that would work just fine //however, when using virtual steps, whose steps can be placed in different //controller, so it affects scope, which will be used to run this action against. function getTargetScope() { var targetElement = scope.ttElement ? angular.element(scope.ttElement) : element; var targetScope = scope; if (targetElement !== element && !scope.ttSourceScope) targetScope = targetElement.scope(); return targetScope; } function calculatePosition(element) { var ttPosition; // Get the position of the directive element var position = element[0].getBoundingClientRect(); //make it relative against page, not the window var top = position.top + window.pageYOffset; var ttWidth = tourtip.width(); var ttHeight = tourtip.height(); // Calculate the tourtip's top and left coordinates to center it switch (scope.ttPlacement) { case 'right': ttPosition = { top: top, left: position.left + position.width + scope.ttOffset }; break; case 'bottom': ttPosition = { top: top + position.height + scope.ttOffset, left: position.left }; if (position.width < 50) { ttPosition.left -= 22; } break; case 'center': ttPosition = { top: top + 0.5 * (position.height - ttHeight) + scope.ttOffset, left: position.left + 0.5 * (position.width - ttWidth) }; break; case 'center-top': ttPosition = { top: top + 0.1 * (position.height - ttHeight) + scope.ttOffset, left: position.left + 0.5 * (position.width - ttWidth) }; break; case 'left': ttPosition = { top: top, left: position.left - ttWidth - scope.ttOffset }; break; default: ttPosition = { top: top - ttHeight - scope.ttOffset, left: position.left }; break; } ttPosition.top += 'px'; ttPosition.left += 'px'; return ttPosition; } function show() { if (!scope.ttContent) { return; } if (scope.ttAnimation) tourtip.fadeIn(); else { tourtip.css({ display: 'block' }); } var targetElement = scope.ttElement ? angular.element(scope.ttElement) : element; if (targetElement == null || targetElement.length === 0) { if (targetElement == null || targetElement.length === 0) { if (scope.last) { scope.$parent.finishTour(); } scope.skipStep(); return; } } angular.element('body').append(tourtip); var updatePosition = function () { var ttPosition = calculatePosition(targetElement); // Now set the calculated positioning. tourtip.css(ttPosition); // Scroll to the tour tip if (!scope.disableScrolling) { scrollTo(tourtip, -200, -300, tourConfig.scrollSpeed); } }; if (tourConfig.backDrop) focusActiveElement(targetElement); angular.element($window).bind('resize.' + scope.$id, updatePosition); updatePosition(); if (scope.onStepShow) { var targetScope = getTargetScope(); //fancy! Let's make on show action not instantly, but after a small delay $timeout(function () { targetScope.$eval(scope.onStepShow); }, 300); } } function hide() { tourtip.detach(); angular.element($window).unbind('resize.' + scope.$id); } function focusActiveElement(el) { angular.element('.tour-element-active').removeClass('tour-element-active'); if (!scope.centered) el.addClass('tour-element-active'); } // Make sure tooltip is destroyed and removed. scope.$on('$destroy', function onDestroyTourtip() { angular.element($window).unbind('resize.' + scope.$id); tourtip.remove(); tourtip = null; }); scope.proceed = function () { if (scope.onStepProceed) { var targetScope = getTargetScope(); $timeout(function () { targetScope.$eval(scope.onStepProceed); }, 100); } scope.setCurrentStep(scope.getCurrentStep() + 1); }; } }; } ]).directive('tourPopup', function () { return { replace: true, templateUrl: 'tour/tour.tpl.html', scope: true, restrict: 'EA', link: function (scope, element, attrs) { } }; }).factory('orderedList', function () { var OrderedList = function () { this.map = {}; this._array = []; }; OrderedList.prototype.set = function (key, value) { if (!angular.isNumber(key)) return; if (key in this.map) { this.map[key] = value; } else { if (key < this._array.length) { var insertIndex = key - 1 > 0 ? key - 1 : 0; this._array.splice(insertIndex, 0, key); } else { this._array.push(key); } this.map[key] = value; this._array.sort(function (a, b) { return a - b; }); } }; OrderedList.prototype.indexOf = function (value) { for (var prop in this.map) { if (this.map.hasOwnProperty(prop)) { if (this.map[prop] === value) return Number(prop); } } }; OrderedList.prototype.push = function (value) { var key = this._array[this._array.length - 1] + 1 || 0; this._array.push(key); this.map[key] = value; this._array.sort(function (a, b) { return a - b; }); }; OrderedList.prototype.remove = function (key) { var index = this._array.indexOf(key); if (index === -1) { throw new Error('key does not exist'); } this._array.splice(index, 1); delete this.map[key]; }; OrderedList.prototype.get = function (key) { return this.map[key]; }; OrderedList.prototype.getCount = function () { return this._array.length; }; OrderedList.prototype.forEach = function (f) { var key, value; for (var i = 0; i < this._array.length; i++) { key = this._array[i]; value = this.map[key]; f(value, key); } }; OrderedList.prototype.first = function () { var key, value; key = this._array[0]; value = this.map[key]; return value; }; var orderedListFactory = function () { return new OrderedList(); }; return orderedListFactory; }).factory('scrollTo', function () { return function (target, offsetY, offsetX, speed) { if (target) { offsetY = offsetY || -100; offsetX = offsetX || -100; speed = speed || 500; $('html,body').stop().animate({ scrollTop: target.offset().top + offsetY, scrollLeft: target.offset().left + offsetX }, speed); } else { $('html,body').stop().animate({ scrollTop: 0 }, speed); } }; }); }(window, document));
{ "content_hash": "088caccb15eee56b7f53548b1ebff47c", "timestamp": "", "source": "github", "line_count": 466, "max_line_length": 581, "avg_line_length": 36.78969957081545, "alnum_prop": 0.5296896873541764, "repo_name": "Real-Skill/angular-tour", "id": "78d76e29af8af5820f6c950b71f84556306149e6", "size": "17144", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dist/angular-tour-tpls.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7502" }, { "name": "HTML", "bytes": "14498" }, { "name": "JavaScript", "bytes": "44855" } ], "symlink_target": "" }
using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Frapid.ApplicationState.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Frapid.Config.DataAccess; using Frapid.Config.Api.Fakes; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Xunit; namespace Frapid.Config.Api.Tests { public class MenuTests { public static ConfigMenuController Fixture() { ConfigMenuController controller = new ConfigMenuController(new MenuRepository(), "", new LoginView()); return controller; } [Fact] [Conditional("Debug")] public void CountEntityColumns() { EntityView entityView = Fixture().GetEntityView(); Assert.Null(entityView.Columns); } [Fact] [Conditional("Debug")] public void Count() { long count = Fixture().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetAll() { int count = Fixture().GetAll().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void Export() { int count = Fixture().Export().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void Get() { Frapid.Config.Entities.Menu menu = Fixture().Get(0); Assert.NotNull(menu); } [Fact] [Conditional("Debug")] public void First() { Frapid.Config.Entities.Menu menu = Fixture().GetFirst(); Assert.NotNull(menu); } [Fact] [Conditional("Debug")] public void Previous() { Frapid.Config.Entities.Menu menu = Fixture().GetPrevious(0); Assert.NotNull(menu); } [Fact] [Conditional("Debug")] public void Next() { Frapid.Config.Entities.Menu menu = Fixture().GetNext(0); Assert.NotNull(menu); } [Fact] [Conditional("Debug")] public void Last() { Frapid.Config.Entities.Menu menu = Fixture().GetLast(); Assert.NotNull(menu); } [Fact] [Conditional("Debug")] public void GetMultiple() { IEnumerable<Frapid.Config.Entities.Menu> menus = Fixture().Get(new int[] { }); Assert.NotNull(menus); } [Fact] [Conditional("Debug")] public void GetPaginatedResult() { int count = Fixture().GetPaginatedResult().Count(); Assert.Equal(1, count); count = Fixture().GetPaginatedResult(1).Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void CountWhere() { long count = Fixture().CountWhere(new JArray()); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetWhere() { int count = Fixture().GetWhere(1, new JArray()).Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void CountFiltered() { long count = Fixture().CountFiltered(""); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetFiltered() { int count = Fixture().GetFiltered(1, "").Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetDisplayFields() { int count = Fixture().GetDisplayFields().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetCustomFields() { int count = Fixture().GetCustomFields().Count(); Assert.Equal(1, count); count = Fixture().GetCustomFields("").Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void AddOrEdit() { try { var form = new JArray { null, null }; Fixture().AddOrEdit(form); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void Add() { try { Fixture().Add(null); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void Edit() { try { Fixture().Edit(0, null); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void BulkImport() { var collection = new JArray { null, null, null, null }; var actual = Fixture().BulkImport(collection); Assert.NotNull(actual); } [Fact] [Conditional("Debug")] public void Delete() { try { Fixture().Delete(0); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode); } } } }
{ "content_hash": "2006f3caa590290256a1309b2808731c", "timestamp": "", "source": "github", "line_count": 239, "max_line_length": 114, "avg_line_length": 24.84100418410042, "alnum_prop": 0.49486272528212905, "repo_name": "nubiancc/frapid", "id": "f58ba6f1e302625c345fc8cb85431688eb50b02f", "size": "5962", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Frapid.Web/Areas/Frapid.Config/WebApi/Tests/MenuTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ABAP", "bytes": "962" }, { "name": "ASP", "bytes": "101" }, { "name": "ActionScript", "bytes": "1133" }, { "name": "Ada", "bytes": "99" }, { "name": "Assembly", "bytes": "549" }, { "name": "AutoHotkey", "bytes": "720" }, { "name": "Batchfile", "bytes": "1029" }, { "name": "C#", "bytes": "5093309" }, { "name": "C++", "bytes": "806" }, { "name": "COBOL", "bytes": "4" }, { "name": "CSS", "bytes": "8735933" }, { "name": "Cirru", "bytes": "520" }, { "name": "Clojure", "bytes": "794" }, { "name": "CoffeeScript", "bytes": "403" }, { "name": "ColdFusion", "bytes": "86" }, { "name": "Common Lisp", "bytes": "632" }, { "name": "Cucumber", "bytes": "699" }, { "name": "D", "bytes": "324" }, { "name": "Dart", "bytes": "489" }, { "name": "Eiffel", "bytes": "375" }, { "name": "Elixir", "bytes": "692" }, { "name": "Elm", "bytes": "487" }, { "name": "Erlang", "bytes": "487" }, { "name": "Forth", "bytes": "979" }, { "name": "FreeMarker", "bytes": "1017" }, { "name": "GLSL", "bytes": "512" }, { "name": "Go", "bytes": "641" }, { "name": "Groff", "bytes": "2072" }, { "name": "Groovy", "bytes": "1080" }, { "name": "HTML", "bytes": "635450" }, { "name": "Haskell", "bytes": "512" }, { "name": "Haxe", "bytes": "447" }, { "name": "Io", "bytes": "140" }, { "name": "JSONiq", "bytes": "4" }, { "name": "Java", "bytes": "1550" }, { "name": "JavaScript", "bytes": "30339436" }, { "name": "Julia", "bytes": "210" }, { "name": "LSL", "bytes": "2080" }, { "name": "Lean", "bytes": "213" }, { "name": "Liquid", "bytes": "1883" }, { "name": "LiveScript", "bytes": "5790" }, { "name": "Lua", "bytes": "981" }, { "name": "Makefile", "bytes": "4774" }, { "name": "Mask", "bytes": "597" }, { "name": "Matlab", "bytes": "203" }, { "name": "Nix", "bytes": "2212" }, { "name": "OCaml", "bytes": "539" }, { "name": "Objective-C", "bytes": "2672" }, { "name": "OpenSCAD", "bytes": "333" }, { "name": "PHP", "bytes": "351" }, { "name": "Pascal", "bytes": "263174" }, { "name": "Perl", "bytes": "678" }, { "name": "PowerShell", "bytes": "346828" }, { "name": "Protocol Buffer", "bytes": "274" }, { "name": "Puppet", "bytes": "6404" }, { "name": "Python", "bytes": "478" }, { "name": "R", "bytes": "2445" }, { "name": "Ruby", "bytes": "531" }, { "name": "Rust", "bytes": "495" }, { "name": "SQLPL", "bytes": "30159" }, { "name": "Scala", "bytes": "1541" }, { "name": "Scheme", "bytes": "559" }, { "name": "Shell", "bytes": "1154" }, { "name": "Swift", "bytes": "476" }, { "name": "Tcl", "bytes": "899" }, { "name": "TeX", "bytes": "1345" }, { "name": "TypeScript", "bytes": "1607" }, { "name": "VHDL", "bytes": "830" }, { "name": "Vala", "bytes": "485" }, { "name": "Verilog", "bytes": "274" }, { "name": "Visual Basic", "bytes": "916" }, { "name": "XQuery", "bytes": "114" } ], "symlink_target": "" }
package org.apache.mesos.chronos.scheduler.jobs import java.util.logging.Logger import org.apache.mesos.Protos.{TaskID, TaskState, TaskStatus} import org.apache.mesos.chronos.scheduler.state.PersistenceStore import org.joda.time.{DateTime, DateTimeZone} import scala.collection.mutable /** * This file contains a number of classes and objects for dealing with tasks. Tasks are the actual units of work that * get translated into a chronos-task based on a job and it's schedule or as a dependency based on another task. They are * serialized to an underlying storage upon submission such that in the case of failed tasks or scheduler failover the * task can be retried, double submission during failover is prevented, etc. * @author Florian Leibert (flo@leibert.de) */ object TaskUtils { //TaskIdFormat: ct:JOB_NAME:DUE:ATTEMPT:ARGUMENTS val taskIdTemplate = "ct:%d:%d:%s:%s" val argumentsPattern = """(.*)?""".r val taskIdPattern = """ct:(\d+):(\d+):%s:?%s""".format(JobUtils.jobNamePattern, argumentsPattern).r val commandInjectionFilter = ";".toSet private[this] val log = Logger.getLogger(getClass.getName) def getTaskStatus(job: BaseJob, due: DateTime, attempt: Int = 0): TaskStatus = { TaskStatus.newBuilder.setTaskId(TaskID.newBuilder.setValue(getTaskId(job, due, attempt))).setState(TaskState.TASK_STAGING).build } def isValidVersion(taskIdString: String): Boolean = { taskIdPattern.findFirstIn(taskIdString).nonEmpty } def appendSchedulerMessage(msg: String, taskStatus: TaskStatus): String = { val schedulerMessage = if (taskStatus.hasMessage && taskStatus.getMessage.nonEmpty) Some(taskStatus.getMessage) else None schedulerMessage.fold(msg)(m => "%sThe scheduler provided this message:\n\n%s".format(msg, m)) } /** * Parses the task id into the jobname and the tasks creation time. * @param taskId * @return */ def getJobNameForTaskId(taskId: String): String = { require(taskId != null, "taskId cannot be null") try { val TaskUtils.taskIdPattern(_, _, jobName, _) = taskId jobName } catch { case t: Exception => log.warning("Unable to parse idStr: '%s' due to a corrupted string or version error. " + "Warning, dependents will not be triggered!") "" } } /** * Parses the task id into job arguments * @param taskId * @return */ def getJobArgumentsForTaskId(taskId: String): String = { require(taskId != null, "taskId cannot be null") try { val TaskUtils.taskIdPattern(_, _, _, jobArguments) = taskId jobArguments } catch { case t: Exception => log.warning("Unable to parse idStr: '%s' due to a corrupted string or version error. " + "Warning, dependents will not be triggered!") "" } } def loadTasks(taskManager: TaskManager, persistenceStore: PersistenceStore) { val allTasks = persistenceStore.getTasks val validTasks = TaskUtils.getDueTimes(allTasks) validTasks.foreach({ case (key, valueTuple) => val (job, due, attempt) = valueTuple taskManager.removeTask(key) if (due == 0L) { log.info("Enqueuing at once") taskManager.scheduleTask(TaskUtils.getTaskId(job, DateTime.now(DateTimeZone.UTC), attempt), job, persist = true) } else if (due > 0L) { log.info("Enqueuing later") val newDueTime = DateTime.now(DateTimeZone.UTC).plus(due) taskManager.scheduleDelayedTask( new ScheduledTask(TaskUtils.getTaskId(job, newDueTime, attempt), newDueTime, job, taskManager), due, persist = true) } else { log.info(("Filtering out old task '" + "%s' overdue by '%d' ms and removing from store.").format(key, due)) } }) } def getTaskId(job: BaseJob, due: DateTime, attempt: Int = 0, arguments: Option[String] = None): String = { val args: String = arguments.getOrElse(job.arguments.mkString(" ")).filterNot(commandInjectionFilter) taskIdTemplate.format(due.getMillis, attempt, job.name, args) } def getDueTimes(tasks: Map[String, Array[Byte]]): Map[String, (BaseJob, Long, Int)] = { val taskMap = new mutable.HashMap[String, (BaseJob, Long, Int)]() tasks.foreach { p: (String, Array[Byte]) => println(p._1) //Any non-recurring job R1/X/Y is equivalent to a task! val taskInstance = JobUtils.fromBytes(p._2) val taskTuple = parseTaskId(p._1) val now = DateTime.now(DateTimeZone.UTC).getMillis val lastExecutableTime = new DateTime(taskTuple._2, DateTimeZone.UTC).plus(taskInstance.epsilon).getMillis //if the task isn't due yet if (taskTuple._2 > now) { log.fine("Task '%s' is scheduled in the future".format(taskInstance.name)) taskMap += (p._1 ->(taskInstance, taskTuple._2 - now, taskTuple._3)) } else if (lastExecutableTime > now) { taskMap += (p._1 ->(taskInstance, 0L, taskTuple._3)) } else { log.fine("Task '%s' is overdue by '%d' ms!".format(p._1, now - taskTuple._2)) taskMap += (p._1 ->(taskInstance, taskTuple._2 - now, taskTuple._3)) } } taskMap.toMap } def parseTaskId(id: String): (String, Long, Int, String) = { val taskIdPattern(due, attempt, jobName, jobArguments) = id (jobName, due.toLong, attempt.toInt, jobArguments) } }
{ "content_hash": "5dc73d0639a3392aee1d8ebd0c6bcdfe", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 132, "avg_line_length": 38.81159420289855, "alnum_prop": 0.669529499626587, "repo_name": "mikkokupsu/chronos", "id": "3e5e2745e8797abd513b24ed546f7ae6b5430b5e", "size": "5356", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/main/scala/org/apache/mesos/chronos/scheduler/jobs/TaskUtils.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "20968" }, { "name": "CSS", "bytes": "49073" }, { "name": "HTML", "bytes": "29659" }, { "name": "JavaScript", "bytes": "1272982" }, { "name": "Makefile", "bytes": "1773" }, { "name": "Ruby", "bytes": "13433" }, { "name": "Scala", "bytes": "335488" }, { "name": "Shell", "bytes": "23333" } ], "symlink_target": "" }
package edu.irabank.form; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class BillpaymerchantapproveFormBean { private int merchantid; private String accountno; private int billid; private double amount; private String status; private String action; private String privateKey; public int getMerchantid() { return merchantid; } public void setMerchantid(int merchantid) { this.merchantid = merchantid; } public String getAccountno() { return accountno; } public void setAccountno(String accountno) { this.accountno = accountno; } public int getBillid() { return billid; } public void setBillid(int billid) { this.billid = billid; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public String getPrivateKey() { return privateKey; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } }
{ "content_hash": "8097c6a97032dccac0630f5413c55426", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 47, "avg_line_length": 18.073170731707318, "alnum_prop": 0.6923076923076923, "repo_name": "rsubra13/ss", "id": "d2a86aabb26d4cbd514aaa34ec0e571ef9534e14", "size": "1482", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ira_bank/src/edu/irabank/form/BillpaymerchantapproveFormBean.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "160496" }, { "name": "Java", "bytes": "276129" }, { "name": "JavaScript", "bytes": "266666" } ], "symlink_target": "" }
package org.jdbcsqltest; import java.sql.*; import java.util.Properties; /** * Created by shivshi on 5/1/17. */ public class JdbcDriver { private Connection conn = null; private String dbType; private static String SCHEMA_NAME = "testschema"; private Properties props; public JdbcDriver(Properties props) throws SQLException { this.props = props; dbType = props.getProperty(Config.DATABASE); conn = getConnection(props); } public Connection getNewConnection() throws SQLException { return getConnection(props); } private Connection getConnection(Properties props) throws SQLException { String JDBC_DRIVER = props.getProperty(Config.JDBC_DRIVER_CLASSNAME); String JDBC_DB_URL = props.getProperty(Config.JDBC_URL); // Database credentials String USER = props.getProperty(Config.JDBC_USER); String PASS = props.getProperty(Config.JDBC_PASSWORD); Connection conn = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(JDBC_DB_URL, USER, PASS); //conn.setAutoCommit(false); } catch (ClassNotFoundException e) { throw new IllegalStateException("Could not load class " + e.getLocalizedMessage()); } catch (SQLException e) { throw new IllegalStateException("Could not connect " + e.getLocalizedMessage()); } setSchema(conn); return conn; } public Connection getConnection() { return conn; } public String getSchema() throws SQLException { //if (Config.DATABASE_CIS.equals(dbType) || Config.DATABASE_ORACLE.equals(dbType)) // return null; return conn.getSchema(); } private void setSchema(Connection connection) throws SQLException { if (Config.DATABASE_CIS.equals(dbType) || Config.DATABASE_SQL_SERVER.equals(dbType) || Config.DATABASE_ORACLE.equals(dbType)) return; Statement stmt = connection.createStatement(); try { stmt.executeUpdate("CREATE SCHEMA " + SCHEMA_NAME); } catch (SQLException ex){ // Ignore if the schema already exists. } if(Config.DATABASE_PGSQL.equals(dbType)) stmt.executeUpdate("SET SCHEMA '" + SCHEMA_NAME + "'"); else stmt.executeUpdate("SET SCHEMA " + SCHEMA_NAME); stmt.close(); } public void clearSchema() throws SQLException { if(Config.DATABASE_CIS.equals(dbType) || Config.DATABASE_DB2.equals(dbType) || Config.DATABASE_SQL_SERVER.equals(dbType) || Config.DATABASE_ORACLE.equals(dbType) ) return; Statement stmt = conn.createStatement(); try { stmt.executeUpdate("DROP SCHEMA " + SCHEMA_NAME + " CASCADE"); } catch (SQLException ex){ // Ignore if the schema does not exist. } stmt.executeUpdate("CREATE SCHEMA " + SCHEMA_NAME); stmt.close(); } public void printDBInfo() { System.out.println("\nDatabase Info."); try { DatabaseMetaData dbmeta = conn.getMetaData(); System.out.println("\tDatabase Product : " + dbmeta.getDatabaseProductName()); System.out.println("\tDatabase Version : " + dbmeta.getDatabaseProductVersion()); System.out.println("\tJDBC Driver Name : " + dbmeta.getDriverName()); System.out.println("\tJDBC Driver Version : " + dbmeta.getDriverVersion()); } catch (SQLException e) { throw new IllegalStateException("Cannot access database metadata " + e.getLocalizedMessage()); } finally { } System.out.println(); } }
{ "content_hash": "9ed9137d0db27fe381e088f755b91c4b", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 133, "avg_line_length": 33.45132743362832, "alnum_prop": 0.6195767195767196, "repo_name": "shivarajugowda/jdbcSQLTest", "id": "4bdfeb805c21627ddb4a302800d65531388a63f8", "size": "3780", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/jdbcsqltest/JdbcDriver.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "70107" }, { "name": "Smarty", "bytes": "168648" } ], "symlink_target": "" }
<component name="libraryTable"> <library name="support-v4-23.0.1"> <ANNOTATIONS> <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/support-v4/23.0.1/annotations.zip!/" /> </ANNOTATIONS> <CLASSES> <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/support-v4/23.0.1/res" /> <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/support-v4/23.0.1/jars/libs/internal_impl-23.0.1.jar!/" /> <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/support-v4/23.0.1/jars/classes.jar!/" /> </CLASSES> <JAVADOC /> <SOURCES> <root url="jar://C:/sdk/extras/android/m2repository/com/android/support/support-v4/23.0.1/support-v4-23.0.1-sources.jar!/" /> </SOURCES> </library> </component>
{ "content_hash": "c4e8e2b9cc7c7e326c5e3afb9644d2ab", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 152, "avg_line_length": 55, "alnum_prop": 0.6829545454545455, "repo_name": "AmniX/MaterialPatternllockView", "id": "da793bdff26f695df68b1837f17f7f7a9c341aaa", "size": "880", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/libraries/support_v4_23_0_1.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "53593" } ], "symlink_target": "" }
package org.apache.bcel.classfile; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.bcel.Constants; /** * This class is derived from the abstract * <A HREF="org.apache.bcel.classfile.Constant.html">Constant</A> class * and represents a reference to a Utf8 encoded string. * * @version $Id: ConstantUtf8.java 386056 2006-03-15 11:31:56Z tcurdt $ * @author <A HREF="mailto:m.dahm@gmx.de">M. Dahm</A> * @see Constant */ public final class ConstantUtf8 extends Constant { private String bytes; /** * Initialize from another object. */ public ConstantUtf8(ConstantUtf8 c) { this(c.getBytes()); } /** * Initialize instance from file data. * * @param file Input stream * @throws IOException */ ConstantUtf8(DataInputStream file) throws IOException { super(Constants.CONSTANT_Utf8); bytes = file.readUTF(); } /** * @param bytes Data */ public ConstantUtf8(String bytes) { super(Constants.CONSTANT_Utf8); if (bytes == null) { throw new IllegalArgumentException("bytes must not be null!"); } this.bytes = bytes; } /** * Called by objects that are traversing the nodes of the tree implicitely * defined by the contents of a Java class. I.e., the hierarchy of methods, * fields, attributes, etc. spawns a tree of objects. * * @param v Visitor object */ public void accept( Visitor v ) { v.visitConstantUtf8(this); } /** * Dump String in Utf8 format to file stream. * * @param file Output file stream * @throws IOException */ public final void dump( DataOutputStream file ) throws IOException { file.writeByte(tag); file.writeUTF(bytes); } /** * @return Data converted to string. */ public final String getBytes() { return bytes; } /** * @param bytes the raw bytes of this Utf-8 */ public final void setBytes( String bytes ) { this.bytes = bytes; } /** * @return String representation */ public final String toString() { return super.toString() + "(\"" + Utility.replace(bytes, "\n", "\\n") + "\")"; } }
{ "content_hash": "bdc10c2c15fe70ce24d66f4f4435f0d2", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 86, "avg_line_length": 23.11881188118812, "alnum_prop": 0.6038543897216274, "repo_name": "treejames/JMD", "id": "f30e0d423fc27f9484777861caccd3e3364d3ef0", "size": "2968", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/org/apache/bcel/classfile/ConstantUtf8.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "23490" }, { "name": "Java", "bytes": "2561043" } ], "symlink_target": "" }
<div class="row"> <div class="col-xs-12 col-sm-12 col-md-offset-3 col-md-6 col-lg-offset-3 col-lg-6"> <div class="col-xs-12 col-sm-12 col-md-6 col-lg-12 box-circle bg-white" style="margin-top: 25%;"> <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6"> <img class="img-responsive center-block" ng-src="{{Application.rootURL+'img/hotlibrary-logo.png'}}" alt="HotLibrary Logo" title="Logo"> </div> <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6"> <form ng-submit="forgotPassword? forgot(User, login.$valid) : makeLogin(User, login.$valid)" class="form-horizontal" name="login" novalidate autocomplete="off"> <div class="form-group"> <div ng-class="{'has-error':login.email.$invalid && (login.email.$dirty || login.$submitted),'has-success':login.email.$valid}"> <label class="control-label" for="email">Email:</label> <input id="email" class="form-control" type="email" name="email" ng-model="User.email" ng-exist-email="forgotPassword" ng-required="true" ng-trim="true" autofocus=""> <span ng-if="login.email.$error.required && (login.email.$dirty || login.$submitted)" class="help-block"><i class="fa fa-exclamation-circle"> O campo email é obrigatório</i></span> <span ng-if="login.email.$error.email" class="help-block"><i class="fa fa-exclamation-circle"> Informe um email válido</i></span> <span ng-if="login.email.$valid" class="help-block"><i class="fa fa-check"></i></span> <span ng-if="login.email.$error.emailAsync" class="help-block"><i class="fa fa-exclamation-circle"> O email informado não esta cadastrado no sistema</i></span> </div> </div> <div ng-if="!forgotPassword" class="form-group"> <div ng-class="{'has-error':login.password.$invalid && (login.password.$dirty || login.$submitted), 'has-success':login.password.$valid}"> <label class="control-label" for="password">Senha:</label> <input id="password" class="form-control" type="password" name="password" ng-model="User.password" ng-minlength="8" ng-required="true" ng-trim="true"> <span ng-if="login.password.$error.required && (login.password.$dirty || login.$submitted)" class="help-block"><i class="fa fa-exclamation-circle"> O campo senha é obrigatório</i></span> <span ng-if="login.password.$error.minlength" class="help-block"><i class="fa fa-exclamation-circle"> A senha deve possuir no minimo 8 caracteres</i></span> <span ng-if="login.password.$valid" class="help-block"><i class="fa fa-check"></i></span> </div> </div> <div class="form-group"> <input id="forgotPassword" type="checkbox" name="forgotPassword" ng-value="false" ng-model="forgotPassword"> <label class="control-label" for="forgotPassword">Esqueçeu sua senha?</label> </div> <div class="form-group"> <button class="btn btn-hotlibrary btn-block" type="submit" name="btnMakeLogin" ng-disabled="btnLogin">Fazer Login <i ng-if="btnLogin" class="fa fa-spinner fa-pulse" aria-hidden="false"></i></button> </div> <div class="form-group"> <hot-alert></hot-alert> </div> </form> </div> </div> </div> </div>
{ "content_hash": "4c97bb5c682717e830726a5a9fe4e0f7", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 210, "avg_line_length": 71.48936170212765, "alnum_prop": 0.6220238095238095, "repo_name": "cronodev/hotlibrary", "id": "cefa63ccb1f5d7ecd5d3fa7043d99686cc7d89ae", "size": "3367", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/views/login/login.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4009" }, { "name": "HTML", "bytes": "98366" }, { "name": "JavaScript", "bytes": "63169" }, { "name": "PHP", "bytes": "1844999" } ], "symlink_target": "" }
export { yuan, fixedZero, getTimeDistance, deepGet } from './utils'; export * from './validate'; export * from './validators'; export { LazyService } from './lazy.service'; export { AdUtilsModule } from './utils.module';
{ "content_hash": "6a1e39aa048c15362992fd6d98a47c64", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 68, "avg_line_length": 44.2, "alnum_prop": 0.6968325791855203, "repo_name": "yoryu/cardinn", "id": "81bd6cbc40824870a73b1f79840de3e2dae8f8eb", "size": "221", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/00.core/50.ctrl/utils/index.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "195957" }, { "name": "HTML", "bytes": "16627" }, { "name": "JavaScript", "bytes": "8022" }, { "name": "TypeScript", "bytes": "411225" } ], "symlink_target": "" }
import AFRAME, { THREE } from 'aframe/src'; import debug from 'debug'; import { bind } from 'utils/components'; const warn = debug('app:components:z-trigger:warn'); AFRAME.registerComponent('z-trigger', { dependencies: ['z-entity'], schema: { id: { type: 'string' }, type: { type: 'string' }, _unknownFlag: { type: 'number' }, _unknownVector: { type: 'array' }, kind: { type: 'number' }, params: { type: 'array' }, _unknownString: { type: 'string' }, position: { type: 'array' }, rotation: { type: 'array' }, target: { type: 'array' }, radius: { type: 'number' }, }, init() { this.unbind = bind(this, 'handleComponentChanged', this.el, 'componentchanged'); }, update(oldData) { const { object3D, components } = this.el; const zEntity = components['z-entity']; const { type, position, rotation } = this.data; object3D.position.fromArray(position); object3D.rotation.x = rotation[1] * Math.PI / 2; object3D.rotation.y = Math.atan2(rotation[0], rotation[2]); if (oldData.type !== type) { zEntity.toggleMarker(true); if (this.el.getObject3D('mesh')) { this.el.removeObject3D('mesh'); } switch (type) { case 'UnknownTrigger0': { const { target } = this.data; const geometry = new THREE.SphereBufferGeometry(0.5, 4, 2); const material = new THREE.MeshBasicMaterial({ color: zEntity.getMarkerColor(), wireframe: true, }); const sphere = new THREE.Mesh(geometry, material); sphere.position.fromArray(target).sub(object3D.position); this.el.setObject3D('mesh', sphere); break; } case 'UnknownTrigger1': { const { radius } = this.data; const geometry = new THREE.SphereBufferGeometry(radius, 8, 8); const material = new THREE.MeshBasicMaterial({ color: zEntity.getMarkerColor(), wireframe: true, }); const sphere = new THREE.Mesh(geometry, material); this.el.setObject3D('mesh', sphere); zEntity.toggleMarker(false); break; } case 'UnknownTrigger2': { // Nothing special here break; } default: warn('Unsupported trigger type: %s', type); } } }, remove() { this.el.removeObject3D('mesh'); }, handleComponentChanged(event) { const { name, newData } = event.detail; if (name === 'position') { const { x, y, z } = newData; this.el.setAttribute(this.attrName, 'position', [x, y, z]); } if (name === 'rotation') { const { y } = newData; const { rotation: oldRotation } = this.data; this.el.setAttribute(this.attrName, 'rotation', [ Math.sin(THREE.Math.degToRad(y)), oldRotation[1], Math.cos(THREE.Math.degToRad(y)), ]); } }, });
{ "content_hash": "35f2ece4fca819a0b9d3073b3933fc5a", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 84, "avg_line_length": 31.170212765957448, "alnum_prop": 0.5692832764505119, "repo_name": "kabbi/zanzarah-tools", "id": "f48c521540a0734e46147c85aab47801f67a9284", "size": "2930", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/z-trigger.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "226" }, { "name": "CoffeeScript", "bytes": "125332" }, { "name": "HTML", "bytes": "302" }, { "name": "JavaScript", "bytes": "260183" }, { "name": "Shell", "bytes": "188" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_01.c Label Definition File: CWE789_Uncontrolled_Mem_Alloc__malloc.label.xml Template File: sources-sinks-01.tmpl.c */ /* * @description * CWE: 789 Uncontrolled Memory Allocation * BadSource: listen_socket Read data using a listen socket (server side) * GoodSource: Small number greater than zero * Sinks: * GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated * BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated * Flow Variant: 01 Baseline * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define LISTEN_BACKLOG 5 #define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2) #define HELLO_STRING "hello" #ifndef OMITBAD void CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_01_bad() { size_t data; /* Initialize data */ data = 0; { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; SOCKET listenSocket = INVALID_SOCKET; SOCKET acceptSocket = INVALID_SOCKET; char inputBuffer[CHAR_ARRAY_SIZE]; do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a listen socket */ listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listenSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = INADDR_ANY; service.sin_port = htons(TCP_PORT); if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) { break; } acceptSocket = accept(listenSocket, NULL, NULL); if (acceptSocket == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed */ recvResult = recv(acceptSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* NUL-terminate the string */ inputBuffer[recvResult] = '\0'; /* Convert to unsigned int */ data = strtoul(inputBuffer, NULL, 0); } while (0); if (listenSocket != INVALID_SOCKET) { CLOSE_SOCKET(listenSocket); } if (acceptSocket != INVALID_SOCKET) { CLOSE_SOCKET(acceptSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } { char * myString; /* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough * for the strcpy() function to not cause a buffer overflow */ /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */ if (data > strlen(HELLO_STRING)) { myString = (char *)malloc(data*sizeof(char)); /* Copy a small string into myString */ strcpy(myString, HELLO_STRING); printLine(myString); free(myString); } else { printLine("Input is less than the length of the source string"); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { size_t data; /* Initialize data */ data = 0; /* FIX: Use a relatively small number for memory allocation */ data = 20; { char * myString; /* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough * for the strcpy() function to not cause a buffer overflow */ /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */ if (data > strlen(HELLO_STRING)) { myString = (char *)malloc(data*sizeof(char)); /* Copy a small string into myString */ strcpy(myString, HELLO_STRING); printLine(myString); free(myString); } else { printLine("Input is less than the length of the source string"); } } } /* goodB2G uses the BadSource with the GoodSink */ static void goodB2G() { size_t data; /* Initialize data */ data = 0; { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; SOCKET listenSocket = INVALID_SOCKET; SOCKET acceptSocket = INVALID_SOCKET; char inputBuffer[CHAR_ARRAY_SIZE]; do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a listen socket */ listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listenSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = INADDR_ANY; service.sin_port = htons(TCP_PORT); if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) { break; } acceptSocket = accept(listenSocket, NULL, NULL); if (acceptSocket == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed */ recvResult = recv(acceptSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* NUL-terminate the string */ inputBuffer[recvResult] = '\0'; /* Convert to unsigned int */ data = strtoul(inputBuffer, NULL, 0); } while (0); if (listenSocket != INVALID_SOCKET) { CLOSE_SOCKET(listenSocket); } if (acceptSocket != INVALID_SOCKET) { CLOSE_SOCKET(acceptSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } { char * myString; /* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough * for the strcpy() function to not cause a buffer overflow */ /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */ if (data > strlen(HELLO_STRING) && data < 100) { myString = (char *)malloc(data*sizeof(char)); /* Copy a small string into myString */ strcpy(myString, HELLO_STRING); printLine(myString); free(myString); } else { printLine("Input is less than the length of the source string or too large"); } } } void CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_01_good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_01_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_01_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "content_hash": "3672bf87caee4bca272dce48c50c2544", "timestamp": "", "source": "github", "line_count": 303, "max_line_length": 109, "avg_line_length": 30.7986798679868, "alnum_prop": 0.5489712816116588, "repo_name": "maurer/tiamat", "id": "245f5bbefb7b807996406ee390b766e1278ebfbd", "size": "9332", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "samples/Juliet/testcases/CWE789_Uncontrolled_Mem_Alloc/s01/CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_01.c", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
namespace AjSharpure.Primitives { using System; using System.Collections.Generic; using System.Linq; using System.Text; using AjSharpure.Expressions; using AjSharpure.Language; public class VarPrimitive : IFunction { public bool IsSpecialForm { get { return true; } } public object Apply(Machine machine, ValueEnvironment environment, object[] arguments) { Symbol symbol = (Symbol)arguments[0]; string ns = symbol.Namespace; if (string.IsNullOrEmpty(ns)) ns = (string)environment.GetValue(Machine.CurrentNamespaceKey); Variable variable = machine.GetVariable(ns, symbol.Name); if (variable == null) throw new InvalidOperationException(string.Format("Unable to resolve Variable from Symbol {0}", symbol.FullName)); return variable; } } }
{ "content_hash": "ae368c4532e53b090964a6d00b4b9b8e", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 130, "avg_line_length": 28.02857142857143, "alnum_prop": 0.5942915392456677, "repo_name": "ajlopez/AjSharpure", "id": "c4e7d4cc3ca2c9e39f080fd1e121d45611eda251", "size": "983", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Src/AjSharpure/Primitives/VarPrimitive.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "419575" } ], "symlink_target": "" }
module SpreeShipworks module Xml module Address def to_shipworks_xml(name, context) context.element name do |a| a.element 'FullName', self.full_name a.element 'Company', ""#self.user.try(:company) a.element 'Street1', self.address1 a.element 'Street2', self.address2 a.element 'City', self.city a.element 'State', self.state.try(:abbr) a.element 'PostalCode', self.zipcode a.element 'Country', self.country.try(:iso_name) a.element 'Phone', self.phone a.element 'Fax', '' a.element 'Email', ""#self.user.try(:email) end end end # Address module Note def to_shipworks_xml(context, note) context.element 'Notes' do |n| n.element 'Note', note end end end # Note module Adjustment def to_shipworks_xml(context) if self.amount.present? context.element 'Total', format("%01.2f", self.amount.abs), :id => self.id, :name => self.label, :impact => self.impact end end def impact if amount && amount < 0 'subtract' elsif amount && amount > 0 'add' else 'none' end end end # Adjustment module Creditcard def to_shipworks_xml(context) context.element 'CreditCard' do |cc| cc.element 'Type', self.cc_type || 'unknown' if self.respond_to?(:cc_type) cc.element 'Owner', self.name || '' rescue '' cc.element 'Number', self.display_number || '' rescue '' cc.element 'Expires', self.expires || '' rescue '' cc.element 'CCV', self.verification_value if self.verification_value? rescue '' end end def expires "#{month}/#{year}" if month.present? || year.present? end end # CreditCard module LineItem def to_shipworks_xml(context) context.element 'Item' do |i| i.element 'ItemID', self.id if self.id.present? i.element 'ProductID', self.product.id if self.product.present? i.element 'Code', self.variant.sku if self.variant.present? i.element 'SKU', self.variant.sku if self.variant.present? i.element 'Name', self.variant.name if self.product.present? i.element 'Quantity', self.quantity i.element 'UnitPrice', format("%01.2f", self.price) i.element 'UnitCost', format("%01.2f", self.variant.cost_price) if self.variant.present? && self.variant.cost_price i.element 'Weight', self.variant.weight || 0.0 if self.variant.present? i.element 'Attributes' do |attributes| self.variant.option_values.each do |option| attributes.element 'Attribute' do |attribute| attribute.element 'AttributeID', option.option_type_id attribute.element 'Name', option.option_type.presentation attribute.element 'Value', option.presentation end end self.ad_hoc_option_values.each do |option| attributes.element 'Attribute' do |attribute| attribute.element 'AttributeID', option.ad_hoc_option_type.option_type_id attribute.element 'Name', option.ad_hoc_option_type.option_type.presentation attribute.element 'Value', option.option_value.presentation attribute.element 'Price', option.price_modifier end end if respond_to?(:ad_hoc_option_values) end end end end # LineItem module Order def to_shipworks_xml(context) context.element 'Order' do |order_context| order_context.element 'OrderNumber', self.number order_context.element 'OrderID', self.id order_context.element 'OrderDate', self.completed_at.to_s(:db).gsub(" ", "T") order_context.element 'LastModified', self.updated_at.to_s(:db).gsub(" ", "T") order_context.element 'ShippingMethod', self.shipments.first.try(:shipping_method).try(:name) order_context.element 'StatusCode', self.state order_context.element 'CustomerID', self.user.try(:id) if self.special_instructions.present? self.special_instructions.extend(Note) self.special_instructions.to_shipworks_xml(order_context, self.special_instructions) end if self.ship_address self.ship_address.extend(Address) self.ship_address.to_shipworks_xml('ShippingAddress', order_context) end if self.bill_address self.bill_address.extend(Address) self.bill_address.to_shipworks_xml('BillingAddress', order_context) end if self.payments.first.present? payment = self.payments.first.extend(::SpreeShipworks::Xml::Payment) payment.to_shipworks_xml(order_context) end order_context.element 'Items' do |items_context| self.line_items.each do |item| next if item.quantity == 0 item.extend(LineItem) item.to_shipworks_xml(items_context) if item.variant.present? end end if self.line_items.present? order_context.element 'Totals' do |totals_context| if self.line_item_adjustments.nonzero.exists? self.line_item_adjustments.nonzero.promotion.eligible.each do |promotion| promotion.extend(Adjustment) promotion.to_shipworks_xml(totals_context) end end self.line_item_adjustments.nonzero.tax.eligible.each do |tax| tax.extend(Adjustment) tax.to_shipworks_xml(totals_context) end if self.shipment_adjustments.nonzero.exists? self.shipment_adjustments.nonzero.promotion.eligible.each do |tax| tax.extend(Adjustment) tax.to_shipworks_xml(totals_context) end end self.shipments.each do |shipment| shipment.extend(Shipment) shipment.extend(Adjustment) shipment.to_shipworks_xml(totals_context) end if self.adjustments.nonzero.eligible.exists? self.adjustments.nonzero.eligible.each do |adjustment| adjustment.extend(Adjustment) adjustment.to_shipworks_xml(totals_context) end end end end end end # Order module Payment def to_shipworks_xml(context) context.element 'Payment' do |payment_context| payment_context.element 'Method', self.payment_source.class.name.split("::").last if self.source.present? && self.source.respond_to?(:cc_type) self.source.extend(Creditcard) self.source.to_shipworks_xml(payment_context) end end end end # Payment module Shipment def amount self.cost end def label "shipment cost" end end #SmallShipment end end
{ "content_hash": "e0b189b21ef543c0162aa62082c0a1de", "timestamp": "", "source": "github", "line_count": 204, "max_line_length": 139, "avg_line_length": 37.63235294117647, "alnum_prop": 0.5524293343754071, "repo_name": "bypotatoes/spree_shipworks", "id": "abbe0f5df7d0fcb973d7e750285ece8425f69732", "size": "7677", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/spree_shipworks/xml.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "70" }, { "name": "JavaScript", "bytes": "58" }, { "name": "Ruby", "bytes": "70843" } ], "symlink_target": "" }
/** *============================================================================ * The Ohio State University Research Foundation, The University of Chicago - * Argonne National Laboratory, Emory University, SemanticBits LLC, * and Ekagra Software Technologies Ltd. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cagrid-portal/LICENSE.txt for details. *============================================================================ **/ package gov.nih.nci.cagrid.portal.aggr.catalog; import org.springframework.transaction.annotation.Transactional; /** * User: kherm * * @author kherm manav.kher@semanticbits.com */ @Transactional public class GridServiceEndPointCatalogCreator extends AbstractCatalogCreator { private GridServiceEndPointCatalogCreatorDelegate gridServiceEndPointCatalogCreatorDelegate; /** * Will make sure catalog items exist for all services Run on container * startup * * @throws Exception */ public void afterPropertiesSet() throws Exception { //call delegate to load catalog items gridServiceEndPointCatalogCreatorDelegate.loadCatalogItems(); } // spring getters and setters public GridServiceEndPointCatalogCreatorDelegate getGridServiceEndPointCatalogCreatorDelegate() { return gridServiceEndPointCatalogCreatorDelegate; } public void setGridServiceEndPointCatalogCreatorDelegate( GridServiceEndPointCatalogCreatorDelegate gridServiceEndPointCatalogCreatorDelegate) { this.gridServiceEndPointCatalogCreatorDelegate = gridServiceEndPointCatalogCreatorDelegate; } }
{ "content_hash": "d3ac79689df027a5171bc029e6620831", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 101, "avg_line_length": 36, "alnum_prop": 0.7135802469135802, "repo_name": "NCIP/cagrid-portal", "id": "304b6cb4e989e2902be64caff8c7f56ebefe37a7", "size": "1620", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cagrid-portal/aggr/src/java/gov/nih/nci/cagrid/portal/aggr/catalog/GridServiceEndPointCatalogCreator.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "2937842" }, { "name": "JavaScript", "bytes": "94652" }, { "name": "Logos", "bytes": "64766" }, { "name": "Shell", "bytes": "31573" }, { "name": "XSLT", "bytes": "69341" } ], "symlink_target": "" }
#ifndef mitkFillRegionTool_h_Included #define mitkFillRegionTool_h_Included #include "mitkSetRegionTool.h" #include <MitkSegmentationExports.h> namespace us { class ModuleResource; } namespace mitk { /** \brief Fill the inside of a contour with 1 \sa SetRegionTool \ingroup Interaction \ingroup ToolManagerEtAl Finds the outer contour of a shape in 2D (possibly including holes) and sets all the inside pixels to 1, filling holes in a segmentation. \warning Only to be instantiated by mitk::ToolManager. $Author$ */ class MITKSEGMENTATION_EXPORT FillRegionTool : public SetRegionTool { public: mitkClassMacro(FillRegionTool, SetRegionTool); itkFactorylessNewMacro(Self) itkCloneMacro(Self) virtual const char** GetXPM() const override; virtual us::ModuleResource GetCursorIconResource() const override; us::ModuleResource GetIconResource() const override; virtual const char* GetName() const override; protected: FillRegionTool(); // purposely hidden virtual ~FillRegionTool(); }; } // namespace #endif
{ "content_hash": "8d74a7b422bfff2d752d66ab83e510c6", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 82, "avg_line_length": 19.618181818181817, "alnum_prop": 0.7479147358665431, "repo_name": "ireicht/MITK-CSI", "id": "b86aae31ddcf18c2ae88d701cd5ab72931953965", "size": "1577", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "Modules/Segmentation/Interactions/mitkFillRegionTool.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "2311235" }, { "name": "C++", "bytes": "27586404" }, { "name": "CMake", "bytes": "837213" }, { "name": "CSS", "bytes": "12562" }, { "name": "HTML", "bytes": "6469" }, { "name": "JavaScript", "bytes": "47658" }, { "name": "Makefile", "bytes": "6216" }, { "name": "Objective-C", "bytes": "476198" }, { "name": "Python", "bytes": "51103" }, { "name": "QMake", "bytes": "5583" }, { "name": "Shell", "bytes": "1259" } ], "symlink_target": "" }
import {Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges} from '@angular/core'; import * as THREE from 'three'; import { BoxGeometry, Line, Mesh, MeshBasicMaterial, Object3D, Scene, Vector2, Vector3, WebGLRenderer } from 'three'; import * as TWEEN from '@tweenjs/tween.js'; import {Subscription} from 'rxjs'; import {OrbitControls} from 'three-orbitcontrols-ts'; import {AbstractView} from '../view/abstract-view'; import {SplitView} from '../view/split-view'; import {MergedView} from '../view/merged-view'; import {IFilter} from '../../interfaces/IFilter'; import {InteractionHandler} from '../interaction-handler/interaction-handler'; import {VisualizationConfig} from '../../VisualizationConfig'; import {INode} from '../../interfaces/INode'; import {FocusService} from '../../service/focus.service'; import {TooltipService} from '../../service/tooltip.service'; import {IMetricMapping} from '../../interfaces/IMetricMapping'; import {ComparisonPanelService} from '../../service/comparison-panel.service'; import {ScreenType} from '../../enum/ScreenType'; import {ViewType} from '../../enum/ViewType'; import {BlockConnection} from '../../geometry/block-connection'; import {NodeType} from '../../enum/NodeType'; import {ElementAnalyzer} from '../../helper/element-analyzer'; import {ScreenInteractionService} from '../../service/screen-interaction.service'; import {ChangetypeSymbols} from '../changetype-symbols/changetype-symbols'; @Component({ selector: 'app-screen', templateUrl: './screen.component.html', styleUrls: ['./screen.component.scss'] }) export class ScreenComponent implements OnInit, OnChanges, OnDestroy { constructor( private focusService: FocusService, private screenInteractionService: ScreenInteractionService, private tooltipService: TooltipService, private comparisonPanelService: ComparisonPanelService ) { } @Input() screenType: ScreenType; @Input() activeViewType: ViewType; @Input() activeFilter: IFilter; @Input() metricTree: INode; @Input() metricMapping: IMetricMapping; subscriptions: Subscription[] = []; renderer: WebGLRenderer; scene: Scene = new Scene(); // (see https://github.com/nicolaspanel/three-orbitcontrols-ts/issues/1) camera: THREE.PerspectiveCamera; controls: OrbitControls; spatialCursor: Object3D; highlightBoxes: Object3D[] = []; interactionHandler: InteractionHandler; changetypeSymbols: ChangetypeSymbols; public displayTooltip = true; // use THREE.PerspectiveCamera instead of importing PerspectiveCamera to avoid warning for panning and zooming are disabled view: AbstractView; private isMergedView = false; private requestAnimationFrameId: number; private renderingIsPaused = false; private screenOffset: Vector2 = new Vector2(); private screenDimensions: Vector2 = new Vector2(); private highlightBoxGeometry: BoxGeometry; private highlightBoxMaterial: MeshBasicMaterial; ngOnChanges(changes: SimpleChanges) { if (this.activeViewType !== null && this.metricTree !== null && this.activeFilter !== null) { this.isMergedView = this.activeViewType === ViewType.MERGED; this.interactionHandler.setIsMergedView(this.isMergedView); if (this.isMergedView) { this.view = new MergedView(this.screenType, this.metricMapping); if (this.screenType === ScreenType.RIGHT) { this.pauseRendering(); this.displayTooltip = false; } document.querySelector('#stage').classList.remove('split'); } else { this.view = new SplitView(this.screenType, this.metricMapping); if (this.screenType === ScreenType.RIGHT) { this.resumeRendering(); this.displayTooltip = true; } document.querySelector('#stage').classList.add('split'); } this.resetScene(); this.prepareView(this.metricTree); this.applyFilter(this.activeFilter); this.handleViewChanged(); } if ( changes.metricTree && changes.metricTree.currentValue && ElementAnalyzer.hasMetricValuesForCurrentCommit( changes.metricTree.currentValue, this.activeViewType === ViewType.MERGED, this.screenType ) ) { this.resetCamera(); this.resetControls(); } } ngOnInit() { this.tooltipService.addScreen(this); this.screenInteractionService.addScreen(this); this.view = new SplitView(this.screenType, this.metricMapping); this.createCamera(); this.createControls(); this.createLight(); this.createRenderer(); this.create3DCursor(); this.createSelectionHighlightBox(); this.createInteractionHandler(); this.changetypeSymbols = new ChangetypeSymbols(); this.initializeEventListeners(); this.render(); this.subscriptions.push( this.focusService.elementFocussed$.subscribe((elementName) => { this.focusElementByName(elementName); this.comparisonPanelService.show({ elementName, foundElement: ElementAnalyzer.findElementByName(this.metricTree, elementName) }); }) ); this.subscriptions.push( this.screenInteractionService.highlightedElements$.subscribe((highlightedElements) => { if (this.highlightBoxes.length < highlightedElements.length) { for (let i = 0; i < highlightedElements.length - this.highlightBoxes.length; i++) { this.highlightBoxes.push(this.createSelectionHighlightBox()); } } this.highlightBoxes.forEach((value, index) => this.highlightElement(this.scene.getObjectByName(highlightedElements[index]), value)); }) ); this.subscriptions.push( this.screenInteractionService.cursorState$.subscribe((state => { if (state.position) { this.spatialCursor.position.copy(state.position); this.tooltipService.setMousePosition(this.getTooltipPosition(), this.screenType); } this.spatialCursor.visible = state.visible; if (state.scale) { this.spatialCursor.scale.set(1, state.scale, 1); this.spatialCursor.children[0].scale.set(state.scale, 1, state.scale); } })) ); } public highlightElement(element: Object3D, highlightBox: Object3D) { const addedMargin = VisualizationConfig.HIGHLIGHT_BOX_MARGIN; if (element) { highlightBox.visible = true && element.visible; highlightBox.position.copy(new Vector3(element.position.x + element.scale.x / 2, element.position.y + element.scale.y / 2, element.position.z + element.scale.z / 2)); highlightBox.scale.copy(element.scale).addScalar(addedMargin); } else { highlightBox.visible = false; } } ngOnDestroy() { this.subscriptions.forEach((subscription: Subscription) => { subscription.unsubscribe(); }); } createRenderer() { this.renderer = new WebGLRenderer({antialias: true, preserveDrawingBuffer: true, logarithmicDepthBuffer: true}); this.renderer.setClearColor(0xf0f0f0); this.renderer.setSize(this.getScreenWidth() - 0, window.innerHeight); document.querySelector('#stage').appendChild(this.renderer.domElement); } updateRenderer() { this.renderer.setSize(this.getScreenWidth() - 0, window.innerHeight); } createLight() { const ambientLight = new THREE.AmbientLight(0xcccccc, 0.5); this.scene.add(ambientLight); const directionalLight = new THREE.DirectionalLight(0xffffff, 0.4); directionalLight.position.set(0, 1, 0); this.scene.add(directionalLight); } createCamera() { this.camera = new THREE.PerspectiveCamera( 45, (this.getScreenWidth() - 0) / window.innerHeight, VisualizationConfig.CAMERA_NEAR, VisualizationConfig.CAMERA_FAR ); this.scene.add(this.camera); } updateCamera() { this.camera.aspect = (this.getScreenWidth() - 0) / window.innerHeight; this.camera.updateProjectionMatrix(); } resetCamera() { const root = this.getRoot(); if (!root) {return; } // pythagoras const diagonal = Math.sqrt(Math.pow(root.scale.x, 2) + Math.pow(root.scale.z, 2)); this.camera.position.x = root.scale.x * 2; this.camera.position.y = diagonal * 1.5; this.camera.position.z = root.scale.z * 2; } createControls() { this.controls = new OrbitControls(this.camera, document.querySelector('#stage') as HTMLElement); } resetControls() { const centralCoordinates = this.getCentralCoordinates(); this.controls.target.x = centralCoordinates.x; this.controls.target.y = centralCoordinates.y; this.controls.target.z = centralCoordinates.z; } render() { this.requestAnimationFrameId = requestAnimationFrame(() => { this.render(); }); // Canvas object offset this.screenOffset.set(this.renderer.domElement.getBoundingClientRect().left, this.renderer.domElement.getBoundingClientRect().top); // Canvas object size this.screenDimensions.set(this.renderer.domElement.getBoundingClientRect().width, this.renderer.domElement.getBoundingClientRect().height); this.controls.update(); this.renderer.render(this.scene, this.camera); this.interactionHandler.update(this.camera); TWEEN.update(); } pauseRendering() { if (this.requestAnimationFrameId) { cancelAnimationFrame(this.requestAnimationFrameId); this.resetScene(); this.renderingIsPaused = true; } } resumeRendering() { if (this.renderingIsPaused) { this.render(); this.renderingIsPaused = false; } } prepareView(metricTree) { if (metricTree.children.length === 0) { return; } this.view.setMetricTree(metricTree); this.view.recalculate(); this.view.getBlockElements().forEach((element) => { this.scene.add(element); }); if (this.view instanceof MergedView) { this.view.calculateConnections(this.scene); this.view.getConnections().forEach((blockConnection: BlockConnection) => { this.scene.add(blockConnection.getCurve()); }); } else { this.changetypeSymbols.addChangeTypeSymbols(this.scene); } } createInteractionHandler() { this.interactionHandler = new InteractionHandler( this.scene, this.renderer, this.screenType, this.isMergedView, this.focusService, this.screenInteractionService, this.tooltipService, this.spatialCursor ); } resetScene() { for (let i = this.scene.children.length - 1; i >= 0; i--) { const child = this.scene.children[i]; // only remove Blocks and Lines. Don't remove lights, cameras etc. if (child.type === 'Mesh' || child.type === 'Line') { this.scene.remove(child); } } } focusElementByName(elementName) { const element = this.scene.getObjectByName(elementName); if (!element) { return; } const root = this.getRoot(); // pythagoras const diagonal = Math.sqrt(Math.pow(root.scale.x, 2) + Math.pow(root.scale.z, 2)); new TWEEN.Tween(this.camera.position) .to({ x: element.position.x + root.scale.x / 5, y: element.position.y + diagonal / 5, z: element.position.z + root.scale.z / 5 }, VisualizationConfig.CAMERA_ANIMATION_DURATION) .easing(TWEEN.Easing.Sinusoidal.InOut) .start(); new TWEEN.Tween(this.controls.target) .to({ x: element.position.x + element.scale.x / 2, y: element.position.y, z: element.position.z + element.scale.z / 2 }, VisualizationConfig.CAMERA_ANIMATION_DURATION) .easing(TWEEN.Easing.Sinusoidal.InOut) .start(); } private getCentralCoordinates() { const root = this.getRoot(); if (!root) { console.warn(`no root found in screen #${this.screenType}`); return; } return { x: root.scale.x / 2, y: 0, z: root.scale.z / 2 }; } private getRoot(): Object3D { return this.scene.getObjectByName(VisualizationConfig.ROOT_NAME); } private getScreenWidth() { if (this.isMergedView) { return window.innerWidth; } return window.innerWidth / 2; } private initializeEventListeners() { window.addEventListener('resize', this.handleViewChanged.bind(this), false); } private handleViewChanged() { this.updateCamera(); this.updateRenderer(); } private applyFilter(activeFilter: IFilter) { for (let i = this.scene.children.length - 1; i >= 0; i--) { const node = this.scene.children[i]; if (node.userData && (node.userData.type === NodeType.FILE || node.userData.type === NodeType.CONNECTION)) { node.visible = true; if ( activeFilter.unmodified === false && node.userData.changeTypes && node.userData.changeTypes.modified === false && node.userData.changeTypes.deleted === false && node.userData.changeTypes.added === false && node.userData.changeTypes.renamed === false ) { node.visible = false; } if (activeFilter.modified === false && node.userData.changeTypes && node.userData.changeTypes.modified === true) { node.visible = false; } if (activeFilter.deleted === false && node.userData.changeTypes && node.userData.changeTypes.deleted === true) { node.visible = false; } if (activeFilter.added === false && node.userData.changeTypes && node.userData.changeTypes.added === true) { node.visible = false; } if (activeFilter.renamed === false && node.userData.changeTypes && node.userData.changeTypes.renamed === true) { node.visible = false; } } } } public getTooltipPosition(): {x: number, y: number} { const tooltipPosition: Vector2 = this.worldPositionToScreenPosition(this.spatialCursor.position.clone().add(new Vector3(0, this.spatialCursor.scale.y, 0))); return {x: tooltipPosition.x, y: tooltipPosition.y}; } public worldPositionToScreenPosition(worldPosition: Vector3): Vector2 { const screenCoordinate: Vector3 = worldPosition.project(this.camera); const screenPosition: Vector2 = new Vector2( this.screenOffset.x + ((screenCoordinate.x + 1) * this.screenDimensions.x / 2), ((-(screenCoordinate.y - 1) * this.screenDimensions.y / 2))); return screenPosition; } private create3DCursor() { const material = new THREE.MeshBasicMaterial({ color: 0xff0000 }); const geometry = new THREE.Geometry(); geometry.vertices.push( new Vector3(0, 0, 0), new Vector3(0, 1, 0) ); const tipSize = 0.2; const tipGeometry = new THREE.ConeGeometry(tipSize / 2, tipSize, 16, 16); tipGeometry.rotateX(Math.PI); tipGeometry.translate(0, tipSize / 2, 0); this.spatialCursor = new Line(geometry, material); const tooltipLineTip = new Mesh(tipGeometry, material); this.spatialCursor.add(tooltipLineTip); this.spatialCursor.type = 'TooltipLine'; this.spatialCursor.visible = false; this.spatialCursor.userData.isHelper = true; this.scene.add(this.spatialCursor); } private createSelectionHighlightBox(): Object3D { let highlightBox: Object3D; if (!this.highlightBoxMaterial) { this.highlightBoxMaterial = new THREE.MeshBasicMaterial({ color: 0x01ff01, opacity: .8, transparent: true }); } if (!this.highlightBoxGeometry) {this.highlightBoxGeometry = new THREE.BoxGeometry(1, 1, 1); } highlightBox = new Mesh(this.highlightBoxGeometry, this.highlightBoxMaterial); highlightBox.type = 'HighlightBox'; highlightBox.visible = false; highlightBox.userData.isHelper = true; this.scene.add(highlightBox); return highlightBox; } }
{ "content_hash": "c65c3549fd5115d30b136b193da3b718", "timestamp": "", "source": "github", "line_count": 480, "max_line_length": 140, "avg_line_length": 32.920833333333334, "alnum_prop": 0.6728262245285407, "repo_name": "reflectoring/coderadar", "id": "51da009b35ece26604877ce6191042fea7542963", "size": "15802", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "coderadar-ui/src/app/city-map/visualization/screen/screen.component.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "61389" }, { "name": "HTML", "bytes": "44707" }, { "name": "Java", "bytes": "972349" }, { "name": "JavaScript", "bytes": "1748" }, { "name": "Perl", "bytes": "9981" }, { "name": "Shell", "bytes": "46559" }, { "name": "TypeScript", "bytes": "274109" } ], "symlink_target": "" }
package de.lazyheroproductions.campuscardreader.UI; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.webkit.WebView; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.TextView; import de.lazyheroproductions.campuscardreader.BuildConfig; import de.lazyheroproductions.campuscardreader.Config; import de.lazyheroproductions.campuscardreader.Logic.CreditDatabase; import de.lazyheroproductions.campuscardreader.R; public class SettingsActivity extends AppCompatActivity implements View.OnClickListener{ private static final String LICENSE_FILE_PATH = "file:///android_asset/license.html"; private static final String SHARED_PREFERENCES_KEY = "unitSharedPreferences"; private static final String CURRENCY_UNIT_KEY = "unit"; private static final String ORDER_KEY = "order"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); if(getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } ((TextView)findViewById(R.id.app_version_textview)).setText(getString(R.string.app_version) + " " + BuildConfig.VERSION_NAME); ((EditText)findViewById(R.id.currency_edittext)).setText(getUnit(this)); ((EditText)findViewById(R.id.currency_edittext)).addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { SettingsActivity.saveUnit(getApplicationContext(), s.toString()); } }); CheckBox graphOrderCheckBox = (CheckBox)findViewById(R.id.graph_order_checkbox); if(isOrderByOldestFirst(this)){ graphOrderCheckBox.setChecked(true); } ((CheckBox)findViewById(R.id.graph_order_checkbox)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { saveOrder(getApplicationContext(),b); } }); //onclicklistener! findViewById(R.id.see_source_button).setOnClickListener(this); findViewById(R.id.about_screen_rate_button).setOnClickListener(this); findViewById(R.id.visit_website_button).setOnClickListener(this); findViewById(R.id.reset_database_button).setOnClickListener(this); findViewById(R.id.license_button).setOnClickListener(this); } @Override public void onClick(View v){ switch(v.getId()){ case R.id.see_source_button: startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Config.PROJECT_HOME))); break; case R.id.visit_website_button: startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Config.AUTHOR_WEBSITE))); break; case R.id.about_screen_rate_button: onRateClick(); break; case R.id.reset_database_button: onDeleteDbClick(); break; case R.id.license_button: onLicenseClick(); break; case View.NO_ID: break; } } private void onRateClick(){ // send the user to the play store or otherwise to the play web store Uri uri = Uri.parse(Config.PLAY_STORE_URI + getPackageName()); Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri); try { startActivity(goToMarket); } catch (ActivityNotFoundException e) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Config.WEB_PLAY_STORE_URL + getPackageName()))); } } private void onDeleteDbClick(){ new AlertDialog.Builder(this) .setTitle(R.string.reset_database) .setMessage(R.string.really_delete_data) .setPositiveButton(R.string.reset_database, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { CreditDatabase cDb = new CreditDatabase(getApplicationContext()); cDb.resetDatabase(); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); } private void onLicenseClick(){ WebView wv = new WebView(this); wv.loadUrl(LICENSE_FILE_PATH); AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.setTitle(R.string.license) .setView(wv) .setPositiveButton(R.string.close, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }) .show(); } public static void saveUnit(Context activityContext, String unitString){ SharedPreferences.Editor editor = getPrefs(activityContext).edit(); editor.putString(CURRENCY_UNIT_KEY, unitString); editor.apply(); } public static String getUnit(Context activityContext){ return getPrefs(activityContext).getString(CURRENCY_UNIT_KEY, activityContext.getString(R.string.currency)); } public static void saveOrder(Context activityContext, boolean orderByOldestFirst){ SharedPreferences.Editor editor = getPrefs(activityContext).edit(); editor.putBoolean(ORDER_KEY, orderByOldestFirst); editor.apply(); } public static boolean isOrderByOldestFirst(Context activityContext){ return getPrefs(activityContext).getBoolean(ORDER_KEY, true); } private static SharedPreferences getPrefs(Context c){ return c.getSharedPreferences(SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE); } }
{ "content_hash": "544effbd948d100d11261846cc672cf4", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 134, "avg_line_length": 40.266666666666666, "alnum_prop": 0.667519566526189, "repo_name": "ueman/CampusCardReader", "id": "52fce8ae04443456815003403ebea5c02c08f3a0", "size": "7232", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/de/lazyheroproductions/campuscardreader/UI/SettingsActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "888" }, { "name": "Java", "bytes": "61640" } ], "symlink_target": "" }
package common import ( "sync" "time" ) // Key type used in the cache. type Key interface{} // Value type held in the cache. Cannot be nil. type Value interface{} // RemovalListener is the callback function type that can be registered with // the cache to receive notification of the removal of expired elements. type RemovalListener func(k Key, v Value) // Clock is the function type used to get the current time. type clock func() time.Time // element represents an element stored in the cache. type element struct { expiration time.Time timeout time.Duration value Value } // IsExpired returns true if the element is expired (current time is greater // than the expiration time). func (e *element) IsExpired(now time.Time) bool { return now.After(e.expiration) } // UpdateLastAccessTime updates the expiration time of the element. This // should be called each time the element is accessed. func (e *element) UpdateLastAccessTime(now time.Time, expiration time.Duration) { e.expiration = now.Add(expiration) } // Cache is a semi-persistent mapping of keys to values. Elements added to the // cache are store until they are explicitly deleted or are expired due time- // based eviction based on last access time. // // Expired elements are not visible through classes methods, but they do remain // stored in the cache until CleanUp() is invoked. Therefore CleanUp() must be // invoked periodically to prevent the cache from becoming a memory leak. If // you want to start a goroutine to perform periodic clean-up then see // StartJanitor(). // // Cache does not support storing nil values. Any attempt to put nil into // the cache will cause a panic. type Cache struct { sync.RWMutex timeout time.Duration // Length of time before cache elements expire. elements map[Key]*element // Data stored by the cache. clock clock // Function used to get the current time. listener RemovalListener // Callback listen to notify of evictions. janitorQuit chan struct{} // Closing this channel stop the janitor. } // NewCache creates and returns a new Cache. d is the length of time after last // access that cache elements expire. initialSize is the initial allocation size // used for the Cache's underlying map. func NewCache(d time.Duration, initialSize int) *Cache { return newCache(d, initialSize, nil, time.Now) } // NewCacheWithRemovalListener creates and returns a new Cache and register a // RemovalListener callback function. d is the length of time after last access // that cache elements expire. initialSize is the initial allocation size used // for the Cache's underlying map. l is the callback function that will be // invoked when cache elements are removed from the map on CleanUp. func NewCacheWithRemovalListener(d time.Duration, initialSize int, l RemovalListener) *Cache { return newCache(d, initialSize, l, time.Now) } func newCache(d time.Duration, initialSize int, l RemovalListener, t clock) *Cache { return &Cache{ timeout: d, elements: make(map[Key]*element, initialSize), listener: l, clock: t, } } // PutIfAbsent writes the given key and value to the cache only if the key is // absent from the cache. Nil is returned if the key-value pair were written, // otherwise the old value is returned. func (c *Cache) PutIfAbsent(k Key, v Value) Value { return c.PutIfAbsentWithTimeout(k, v, 0) } // PutIfAbsentWithTimeout writes the given key and value to the cache only if // the key is absent from the cache. Nil is returned if the key-value pair were // written, otherwise the old value is returned. // The cache expiration time will be overwritten by timeout of the key being // inserted. func (c *Cache) PutIfAbsentWithTimeout(k Key, v Value, timeout time.Duration) Value { c.Lock() defer c.Unlock() oldValue, exists := c.get(k) if exists { return oldValue } c.put(k, v, timeout) return nil } // Put writes the given key and value to the map replacing any existing value // if it exists. The previous value associated with the key returned or nil // if the key was not present. func (c *Cache) Put(k Key, v Value) Value { return c.PutWithTimeout(k, v, 0) } // PutWithTimeout writes the given key and value to the map replacing any // existing value if it exists. The previous value associated with the key // returned or nil if the key was not present. // The cache expiration time will be overwritten by timeout of the key being // inserted. func (c *Cache) PutWithTimeout(k Key, v Value, timeout time.Duration) Value { c.Lock() defer c.Unlock() oldValue, _ := c.get(k) c.put(k, v, timeout) return oldValue } // Replace overwrites the value for a key only if the key exists. The old // value is returned if the value is updated, otherwise nil is returned. func (c *Cache) Replace(k Key, v Value) Value { return c.ReplaceWithTimeout(k, v, 0) } // ReplaceWithTimeout overwrites the value for a key only if the key exists. The // old value is returned if the value is updated, otherwise nil is returned. // The cache expiration time will be overwritten by timeout of the key being // inserted. func (c *Cache) ReplaceWithTimeout(k Key, v Value, timeout time.Duration) Value { c.Lock() defer c.Unlock() oldValue, exists := c.get(k) if !exists { return nil } c.put(k, v, timeout) return oldValue } // Get the current value associated with a key or nil if the key is not // present. The last access time of the element is updated. func (c *Cache) Get(k Key) Value { c.RLock() defer c.RUnlock() v, _ := c.get(k) return v } // Delete a key from the map and return the value or nil if the key does // not exist. The RemovalListener is not notified for explicit deletions. func (c *Cache) Delete(k Key) Value { c.Lock() defer c.Unlock() v, _ := c.get(k) delete(c.elements, k) return v } // CleanUp performs maintenance on the cache by removing expired elements from // the cache. If a RemoveListener is registered it will be invoked for each // element that is removed during this clean up operation. The RemovalListener // is invoked on the caller's goroutine. func (c *Cache) CleanUp() int { c.Lock() defer c.Unlock() count := 0 for k, v := range c.elements { if v.IsExpired(c.clock()) { delete(c.elements, k) count++ if c.listener != nil { c.listener(k, v.value) } } } return count } // Entries returns a shallow copy of the non-expired elements in the cache. func (c *Cache) Entries() map[Key]Value { c.RLock() defer c.RUnlock() copy := make(map[Key]Value, len(c.elements)) for k, v := range c.elements { if !v.IsExpired(c.clock()) { copy[k] = v.value } } return copy } // Size returns the number of elements in the cache. The number includes both // active elements and expired elements that have not been cleaned up. func (c *Cache) Size() int { c.RLock() defer c.RUnlock() return len(c.elements) } // StartJanitor starts a goroutine that will periodically invoke the cache's // CleanUp() method. func (c *Cache) StartJanitor(interval time.Duration) { ticker := time.NewTicker(interval) c.janitorQuit = make(chan struct{}) go func() { for { select { case <-ticker.C: c.CleanUp() case <-c.janitorQuit: ticker.Stop() return } } }() } // StopJanitor stops the goroutine created by StartJanitor. func (c *Cache) StopJanitor() { close(c.janitorQuit) } // get returns the non-expired values from the cache. func (c *Cache) get(k Key) (Value, bool) { elem, exists := c.elements[k] now := c.clock() if exists && !elem.IsExpired(now) { elem.UpdateLastAccessTime(now, elem.timeout) return elem.value, true } return nil, false } // put writes a key-value to the cache replacing any existing mapping. func (c *Cache) put(k Key, v Value, timeout time.Duration) { if v == nil { panic("Cache does not support storing nil values.") } if timeout <= 0 { timeout = c.timeout } c.elements[k] = &element{ expiration: c.clock().Add(timeout), timeout: timeout, value: v, } }
{ "content_hash": "39923483a83115d92cac29457fdd3932", "timestamp": "", "source": "github", "line_count": 260, "max_line_length": 94, "avg_line_length": 30.815384615384616, "alnum_prop": 0.7192960559161258, "repo_name": "lflxp/sflowtool", "id": "25f3be7d92b4e3a865ea709304812dc9f0a6ee24", "size": "8806", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/github.com/elastic/beats/libbeat/common/cache.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "89382" } ], "symlink_target": "" }
package mailchimp import ( "bytes" "encoding/json" "fmt" "io" "net/http" "net/url" "regexp" "sync" "time" "github.com/influxdata/telegraf" ) const ( reportsEndpoint string = "/3.0/reports" reportsEndpointCampaign string = "/3.0/reports/%s" ) var mailchimpDatacenter = regexp.MustCompile("[a-z]+[0-9]+$") type ChimpAPI struct { Transport http.RoundTripper debug bool sync.Mutex url *url.URL log telegraf.Logger } type ReportsParams struct { Count string Offset string SinceSendTime string BeforeSendTime string } func (p *ReportsParams) String() string { v := url.Values{} if p.Count != "" { v.Set("count", p.Count) } if p.Offset != "" { v.Set("offset", p.Offset) } if p.BeforeSendTime != "" { v.Set("before_send_time", p.BeforeSendTime) } if p.SinceSendTime != "" { v.Set("since_send_time", p.SinceSendTime) } return v.Encode() } func NewChimpAPI(apiKey string, log telegraf.Logger) *ChimpAPI { u := &url.URL{} u.Scheme = "https" u.Host = fmt.Sprintf("%s.api.mailchimp.com", mailchimpDatacenter.FindString(apiKey)) u.User = url.UserPassword("", apiKey) return &ChimpAPI{url: u, log: log} } type APIError struct { Status int `json:"status"` Type string `json:"type"` Title string `json:"title"` Detail string `json:"detail"` Instance string `json:"instance"` } func (e APIError) Error() string { return fmt.Sprintf("ERROR %v: %v. See %v", e.Status, e.Title, e.Type) } func chimpErrorCheck(body []byte) error { var e APIError if err := json.Unmarshal(body, &e); err != nil { return err } if e.Title != "" || e.Status != 0 { return e } return nil } func (a *ChimpAPI) GetReports(params ReportsParams) (ReportsResponse, error) { a.Lock() defer a.Unlock() a.url.Path = reportsEndpoint var response ReportsResponse rawjson, err := a.runChimp(params) if err != nil { return response, err } err = json.Unmarshal(rawjson, &response) if err != nil { return response, err } return response, nil } func (a *ChimpAPI) GetReport(campaignID string) (Report, error) { a.Lock() defer a.Unlock() a.url.Path = fmt.Sprintf(reportsEndpointCampaign, campaignID) var response Report rawjson, err := a.runChimp(ReportsParams{}) if err != nil { return response, err } err = json.Unmarshal(rawjson, &response) if err != nil { return response, err } return response, nil } func (a *ChimpAPI) runChimp(params ReportsParams) ([]byte, error) { client := &http.Client{ Transport: a.Transport, Timeout: 4 * time.Second, } var b bytes.Buffer req, err := http.NewRequest("GET", a.url.String(), &b) if err != nil { return nil, err } req.URL.RawQuery = params.String() req.Header.Set("User-Agent", "Telegraf-MailChimp-Plugin") if a.debug { a.log.Debugf("request URL: %s", req.URL.String()) } resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { // ignore the err here; LimitReader returns io.EOF and we're not interested in read errors. body, _ := io.ReadAll(io.LimitReader(resp.Body, 200)) return nil, fmt.Errorf("%s returned HTTP status %s: %q", a.url.String(), resp.Status, body) } body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } if a.debug { a.log.Debugf("response Body: %q", string(body)) } if err = chimpErrorCheck(body); err != nil { return nil, err } return body, nil } type ReportsResponse struct { Reports []Report `json:"reports"` TotalItems int `json:"total_items"` } type Report struct { ID string `json:"id"` CampaignTitle string `json:"campaign_title"` Type string `json:"type"` EmailsSent int `json:"emails_sent"` AbuseReports int `json:"abuse_reports"` Unsubscribed int `json:"unsubscribed"` SendTime string `json:"send_time"` TimeSeries []TimeSeries Bounces Bounces `json:"bounces"` Forwards Forwards `json:"forwards"` Opens Opens `json:"opens"` Clicks Clicks `json:"clicks"` FacebookLikes FacebookLikes `json:"facebook_likes"` IndustryStats IndustryStats `json:"industry_stats"` ListStats ListStats `json:"list_stats"` } type Bounces struct { HardBounces int `json:"hard_bounces"` SoftBounces int `json:"soft_bounces"` SyntaxErrors int `json:"syntax_errors"` } type Forwards struct { ForwardsCount int `json:"forwards_count"` ForwardsOpens int `json:"forwards_opens"` } type Opens struct { OpensTotal int `json:"opens_total"` UniqueOpens int `json:"unique_opens"` OpenRate float64 `json:"open_rate"` LastOpen string `json:"last_open"` } type Clicks struct { ClicksTotal int `json:"clicks_total"` UniqueClicks int `json:"unique_clicks"` UniqueSubscriberClicks int `json:"unique_subscriber_clicks"` ClickRate float64 `json:"click_rate"` LastClick string `json:"last_click"` } type FacebookLikes struct { RecipientLikes int `json:"recipient_likes"` UniqueLikes int `json:"unique_likes"` FacebookLikes int `json:"facebook_likes"` } type IndustryStats struct { Type string `json:"type"` OpenRate float64 `json:"open_rate"` ClickRate float64 `json:"click_rate"` BounceRate float64 `json:"bounce_rate"` UnopenRate float64 `json:"unopen_rate"` UnsubRate float64 `json:"unsub_rate"` AbuseRate float64 `json:"abuse_rate"` } type ListStats struct { SubRate float64 `json:"sub_rate"` UnsubRate float64 `json:"unsub_rate"` OpenRate float64 `json:"open_rate"` ClickRate float64 `json:"click_rate"` } type TimeSeries struct { TimeStamp string `json:"timestamp"` EmailsSent int `json:"emails_sent"` UniqueOpens int `json:"unique_opens"` RecipientsClick int `json:"recipients_click"` }
{ "content_hash": "0524f161a95cedcc4977bbbe811f3bcb", "timestamp": "", "source": "github", "line_count": 248, "max_line_length": 93, "avg_line_length": 23.56451612903226, "alnum_prop": 0.6642710472279261, "repo_name": "influxdata/telegraf", "id": "71e7bcea6d53553df0a55c8ebb6c9a67f448535f", "size": "5844", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "plugins/inputs/mailchimp/chimp_api.go", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "1067" }, { "name": "Go", "bytes": "9722072" }, { "name": "Makefile", "bytes": "15617" }, { "name": "PowerShell", "bytes": "1385" }, { "name": "Ragel", "bytes": "10377" }, { "name": "Ruby", "bytes": "1981" }, { "name": "Shell", "bytes": "32388" } ], "symlink_target": "" }
/*! * REasy UI Validate @VERSION * * Depends: * reasy-ui-core.js * reasy-ui-checker.js */ (function () {"use strict"; var defaults = { wrapElem: $('body'), custom: null, success: function () {}, error: function () {} }; function Validate(options) { this.options = $.extend({}, defaults, options); this.$elems = $(this.options.wrapElem).find(".validatebox"); this.init(); } Validate.prototype.init = function() { this.$elems.addCheck(); } Validate.prototype.checkAll = function() { var checkPass = true, customResult; this.$elems.each(function() { //有错误信息返回,既不返回undefined->验证不通过 if ($(this).check()) { checkPass = false; } }); if (checkPass) { if (typeof this.options.custom === 'function') { customResult = this.options.custom(); } if (!customResult) { if (typeof this.options.success === 'function') { this.options.success(); } return true; } } if (typeof this.options.error === 'function' && customResult) { this.options.error(customResult); } } //同步验证,验证通过返回undefined;不通过返回- //-错误数组-->格式: [{"errorElem": 错误元素, "errorMsg": 对应错误信息}] //注: 使用此同步方法不会验证custom Validate.prototype.check = function($elem) { var $checkElems = ($elem?$($elem):[]), errResults = [], checkResult; if ($checkElems.length === 0) { $checkElems = this.$elems; } $checkElems.each(function() { //console.log($(this).check()); checkResult = $(this).check(); if (checkResult) { errResults.push({"errorElem": this, "errorMsg": checkResult}); } }); return (errResults.length > 0 ? errResults: undefined); } Validate.prototype.addElems = function(elems) { this.$elems = this.$elems.add($(elems)); } Validate.prototype.removeElems = function(elems) { this.$elems = this.$elems.not($(elems)); } /******** 数据验证 *******/ $.validate = function(options) { return new Validate(options); }; $.validate.valid = $.valid; })();
{ "content_hash": "6290146fdf0f74b6531acc02dafe68cb", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 65, "avg_line_length": 19.316326530612244, "alnum_prop": 0.6296883254094031, "repo_name": "zhzhchwin/Reasy-ui", "id": "6218ee2f29fe10f31ebf5c99f5781ba764236335", "size": "2025", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/js/reasy-ui-validate.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "111367" }, { "name": "HTML", "bytes": "24689" }, { "name": "JavaScript", "bytes": "349819" } ], "symlink_target": "" }
<?php namespace Amp\Websocket; use Amp\ByteStream\InputStream; use Amp\Promise; use Amp\Socket\SocketAddress; use Amp\Socket\TlsInfo; interface Client { /** * Receive a message from the remote Websocket endpoint. * * @return Promise<Message|null> Resolves to message sent by the remote. * * @throws ClosedException Thrown if the connection is closed. */ public function receive(): Promise; /** * @return int Unique identifier for the client. */ public function getId(): int; /** * @return bool True if the client is still connected, false otherwise. Returns false as soon as the closing * handshake is initiated by the server or client. */ public function isConnected(): bool; /** * @return SocketAddress Local socket address. */ public function getLocalAddress(): SocketAddress; /** * @return SocketAddress Remote socket address. */ public function getRemoteAddress(): SocketAddress; /** * @return TlsInfo|null TlsInfo object if connection is secure. */ public function getTlsInfo(): ?TlsInfo; /** * @return int Number of pings sent that have not been answered. */ public function getUnansweredPingCount(): int; /** * @return int Client close code (generally one of those listed in Code, though not necessarily). * * @throws \Error Thrown if the client has not closed. */ public function getCloseCode(): int; /** * @return string Client close reason. * * @throws \Error Thrown if the client has not closed. */ public function getCloseReason(): string; /** * @return bool True if the peer initiated the websocket close. * * @throws \Error Thrown if the client has not closed. */ public function isClosedByPeer(): bool; /** * Sends a text message to the endpoint. All data sent with this method must be valid UTF-8. Use `sendBinary()` if * you want to send binary data. * * @param string $data Payload to send. * * @return Promise<void> Resolves once the message has been sent to the peer. * * @throws ClosedException Thrown if sending to the client fails. */ public function send(string $data): Promise; /** * Sends a binary message to the endpoint. * * @param string $data Payload to send. * * @return Promise<void> Resolves once the message has been sent to the peer. * * @throws ClosedException Thrown if sending to the client fails. */ public function sendBinary(string $data): Promise; /** * Streams the given UTF-8 text stream to the endpoint. This method should be used only for large payloads such as * files. Use send() for smaller payloads. * * @param InputStream $stream * * @return Promise<void> Resolves once the message has been sent to the peer. * * @throws ClosedException Thrown if sending to the client fails. */ public function stream(InputStream $stream): Promise; /** * Streams the given binary to the endpoint. This method should be used only for large payloads such as * files. Use sendBinary() for smaller payloads. * * @param InputStream $stream * * @return Promise<void> Resolves once the message has been sent to the peer. * * @throws ClosedException Thrown if sending to the client fails. */ public function streamBinary(InputStream $stream): Promise; /** * Sends a ping to the endpoint. * * @return Promise<int> Resolves with the number of bytes sent to the other endpoint. */ public function ping(): Promise; /** * @return Options The options object associated with this client. */ public function getOptions(): Options; /** * Returns connection metadata. * * @return ClientMetadata */ public function getInfo(): ClientMetadata; /** * Closes the client connection. * * @param int $code * @param string $reason * * @return Promise<array> Resolves with an array containing the close code at key 0 and the close reason at key 1. * These may differ from those provided if the connection was closed prior. */ public function close(int $code = Code::NORMAL_CLOSE, string $reason = ''): Promise; /** * Attaches a callback invoked when the client closes. The callback is passed this object as the first parameter, * the close code as the second parameter, and the close reason as the third parameter. * * @param callable(Client $client, int $code, string $reason) $callback */ public function onClose(callable $callback): void; }
{ "content_hash": "bbde533bbb4c56ebc5445f36f7ac80cb", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 118, "avg_line_length": 30.573248407643312, "alnum_prop": 0.6447916666666667, "repo_name": "amphp/websocket", "id": "bb76b01f423167a4c8148a918e5c7938e1dbbeee", "size": "4800", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Client.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "86343" } ], "symlink_target": "" }
<?php namespace Thaumatic\Junxa; use Thaumatic\Junxa\Exceptions\JunxaDatabaseModelingException; use Thaumatic\Junxa\Exceptions\JunxaNoSuchColumnException; use Thaumatic\Junxa\KeyPart; /** * Models a database key. */ final class Key { /** * @const int key collation: the key is stored in ascending order */ const COLLATION_ASCENDING = 1; /** * @const int key collation: the key is stored unordered */ const COLLATION_NONE = 2; /** * @const int index type: B-tree */ const INDEX_TYPE_BTREE = 1; /** * @const int index type: full text */ const INDEX_TYPE_FULLTEXT = 2; /** * @const int index type: hash */ const INDEX_TYPE_HASH = 3; /** * @const int index type: R-tree */ const INDEX_TYPE_RTREE = 4; /** * @var string the name of the key */ private $name; /** * @var array<Thaumatic\Junxa\KeyPart> positional array of the constituent * parts of the key */ private $parts = []; /** * @var array<string:int> map of column names in the key to their indices * in the parts array */ private $columnIndices = []; /** * @var bool whether this is a unique key */ private $unique; /** * @var int Thaumatic\Junxa\Key::COLLATION_* type of collation used in the * key */ private $collation; /** * @var int Thaumatic\Junxa\Key::INDEX_TYPE_* index type used in the key */ private $indexType; /** * @var string database-generated comment on the key */ private $comment; /** * @var string user-specified comment on the key from table creation */ private $indexComment; /** * @param string the name of the key * @param bool whether this is a unique key * @param int Thaumatic\Junxa\Key::COLLATION_* type of collation used in * this key * @param int Thaumatic\Junxa\Key::INDEX_TYPE_* index type used in this key * @param string database-generated comment on the key * @param string used-specified comment on the key from table creation */ public function __construct( $name, $unique, $collation, $indexType, $comment, $indexComment ) { $this->name = $name; $this->unique = $unique; $this->collation = $collation; $this->indexType = $indexType; $this->comment = $comment; $this->indexComment = $indexComment; } /** * @param int the MySQL-reported position of the column in the key * @param Thaumatic\Junxa\KeyPart the key part model for the column * @return $this * @throws Thaumatic\Junxa\Exceptions\JunxaDatabaseModelingException if the * index in the parts array corresponding to $seq is already occupied * @throws Thaumatic\Junxa\Exceptions\JunxaDatabaseModelingException if * there is already an index tracked for the column name of the key part */ public function addKeyPart($seq, KeyPart $keyPart) { $index = $seq - 1; if (isset($this->parts[$index])) { throw new JunxaDatabaseModelingException( 'already have a key part at index ' . $index ); } $columnName = $keyPart->getColumnName(); if (isset($this->columnIndices[$columnName])) { throw new JunxaDatabaseModelingException( 'already have an index for column ' . $columnName ); } $this->parts[$index] = $keyPart; $this->columnIndices[$columnName] = $index; return $this; } /** * Retrieves the key part corresponding to the specified column name. * * @param string the column name * @return Thaumatic\Junxa\KeyPart * @throws Thaumatic\Junxa\Exceptions\JunxaNoSuchColumnException if the * specified column is not part of this key */ public function getColumnKeyPart($columnName) { if (!isset($this->columnIndices[$columnName])) { throw new JunxaDatabaseModelingException( 'column ' . $columnName . ' not part of key' ); } return $this->parts[$this->columnIndices[$columnName]]; } /** * @return string the name of the key */ public function getName() { return $this->name; } /** * @return array<Thaumatic\Junxa\KeyPart> positional array of the * constituent parts of the key */ public function getParts() { return $this->parts; } /** * @return array<string:int> map of column names in the key to their * indices in the parts array */ public function getColumnIndices() { return $this->columnIndices; } /** * @return bool whether this is a unique key */ public function getUnique() { return $this->unique; } /** * @return int Thaumatic\Junxa\Key::COLLATION_* type of collation used in * the key */ public function getCollation() { return $this->collation; } /** * @return int Thaumatic\Junxa\Key::INDEX_TYPE_* index type used in the key */ public function getIndexType() { return $this->indexType; } /** * @return string the database-generated comment on the key */ public function getComment() { return $this->comment; } /** * @return string the user-specified comment on the key from table creation */ public function getIndexComment() { return $this->indexComment; } /** * Retrieves whether a given column is part of this key. * * @param string column name * @return bool whether the specified column is part of this key */ public function isColumnInKey($columnName) { return isset($this->columnIndices[$columnName]); } }
{ "content_hash": "98db26ba786ab5ad5bb81951e6baf42d", "timestamp": "", "source": "github", "line_count": 237, "max_line_length": 79, "avg_line_length": 25.49789029535865, "alnum_prop": 0.5846433890451762, "repo_name": "thaumatic/junxa", "id": "aa3a454e175a8416be0a8781de7497b9f6957ad8", "size": "6043", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Junxa/Key.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "504177" } ], "symlink_target": "" }
package net.oneandone.troilus.async; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import net.oneandone.troilus.AbstractCassandraBasedTest; import net.oneandone.troilus.Dao; import net.oneandone.troilus.DaoImpl; import net.oneandone.troilus.Record; import net.oneandone.troilus.Result; import net.oneandone.troilus.TooManyResultsException; import net.oneandone.troilus.api.FeesTable; import org.junit.Assert; import org.junit.Test; import com.datastax.driver.core.querybuilder.QueryBuilder; import com.google.common.collect.ImmutableList; public class AsyncTest extends AbstractCassandraBasedTest { @Test public void testAsync() throws Exception { Dao feeDao = new DaoImpl(getSession(), FeesTable.TABLE); // delete records of previous tests for (Record record : feeDao.readAll().execute()) { feeDao.deleteWithKey(FeesTable.CUSTOMER_ID, record.getString(FeesTable.CUSTOMER_ID), FeesTable.YEAR, record.getInt(FeesTable.YEAR)); } //////////////// // inserts CompletableFuture<Result> insert1 = feeDao.writeWithKey(FeesTable.CUSTOMER_ID, "233132", FeesTable.YEAR, 3) .value(FeesTable.AMOUNT, 23433) .executeAsync(); CompletableFuture<Result> insert2 = feeDao.writeWithKey(FeesTable.CUSTOMER_ID, "233132", FeesTable.YEAR, 4) .value(FeesTable.AMOUNT, 1223) .executeAsync(); CompletableFuture<Result> insert3 = feeDao.writeWithKey(FeesTable.CUSTOMER_ID, "233132", FeesTable.YEAR, 8) .value(FeesTable.AMOUNT, 23233) .executeAsync(); CompletableFuture.allOf(insert1, insert2, insert3) .get(); // waits for completion try { feeDao.readWithKey(FeesTable.CUSTOMER_ID, "233132") .columns(FeesTable.CUSTOMER_ID, FeesTable.YEAR, FeesTable.AMOUNT) .executeAsync() .get(); // waits for completion Assert.fail("TooManyResultsException expected"); } catch (ExecutionException expected) { Assert.assertTrue(expected.getCause() instanceof TooManyResultsException); } //////////////// // reads ImmutableList<Record> recs = feeDao.readWhere(QueryBuilder.eq(FeesTable.CUSTOMER_ID, "233132")) .column(FeesTable.CUSTOMER_ID) .executeAsync() .thenApply(iterable -> iterable.iterator()) .thenApply(result -> ImmutableList.of(result.next(), result.next(), result.next())) .get(); // waits for completion Assert.assertEquals(3, recs.size()); Record record = feeDao.readWithKey(FeesTable.CUSTOMER_ID, "233132", FeesTable.YEAR, 4) .columns(FeesTable.CUSTOMER_ID, FeesTable.YEAR, FeesTable.AMOUNT) .executeAsync() .thenApply(optionalRecord -> optionalRecord.<RuntimeException>orElseThrow(RuntimeException::new)) .get(); // waits for completion; Assert.assertEquals((Integer) 1223, record.getInt(FeesTable.AMOUNT).get()); } }
{ "content_hash": "ddc02256daff3c0b26b8e1f89bdb41e4", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 127, "avg_line_length": 39.915789473684214, "alnum_prop": 0.5477320675105485, "repo_name": "mindis/Troilus", "id": "fbea8de08c601f8f8672b24638a63d8e2461704f", "size": "4411", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "troilus-core/src/test/java/net/oneandone/troilus/async/AsyncTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "708174" } ], "symlink_target": "" }
# CI Detector [![Latest Stable Version](https://img.shields.io/packagist/v/ondram/ci-detector.svg?style=flat-square)](https://packagist.org/packages/ondram/ci-detector) [![Packagist Downloads](https://img.shields.io/packagist/dt/OndraM/ci-detector?style=flat-square)](https://packagist.org/packages/ondram/ci-detector) [![Coverage Status](https://img.shields.io/coveralls/OndraM/ci-detector/main.svg?style=flat-square)](https://coveralls.io/r/OndraM/ci-detector) [![GitHub Actions Build Status](https://img.shields.io/github/workflow/status/OndraM/ci-detector/Tests%20and%20linting?style=flat-square&label=GitHub%20Actions%20build)](https://github.com/OndraM/ci-detector/actions) [![Travis Build Status](https://img.shields.io/travis/com/OndraM/ci-detector.svg?style=flat-square&label=Travis%20build)](https://app.travis-ci.com/OndraM/ci-detector) [![AppVeyor Build Status](https://img.shields.io/appveyor/ci/OndraM/ci-detector.svg?style=flat-square&label=AppVeyor%20build)](https://ci.appveyor.com/project/OndraM/ci-detector) PHP library to detect continuous integration environment and to read information of the current build. ## Why This library is useful if you need to detect whether some CLI script/tool is running in an automated environment (on a CI server). Based on that, your script may behave differently (for example hide some information which relevant only for a real person - like status bar, etc.). Plus, you may want to detect some information about the current build: build ID, git commit, branch etc. For example, if you'd like to record these values to log, publish them to Slack, etc. ## How The detection is based on environment variables injected to the build environment by each CI server. However, these variables are named differently in each CI. This library contains adapters for many supported CI servers to handle these differences, so you can make your scripts (and especially CLI tools) portable to multiple build environments. ## Supported continuous integration servers These CI servers are currently recognized: - [AppVeyor][appveyor] - [AWS CodeBuild][aws-codebuild] - [Azure DevOps Pipelines][azure-pipelines] - [Bamboo][bamboo] - [Bitbucket Pipelines][bitbucket] - [Buddy][buddy] - [CircleCI][circleci] - [Codeship][codeship] - continuousphp - [drone][drone] - [GitHub Actions][github-actions] - [GitLab][gitlab] - [Jenkins][jenkins] - [SourceHut][sourcehut] - [TeamCity][teamcity] - [Travis CI][travis-ci] - Wercker If your favorite CI server is missing, feel free to send a pull-request! ## Installation Install using [Composer](https://getcomposer.org/): ```sh $ composer require ondram/ci-detector ``` ## Example usage ```php <?php $ciDetector = new \OndraM\CiDetector\CiDetector(); if ($ciDetector->isCiDetected()) { // Make sure we are on CI environment echo 'You are running this script on CI server!'; $ci = $ciDetector->detect(); // Returns class implementing CiInterface or throws CiNotDetectedException // Example output when run inside GitHub Actions build: echo $ci->getCiName(); // "GitHub Actions" echo $ci->getBuildNumber(); // "33" echo $ci->getBranch(); // "feature/foo-bar" or empty string if not detected // Conditional code for pull request: if ($ci->isPullRequest()->yes()) { echo 'This is pull request. The target branch is: '; echo $ci->getTargetBranch(); // "main" } // Conditional code for specific CI server: if ($ci->getCiName() === OndraM\CiDetector\CiDetector::CI_GITHUB_ACTIONS) { echo 'This is being built on GitHub Actions'; } // Describe all detected values in human-readable form: print_r($ci->describe()); // Array // ( // [ci-name] => GitHub Actions // [build-number] => 33 // [build-url] => https://github.com/OndraM/ci-detector/commit/abcd/checks // [commit] => fad3f7bdbf3515d1e9285b8aa80feeff74507bde // [branch] => feature/foo-bar // [target-branch] => main // [repository-name] => OndraM/ci-detector // [repository-url] => https://github.com/OndraM/ci-detector // [is-pull-request] => Yes // ) } else { echo 'This script is not run on CI server'; } ``` ## API methods reference Available methods of `CiInterface` instance (returned from `$ciDetector->detect()`): | Method | Example value | Description | |-----------------------|------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `getCiName()` | `GitHub Actions` | Name of the CI server.<br>The value is one of `CiDetector::CI_*` constants. | | `getBuildNumber()` | `33` | Get number of this concrete build.<br>Build number is usually human-readable increasing number sequence. It should increase each time this particular job was run on the CI server. Most CIs use simple numbering sequence like: 1, 2, 3... However, some CIs do not provide this simple human-readable value and rather use for example alphanumeric hash. | | `getBuildUrl()` | `https://github.com/OndraM/ci-detector/commit/abcd/checks`<br>or empty string | Get URL where this build can be found and viewed or empty string if it cannot be determined. | | `getCommit()` | `b9173d94(...)` | Get hash of the git (or other VCS) commit being built. | | `getBranch()` | `my-feature`<br>or empty string | Get name of the git (or other VCS) branch which is being built or empty string if it cannot be determined.<br>Use `getTargetBranch()` to get name of the branch where this branch is targeted. | | `getTargetBranch()` | `main`<br>or empty string | Get name of the target branch of a pull request or empty string if it cannot be determined.<br>This is the base branch to which the pull request is targeted. | | `getRepositoryName()` | `OndraM/ci-detector`<br>or empty string | Get name of the git (or other VCS) repository which is being built or empty string if it cannot be determined.<br>This is usually in form "user/repository", for example `OndraM/ci-detector`. | | `getRepositoryUrl()` | `https://github.com/OndraM/ci-detector`<br>or empty string | Get URL where the repository which is being built can be found or empty string if it cannot be determined.<br>This is either HTTP URL like `https://github.com/OndraM/ci-detector` but may be a git ssh url like `ssh://git@bitbucket.org/OndraM/ci-detector` | | `isPullRequest()` | `TrinaryLogic` instance | Detect whether current build is from a pull/merge request.<br>Returned `TrinaryLogic` object's value will be true if the current build is from a pull/merge request, false if it not, and maybe if we can't determine it (see below for what CI supports PR detection).<br>Use condition like `if ($ci->isPullRequest()->yes()) { /*...*/ }` to use the value. | | `describe()` | `[...]`<br>(array of values) | Return key-value map of all detected properties in human-readable form. | ## Supported properties of each CI server Most CI servers support (✔) detection of all information. However some don't expose necessary environment variables, thus reading some information may be unsupported (❌). | CI server | Constant of `CiDetector` | `is​PullRequest` | `get​Branch` | `get​Target​Branch` | `get​Repository​Name` | `get​Repository​Url` | `get​Build​Url` | |------------------------------------|--------------------------|---|---|---|---|---|---| | [AppVeyor][appveyor] | `CI_APPVEYOR` | ✔ | ✔ | ✔ | ✔ | ❌ | ✔ | | [AWS CodeBuild][aws-codebuild] | `CI_AWS_CODEBUILD` | ✔ | ✔ | ❌ | ❌ | ✔ | ✔ | | [Azure Pipelines][azure-pipelines] | `CI_AZURE_PIPELINES` | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | | [Bamboo][bamboo] | `CI_BAMBOO` | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | | [Bitbucket Pipelines][bitbucket] | `CI_BITBUCKET_PIPELINES` | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | | [Buddy][buddy] | `CI_BUDDY` | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | | [CircleCI][circleci] | `CI_CIRCLE` | ✔ | ✔ | ❌ | ✔ | ✔ | ✔ | | [Codeship][codeship] | `CI_CODESHIP` | ✔ | ✔ | ❌ | ✔ | ❌ | ✔ | | continuousphp | `CI_CONTINUOUSPHP` | ✔ | ✔ | ❌ | ❌ | ✔ | ✔ | | [drone][drone] | `CI_DRONE` | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | | [GitHub Actions][github-actions] | `CI_GITHUB_ACTIONS` | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | | [GitLab][gitlab] | `CI_GITLAB` | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | | [Jenkins][jenkins] | `CI_JENKINS` | ❌ | ✔ | ❌ | ❌ | ✔ | ✔ | | [SourceHut][sourcehut] | `CI_SOURCEHUT` | ✔ | ❌ | ❌ | ❌ | ❌ | ✔ | | [TeamCity][teamcity] | `CI_TEAMCITY` | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | | [Travis CI][travis-ci] | `CI_TRAVIS` | ✔ | ✔ | ✔ | ✔ | ❌ | ✔ | | Wercker | `CI_WERCKER` | ❌ | ✔ | ❌ | ✔ | ❌ | ✔ | ## Testing Check codestyle, static analysis and run unit-tests: ```sh composer all ``` To automatically fix codestyle violations run: ```sh composer fix ``` ## Standalone CLI version If you want to use CI Detector as a standalone CLI command (ie. without using inside code of PHP project), see [ci-detector-standalone](https://github.com/OndraM/ci-detector-standalone) repository, where you can download CI Detector as a standalone PHAR file with simple command line interface. ## Changelog For latest changes see [CHANGELOG.md](CHANGELOG.md) file. This project follows [Semantic Versioning](https://semver.org/). ## Similar libraries for other languages Similar "CI Info" libraries exists for some other languages, for example: - Go - [KlotzAndrew/ci-info](https://github.com/KlotzAndrew/ci-info) - JavaScript/Node.js - [watson/ci-info](https://github.com/watson/ci-info) - Python - [mgxd/ci-info](https://github.com/mgxd/ci-info) - Rust - [sagiegurari/ci_info](https://github.com/sagiegurari/ci_info) [appveyor]: https://www.appveyor.com/ [aws-codebuild]: https://aws.amazon.com/codebuild/ [azure-pipelines]: https://azure.microsoft.com/en-us/services/devops/pipelines/ [bamboo]: https://www.atlassian.com/software/bamboo [bitbucket]: https://bitbucket.org/product/features/pipelines [buddy]: https://buddy.works/ [circleci]: https://circleci.com/ [codeship]: https://codeship.com/ [drone]: https://drone.io/ [github-actions]: https://github.com/features/actions [gitlab]: https://about.gitlab.com/gitlab-ci/ [jenkins]: https://www.jenkins.io/ [sourcehut]: https://sourcehut.org/ [teamcity]: https://www.jetbrains.com/teamcity/ [travis-ci]: https://travis-ci.org/
{ "content_hash": "c3b842132f39c0bd22e927291e0c4b8e", "timestamp": "", "source": "github", "line_count": 193, "max_line_length": 453, "avg_line_length": 69.02072538860104, "alnum_prop": 0.516252533593574, "repo_name": "OndraM/ci-detector", "id": "4994602d1c9f59d0be801a85a6ceb5fcf8fd83de", "size": "13549", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "132786" } ], "symlink_target": "" }
<?php try{ new $class(new stdClass()); } catch(TypeError $e){ $status = $e->getMessage() == "Argument 1 passed to $class::__construct() must be an instance of UVLoop, instance of stdClass given"?'ok':'fail'; echo "$class $status"; }
{ "content_hash": "a53e48d1011138708a0789f8c7f14c9e", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 149, "avg_line_length": 30.5, "alnum_prop": 0.639344262295082, "repo_name": "RickySu/php_ext_uv", "id": "60ac959269ccd93be4c227dee115fedae76e3dfd", "size": "244", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/typecheck/error_handler.php", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "109623" }, { "name": "C++", "bytes": "9898" }, { "name": "M4", "bytes": "1855" }, { "name": "PHP", "bytes": "64492" }, { "name": "Shell", "bytes": "530" } ], "symlink_target": "" }
(function(audiojs, audiojsInstance, container) { // Use the path to the audio.js file to create relative paths to the swf and player graphics // Remember that some systems (e.g. ruby on rails) append strings like '?1301478336' to asset paths var path = (function() { var re = new RegExp('audio(\.min)?\.js.*'), scripts = document.getElementsByTagName('script'); for (var i = 0, ii = scripts.length; i < ii; i++) { var path = scripts[i].getAttribute('src'); if(re.test(path)) return path.replace(re, ''); } })(); // ##The audiojs interface // This is the global object which provides an interface for creating new `audiojs` instances. // It also stores all of the construction helper methods and variables. container[audiojs] = { instanceCount: 0, instances: {}, // The markup for the swf. It is injected into the page if there is not support for the `<audio>` element. The `$n`s are placeholders. // `$1` The name of the flash movie // `$2` The path to the swf // `$3` Cache invalidation flashSource: '\ <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="$1" width="1" height="1" name="$1" style="position: absolute; left: -1px;"> \ <param name="movie" value="$2?playerInstance='+audiojs+'.instances[\'$1\']&datetime=$3"> \ <param name="allowscriptaccess" value="always"> \ <embed name="$1" src="$2?playerInstance='+audiojs+'.instances[\'$1\']&datetime=$3" width="1" height="1" allowscriptaccess="always"> \ </object>', // ### The main settings object // Where all the default settings are stored. Each of these variables and methods can be overwritten by the user-provided `options` object. settings: { autoplay: false, loop: false, preload: true, imageLocation: path + 'player-graphics.gif', swfLocation: path + 'audiojs.swf', useFlash: (function() { var a = document.createElement('audio'); return !(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, '')); })(), hasFlash: (function() { if (navigator.plugins && navigator.plugins.length && navigator.plugins['Shockwave Flash']) { return true; } else if (navigator.mimeTypes && navigator.mimeTypes.length) { var mimeType = navigator.mimeTypes['application/x-shockwave-flash']; return mimeType && mimeType.enabledPlugin; } else { try { var ax = new ActiveXObject('ShockwaveFlash.ShockwaveFlash'); return true; } catch (e) {} } return false; })(), // The default markup and classes for creating the player: createPlayer: { markup: '\ <div class="play-pause"> \ <p class="play"></p> \ <p class="pause"></p> \ <p class="loading"></p> \ <p class="error"></p> \ </div> \ <div class="scrubber"> \ <div class="progress"></div> \ <div class="loaded"></div> \ </div> \ <div class="time"> \ <em class="played">00:00</em>/<strong class="duration">00:00</strong> \ </div> \ <div class="error-message"></div>', playPauseClass: 'play-pause', scrubberClass: 'scrubber', progressClass: 'progress', loaderClass: 'loaded', timeClass: 'time', durationClass: 'duration', playedClass: 'played', errorMessageClass: 'error-message', playingClass: 'playing', loadingClass: 'loading', errorClass: 'error' }, // The default event callbacks: trackEnded: function(e) {}, flashError: function() { var player = this.settings.createPlayer, errorMessage = getByClass(player.errorMessageClass, this.wrapper), html = 'Missing <a href="http://get.adobe.com/flashplayer/">flash player</a> plugin.'; if (this.mp3) html += ' <a href="'+this.mp3+'">Download audio file</a>.'; container[audiojs].helpers.removeClass(this.wrapper, player.loadingClass); container[audiojs].helpers.addClass(this.wrapper, player.errorClass); errorMessage.innerHTML = html; }, loadError: function(e) { var player = this.settings.createPlayer, errorMessage = getByClass(player.errorMessageClass, this.wrapper); container[audiojs].helpers.removeClass(this.wrapper, player.loadingClass); container[audiojs].helpers.addClass(this.wrapper, player.errorClass); errorMessage.innerHTML = 'Error loading: "'+this.mp3+'"'; }, init: function() { var player = this.settings.createPlayer; container[audiojs].helpers.addClass(this.wrapper, player.loadingClass); }, loadStarted: function() { var player = this.settings.createPlayer, duration = getByClass(player.durationClass, this.wrapper), m = Math.floor(this.duration / 60), s = Math.floor(this.duration % 60); container[audiojs].helpers.removeClass(this.wrapper, player.loadingClass); duration.innerHTML = ((m<10?'0':'')+m+':'+(s<10?'0':'')+s); }, loadProgress: function(percent) { var player = this.settings.createPlayer, scrubber = getByClass(player.scrubberClass, this.wrapper), loaded = getByClass(player.loaderClass, this.wrapper); loaded.style.width = (scrubber.offsetWidth * percent) + 'px'; }, playPause: function() { if (this.playing) this.settings.play(); else this.settings.pause(); }, play: function() { var player = this.settings.createPlayer; container[audiojs].helpers.addClass(this.wrapper, player.playingClass); }, pause: function() { var player = this.settings.createPlayer; container[audiojs].helpers.removeClass(this.wrapper, player.playingClass); }, updatePlayhead: function(percent) { var player = this.settings.createPlayer, scrubber = getByClass(player.scrubberClass, this.wrapper), progress = getByClass(player.progressClass, this.wrapper); progress.style.width = (scrubber.offsetWidth * percent) + 'px'; var played = getByClass(player.playedClass, this.wrapper), p = this.duration * percent, m = Math.floor(p / 60), s = Math.floor(p % 60); played.innerHTML = ((m<10?'0':'')+m+':'+(s<10?'0':'')+s); } }, // ### Contructor functions // `create()` // Used to create a single `audiojs` instance. // If an array is passed then it calls back to `createAll()`. // Otherwise, it creates a single instance and returns it. create: function(element, options) { var options = options || {} if (element.length) { return this.createAll(options, element); } else { return this.newInstance(element, options); } }, // `createAll()` // Creates multiple `audiojs` instances. // If `elements` is `null`, then automatically find any `<audio>` tags on the page and create `audiojs` instances for them. createAll: function(options, elements) { var audioElements = elements || document.getElementsByTagName('audio'), instances = [] options = options || {}; for (var i = 0, ii = audioElements.length; i < ii; i++) { instances.push(this.newInstance(audioElements[i], options)); } return instances; }, // ### Creating and returning a new instance // This goes through all the steps required to build out a usable `audiojs` instance. newInstance: function(element, options) { var element = element, s = this.helpers.clone(this.settings), id = 'audiojs'+this.instanceCount, wrapperId = 'audiojs_wrapper'+this.instanceCount, instanceCount = this.instanceCount++; // Check for `autoplay`, `loop` and `preload` attributes and write them into the settings. if (element.getAttribute('autoplay') != null) s.autoplay = true; if (element.getAttribute('loop') != null) s.loop = true; if (element.getAttribute('preload') == 'none') s.preload = false; // Merge the default settings with the user-defined `options`. if (options) this.helpers.merge(s, options); // Inject the player html if required. if (s.createPlayer.markup) element = this.createPlayer(element, s.createPlayer, wrapperId); else element.parentNode.setAttribute('id', wrapperId); // Return a new `audiojs` instance. var audio = new container[audiojsInstance](element, s); // If `<audio>` or mp3 playback isn't supported, insert the swf & attach the required events for it. if (s.useFlash && s.hasFlash) { this.injectFlash(audio, id); this.attachFlashEvents(audio.wrapper, audio); } else if (s.useFlash && !s.hasFlash) { this.settings.flashError.apply(audio); } // Attach event callbacks to the new audiojs instance. if (!s.useFlash || (s.useFlash && s.hasFlash)) this.attachEvents(audio.wrapper, audio); // Store the newly-created `audiojs` instance. this.instances[id] = audio; return audio; }, // ### Helper methods for constructing a working player // Inject a wrapping div and the markup for the html player. createPlayer: function(element, player, id) { var wrapper = document.createElement('div'), newElement = element.cloneNode(true); wrapper.setAttribute('class', 'audiojs'); wrapper.setAttribute('className', 'audiojs'); wrapper.setAttribute('id', id); // Fix IE's broken implementation of `innerHTML` & `cloneNode` for HTML5 elements. if (newElement.outerHTML && !document.createElement('audio').canPlayType) { newElement = this.helpers.cloneHtml5Node(element); wrapper.innerHTML = player.markup; wrapper.appendChild(newElement); element.outerHTML = wrapper.outerHTML; wrapper = document.getElementById(id); } else { wrapper.appendChild(newElement); wrapper.innerHTML = wrapper.innerHTML + player.markup; element.parentNode.replaceChild(wrapper, element); } return wrapper.getElementsByTagName('audio')[0]; }, // Attaches useful event callbacks to an `audiojs` instance. attachEvents: function(wrapper, audio) { if (!audio.settings.createPlayer) return; var player = audio.settings.createPlayer, playPause = getByClass(player.playPauseClass, wrapper), scrubber = getByClass(player.scrubberClass, wrapper), leftPos = function(elem) { var curleft = 0; if (elem.offsetParent) { do { curleft += elem.offsetLeft; } while (elem = elem.offsetParent); } return curleft; }; container[audiojs].events.addListener(playPause, 'click', function(e) { audio.playPause.apply(audio); }); container[audiojs].events.addListener(scrubber, 'click', function(e) { var relativeLeft = e.clientX - leftPos(this); audio.skipTo(relativeLeft / scrubber.offsetWidth); }); // _If flash is being used, then the following handlers don't need to be registered._ if (audio.settings.useFlash) return; // Start tracking the load progress of the track. container[audiojs].events.trackLoadProgress(audio); container[audiojs].events.addListener(audio.element, 'timeupdate', function(e) { audio.updatePlayhead.apply(audio); }); container[audiojs].events.addListener(audio.element, 'ended', function(e) { audio.trackEnded.apply(audio); }); container[audiojs].events.addListener(audio.source, 'error', function(e) { // on error, cancel any load timers that are running. clearInterval(audio.readyTimer); clearInterval(audio.loadTimer); audio.settings.loadError.apply(audio); }); }, // Flash requires a slightly different API to the `<audio>` element, so this method is used to overwrite the standard event handlers. attachFlashEvents: function(element, audio) { audio['swfReady'] = false; audio['load'] = function(mp3) { // If the swf isn't ready yet then just set `audio.mp3`. `init()` will load it in once the swf is ready. audio.mp3 = mp3; if (audio.swfReady) audio.element.load(mp3); } audio['loadProgress'] = function(percent, duration) { audio.loadedPercent = percent; audio.duration = duration; audio.settings.loadStarted.apply(audio); audio.settings.loadProgress.apply(audio, [percent]); } audio['skipTo'] = function(percent) { if (percent > audio.loadedPercent) return; audio.updatePlayhead.call(audio, [percent]) audio.element.skipTo(percent); } audio['updatePlayhead'] = function(percent) { audio.settings.updatePlayhead.apply(audio, [percent]); } audio['play'] = function() { // If the audio hasn't started preloading, then start it now. // Then set `preload` to `true`, so that any tracks loaded in subsequently are loaded straight away. if (!audio.settings.preload) { audio.settings.preload = true; audio.element.init(audio.mp3); } audio.playing = true; // IE doesn't allow a method named `play()` to be exposed through `ExternalInterface`, so lets go with `pplay()`. // <http://dev.nuclearrooster.com/2008/07/27/externalinterfaceaddcallback-can-cause-ie-js-errors-with-certain-keyworkds/> audio.element.pplay(); audio.settings.play.apply(audio); } audio['pause'] = function() { audio.playing = false; // Use `ppause()` for consistency with `pplay()`, even though it isn't really required. audio.element.ppause(); audio.settings.pause.apply(audio); } audio['setVolume'] = function(v) { audio.element.setVolume(v); } audio['loadStarted'] = function() { // Load the mp3 specified by the audio element into the swf. audio.swfReady = true; if (audio.settings.preload) audio.element.init(audio.mp3); if (audio.settings.autoplay) audio.play.apply(audio); } }, // ### Injecting an swf from a string // Build up the swf source by replacing the `$keys` and then inject the markup into the page. injectFlash: function(audio, id) { var flashSource = this.flashSource.replace(/\$1/g, id); flashSource = flashSource.replace(/\$2/g, audio.settings.swfLocation); // `(+new Date)` ensures the swf is not pulled out of cache. The fixes an issue with Firefox running multiple players on the same page. flashSource = flashSource.replace(/\$3/g, (+new Date + Math.random())); // Inject the player markup using a more verbose `innerHTML` insertion technique that works with IE. var html = audio.wrapper.innerHTML, div = document.createElement('div'); div.innerHTML = flashSource + html; audio.wrapper.innerHTML = div.innerHTML; audio.element = this.helpers.getSwf(id); }, // ## Helper functions helpers: { // **Merge two objects, with `obj2` overwriting `obj1`** // The merge is shallow, but that's all that is required for our purposes. merge: function(obj1, obj2) { for (attr in obj2) { if (obj1.hasOwnProperty(attr) || obj2.hasOwnProperty(attr)) { obj1[attr] = obj2[attr]; } } }, // **Clone a javascript object (recursively)** clone: function(obj){ if (obj == null || typeof(obj) !== 'object') return obj; var temp = new obj.constructor(); for (var key in obj) temp[key] = arguments.callee(obj[key]); return temp; }, // **Adding/removing classnames from elements** addClass: function(element, className) { var re = new RegExp('(\\s|^)'+className+'(\\s|$)'); if (re.test(element.className)) return; element.className += ' ' + className; }, removeClass: function(element, className) { var re = new RegExp('(\\s|^)'+className+'(\\s|$)'); element.className = element.className.replace(re,' '); }, // **Handle all the IE6+7 requirements for cloning `<audio>` nodes** // Create a html5-safe document fragment by injecting an `<audio>` element into the document fragment. cloneHtml5Node: function(audioTag) { var fragment = document.createDocumentFragment(), doc = fragment.createElement ? fragment : document; doc.createElement('audio'); var div = doc.createElement('div'); fragment.appendChild(div); div.innerHTML = audioTag.outerHTML; return div.firstChild; }, // **Cross-browser `<object>` / `<embed>` element selection** getSwf: function(name) { var swf = document[name] || window[name]; return swf.length > 1 ? swf[swf.length - 1] : swf; } }, // ## Event-handling events: { memoryLeaking: false, listeners: [], // **A simple cross-browser event handler abstraction** addListener: function(element, eventName, func) { // For modern browsers use the standard DOM-compliant `addEventListener`. if (element.addEventListener) { element.addEventListener(eventName, func, false); // For older versions of Internet Explorer, use `attachEvent`. // Also provide a fix for scoping `this` to the calling element and register each listener so the containing elements can be purged on page unload. } else if (element.attachEvent) { this.listeners.push(element); if (!this.memoryLeaking) { window.attachEvent('onunload', function() { if(this.listeners) { for (var i = 0, ii = this.listeners.length; i < ii; i++) { container[audiojs].events.purge(this.listeners[i]); } } }); this.memoryLeaking = true; } element.attachEvent('on' + eventName, function() { func.call(element, window.event); }); } }, trackLoadProgress: function(audio) { // If `preload` has been set to `none`, then we don't want to start loading the track yet. if (!audio.settings.preload) return; var readyTimer, loadTimer, audio = audio, ios = (/(ipod|iphone|ipad)/i).test(navigator.userAgent); // Use timers here rather than the official `progress` event, as Chrome has issues calling `progress` when loading mp3 files from cache. readyTimer = setInterval(function() { if (audio.element.readyState > -1) { // iOS doesn't start preloading the mp3 until the user interacts manually, so this stops the loader being displayed prematurely. if (!ios) audio.init.apply(audio); } if (audio.element.readyState > 1) { if (audio.settings.autoplay) audio.play.apply(audio); clearInterval(readyTimer); // Once we have data, start tracking the load progress. loadTimer = setInterval(function() { audio.loadProgress.apply(audio); if (audio.loadedPercent >= 1) clearInterval(loadTimer); }); } }, 10); audio.readyTimer = readyTimer; audio.loadTimer = loadTimer; }, // **Douglas Crockford's IE6 memory leak fix** // <http://javascript.crockford.com/memory/leak.html> // This is used to release the memory leak created by the circular references created when fixing `this` scoping for IE. It is called on page unload. purge: function(d) { var a = d.attributes, i; if (a) { for (i = 0; i < a.length; i += 1) { if (typeof d[a[i].name] === 'function') d[a[i].name] = null; } } a = d.childNodes; if (a) { for (i = 0; i < a.length; i += 1) purge(d.childNodes[i]); } }, // **DOMready function** // As seen here: <https://github.com/dperini/ContentLoaded/>. ready: (function() { return function(fn) { var win = window, done = false, top = true, doc = win.document, root = doc.documentElement, add = doc.addEventListener ? 'addEventListener' : 'attachEvent', rem = doc.addEventListener ? 'removeEventListener' : 'detachEvent', pre = doc.addEventListener ? '' : 'on', init = function(e) { if (e.type == 'readystatechange' && doc.readyState != 'complete') return; (e.type == 'load' ? win : doc)[rem](pre + e.type, init, false); if (!done && (done = true)) fn.call(win, e.type || e); }, poll = function() { try { root.doScroll('left'); } catch(e) { setTimeout(poll, 50); return; } init('poll'); }; if (doc.readyState == 'complete') fn.call(win, 'lazy'); else { if (doc.createEventObject && root.doScroll) { try { top = !win.frameElement; } catch(e) { } if (top) poll(); } doc[add](pre + 'DOMContentLoaded', init, false); doc[add](pre + 'readystatechange', init, false); win[add](pre + 'load', init, false); } } })() } } // ## The audiojs class // We create one of these per `<audio>` and then push them into `audiojs['instances']`. container[audiojsInstance] = function(element, settings) { // Each audio instance returns an object which contains an API back into the `<audio>` element. this.element = element; this.wrapper = element.parentNode; this.source = element.getElementsByTagName('source')[0] || element; // First check the `<audio>` element directly for a src and if one is not found, look for a `<source>` element. this.mp3 = (function(element) { var source = element.getElementsByTagName('source')[0]; return element.getAttribute('src') || (source ? source.getAttribute('src') : null); })(element); this.settings = settings; this.loadStartedCalled = false; this.loadedPercent = 0; this.duration = 1; this.playing = false; } container[audiojsInstance].prototype = { // API access events: // Each of these do what they need do and then call the matching methods defined in the settings object. updatePlayhead: function() { var percent = this.element.currentTime / this.duration; this.settings.updatePlayhead.apply(this, [percent]); }, skipTo: function(percent) { if (percent > this.loadedPercent) return; this.element.currentTime = this.duration * percent; this.updatePlayhead(); }, load: function(mp3) { this.loadStartedCalled = false; this.source.setAttribute('src', mp3); // The now outdated `load()` method is required for Safari 4 this.element.load(); this.mp3 = mp3; container[audiojs].events.trackLoadProgress(this); }, loadError: function() { this.settings.loadError.apply(this); }, init: function() { this.settings.init.apply(this); }, loadStarted: function() { // Wait until `element.duration` exists before setting up the audio player. if (!this.element.duration) return false; this.duration = this.element.duration; this.updatePlayhead(); this.settings.loadStarted.apply(this); }, loadProgress: function() { if (this.element.buffered != null && this.element.buffered.length) { // Ensure `loadStarted()` is only called once. if (!this.loadStartedCalled) { this.loadStartedCalled = this.loadStarted(); } var durationLoaded = this.element.buffered.end(this.element.buffered.length - 1); this.loadedPercent = durationLoaded / this.duration; this.settings.loadProgress.apply(this, [this.loadedPercent]); } }, playPause: function() { if (this.playing) this.pause(); else this.play(); }, play: function() { var ios = (/(ipod|iphone|ipad)/i).test(navigator.userAgent); // On iOS this interaction will trigger loading the mp3, so run `init()`. if (ios && this.element.readyState == 0) this.init.apply(this); // If the audio hasn't started preloading, then start it now. // Then set `preload` to `true`, so that any tracks loaded in subsequently are loaded straight away. if (!this.settings.preload) { this.settings.preload = true; this.element.setAttribute('preload', 'auto'); container[audiojs].events.trackLoadProgress(this); } this.playing = true; this.element.play(); this.settings.play.apply(this); }, pause: function() { this.playing = false; this.element.pause(); this.settings.pause.apply(this); }, setVolume: function(v) { this.element.volume = v; }, trackEnded: function(e) { this.skipTo.apply(this, [0]); if (!this.settings.loop) this.pause.apply(this); this.settings.trackEnded.apply(this); } } // **getElementsByClassName** // Having to rely on `getElementsByTagName` is pretty inflexible internally, so a modified version of Dustin Diaz's `getElementsByClassName` has been included. // This version cleans things up and prefers the native DOM method if it's available. var getByClass = function(searchClass, node) { var matches = []; node = node || document; if (node.getElementsByClassName) { matches = node.getElementsByClassName(searchClass); } else { var i, l, els = node.getElementsByTagName("*"), pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"); for (i = 0, l = els.length; i < l; i++) { if (pattern.test(els[i].className)) { matches.push(els[i]); } } } return matches.length > 1 ? matches : matches[0]; }; // The global variable names are passed in here and can be changed if they conflict with anything else. })('audiojs', 'audiojsInstance', this);
{ "content_hash": "eb7d04657c48b13fcba75c24ef0fe2f0", "timestamp": "", "source": "github", "line_count": 625, "max_line_length": 161, "avg_line_length": 42.3616, "alnum_prop": 0.6104396434506723, "repo_name": "edinella/ploud", "id": "763f18879e4cb7d16f9bf25d624e2c4419828a06", "size": "26527", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/audiojs/audio.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "52225" } ], "symlink_target": "" }
package org.apache.beam.sdk.io.gcp; import static org.apache.beam.sdk.util.ApiSurface.classesInPackage; import static org.apache.beam.sdk.util.ApiSurface.containsOnlyClassesMatching; import static org.hamcrest.MatcherAssert.assertThat; import com.google.common.collect.ImmutableSet; import java.util.Set; import org.apache.beam.sdk.util.ApiSurface; import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** API surface verification for {@link org.apache.beam.sdk.io.gcp}. */ @RunWith(JUnit4.class) public class GcpApiSurfaceTest { @Test public void testGcpApiSurface() throws Exception { final Package thisPackage = getClass().getPackage(); final ClassLoader thisClassLoader = getClass().getClassLoader(); final ApiSurface apiSurface = ApiSurface.ofPackage(thisPackage, thisClassLoader) .pruningPattern("org[.]apache[.]beam[.].*Test.*") .pruningPattern("org[.]apache[.]beam[.].*IT") .pruningPattern("java[.]lang.*"); @SuppressWarnings("unchecked") final Set<Matcher<Class<?>>> allowedClasses = ImmutableSet.of( classesInPackage("com.google.api.client.json"), classesInPackage("com.google.api.client.util"), classesInPackage("com.google.api.services.bigquery.model"), classesInPackage("com.google.auth"), classesInPackage("com.google.bigtable.v2"), classesInPackage("com.google.cloud.bigtable.config"), Matchers.<Class<?>>equalTo(com.google.cloud.bigtable.grpc.BigtableClusterName.class), Matchers.<Class<?>>equalTo(com.google.cloud.bigtable.grpc.BigtableInstanceName.class), Matchers.<Class<?>>equalTo(com.google.cloud.bigtable.grpc.BigtableTableName.class), // via Bigtable, PR above out to fix. classesInPackage("com.google.datastore.v1"), classesInPackage("com.google.protobuf"), classesInPackage("com.google.type"), classesInPackage("com.fasterxml.jackson.annotation"), classesInPackage("com.fasterxml.jackson.core"), classesInPackage("com.fasterxml.jackson.databind"), classesInPackage("io.grpc"), classesInPackage("java"), classesInPackage("javax"), classesInPackage("org.apache.beam"), classesInPackage("org.apache.commons.logging"), // via Bigtable classesInPackage("org.joda.time")); assertThat(apiSurface, containsOnlyClassesMatching(allowedClasses)); } }
{ "content_hash": "3fa0f43b8b77884044594da5b99473de", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 98, "avg_line_length": 42.37096774193548, "alnum_prop": 0.6848115721355158, "repo_name": "xsm110/Apache-Beam", "id": "0987140e7d8a872fc3088467d1b851b98d139413", "size": "3432", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/GcpApiSurfaceTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "42728" }, { "name": "Java", "bytes": "11382377" }, { "name": "Protocol Buffer", "bytes": "50349" }, { "name": "Python", "bytes": "2635088" }, { "name": "Shell", "bytes": "34853" } ], "symlink_target": "" }
// g2o - General Graph Optimization // Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Modified by Michal Nowicki (michal.nowicki@put.poznan.pl) 2015 // Added EdgeSE2Orientation (Pure orientation measurement) #include "edge_se2_orientation.h" #ifdef G2O_HAVE_OPENGL #include "g2o/stuff/opengl_wrapper.h" #include "g2o/stuff/opengl_primitives.h" #endif namespace g2o { EdgeSE2Orientation::EdgeSE2Orientation() { } void EdgeSE2Orientation::initialEstimate( const OptimizableGraph::VertexSet& from, OptimizableGraph::Vertex* /*to*/) { VertexSE2* fromEdge = static_cast<VertexSE2*>(_vertices[0]); VertexSE2* toEdge = static_cast<VertexSE2*>(_vertices[1]); double theta = _measurement; SE2 tmpMeasurement(0,0,theta); SE2 inverseTmpMeasurement = tmpMeasurement.inverse(); if (from.count(fromEdge) > 0) toEdge->setEstimate(fromEdge->estimate() * tmpMeasurement); else fromEdge->setEstimate(toEdge->estimate() * inverseTmpMeasurement); } bool EdgeSE2Orientation::read(std::istream& is) { double p; is >> p; setMeasurement(p); is >> information()(0,0); return true; } bool EdgeSE2Orientation::write(std::ostream& os) const { os << _measurement << information()(0, 0); return os.good(); } EdgeSE2OrientationWriteGnuplotAction::EdgeSE2OrientationWriteGnuplotAction(): WriteGnuplotAction(typeid(EdgeSE2Orientation).name()){} HyperGraphElementAction* EdgeSE2OrientationWriteGnuplotAction::operator()(HyperGraph::HyperGraphElement* element, HyperGraphElementAction::Parameters* params_){ if (typeid(*element).name()!=_typeName) return 0; WriteGnuplotAction::Parameters* params=static_cast<WriteGnuplotAction::Parameters*>(params_); if (!params->os){ std::cerr << __PRETTY_FUNCTION__ << ": warning, on valid os specified" << std::endl; return 0; } EdgeSE2Orientation* e = static_cast<EdgeSE2Orientation*>(element); VertexSE2* fromEdge = static_cast<VertexSE2*>(e->vertex(0)); VertexPointXY* toEdge = static_cast<VertexPointXY*>(e->vertex(1)); *(params->os) << fromEdge->estimate().translation().x() << " " << fromEdge->estimate().translation().y() << " " << fromEdge->estimate().rotation().angle() << std::endl; *(params->os) << toEdge->estimate().x() << " " << toEdge->estimate().y() << std::endl; *(params->os) << std::endl; return this; } #ifdef G2O_HAVE_OPENGL EdgeSE2OrientationDrawAction::EdgeSE2OrientationDrawAction(): DrawAction(typeid(EdgeSE2Orientation).name()){} HyperGraphElementAction* EdgeSE2OrientationDrawAction::operator()(HyperGraph::HyperGraphElement* element, HyperGraphElementAction::Parameters* params_){ if (typeid(*element).name()!=_typeName) return 0; refreshPropertyPtrs(params_); if (! _previousParams) return this; if (_show && !_show->value()) return this; EdgeSE2Orientation* e = static_cast<EdgeSE2Orientation*>(element); VertexSE2* from = static_cast<VertexSE2*>(e->vertex(0)); VertexPointXY* to = static_cast<VertexPointXY*>(e->vertex(1)); if (! from) return this; double guessRange=5; double theta = e->measurement(); Vector2D p(cos(theta)*guessRange, sin(theta)*guessRange); glPushAttrib(GL_ENABLE_BIT|GL_LIGHTING|GL_COLOR); glDisable(GL_LIGHTING); if (!to){ p=from->estimate()*p; glColor3f(LANDMARK_EDGE_GHOST_COLOR); glPushAttrib(GL_POINT_SIZE); glPointSize(3); glBegin(GL_POINTS); glVertex3f((float)p.x(),(float)p.y(),0.f); glEnd(); glPopAttrib(); } else { p=to->estimate(); glColor3f(LANDMARK_EDGE_COLOR); } glBegin(GL_LINES); glVertex3f((float)from->estimate().translation().x(),(float)from->estimate().translation().y(),0.f); glVertex3f((float)p.x(),(float)p.y(),0.f); glEnd(); glPopAttrib(); return this; } #endif } // end namespace
{ "content_hash": "cc954603ebbd872c3c1adb2c6abd76b7", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 155, "avg_line_length": 37.87323943661972, "alnum_prop": 0.6822238750464856, "repo_name": "LRMPUT/DiamentowyGrant", "id": "a688aa1ee59b9164c8e965369423607dc156e5bd", "size": "5378", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "NavigationDG/jni/GraphOptimization/edge_se2_orientation.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "291264" }, { "name": "C++", "bytes": "13785454" }, { "name": "CMake", "bytes": "29391" }, { "name": "Java", "bytes": "420298" }, { "name": "Makefile", "bytes": "8468" } ], "symlink_target": "" }
class TestExample : public TestCase{ public: TestExample(int id, std::string brief): TestCase(id, brief){}; protected: int32_t testint = 12345; TEST(test1); TEST(test2); TEST(test3); TEST_CASE_METHODS }; #endif //SE2_TEST_FRAMEWORK_TESTEXAMPLE_H
{ "content_hash": "69ada2fdd355bdb11bd4abe5af724643", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 66, "avg_line_length": 20.923076923076923, "alnum_prop": 0.6727941176470589, "repo_name": "ReneHerthel/ConveyorBelt", "id": "b965f69c49329c151e432d7624436e16049a7cde", "size": "502", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Tests/TestExample.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6145" }, { "name": "C++", "bytes": "390037" } ], "symlink_target": "" }
'use strict'; import Promise from 'bluebird'; import Joi from 'joi'; export default [ { path: '/v1/teams', method: 'GET', config: { handler: { async: Promise.coroutine(function* (request, reply) { let result = yield Promise.resolve([]); reply(result); }) } } }, { path: '/v1/teams', method: 'POST', config: { validate: { payload: Joi.object({ name: Joi.string().required().min(2).description('Team Name'), description: Joi.string().description('Team description'), members: Joi.array().unique().min(1).items(Joi.string().required()).description('Team Members'), isPublic: Joi.boolean().default(false).description('Is Public'), isActive: Joi.boolean().default(true).description('Is Active') }) }, handler: { async: Promise.coroutine(function* (request, reply) { let result = yield Promise.resolve({}); reply(result); }) } } }, { path: '/v1/teams/:id', method: 'GET', config: { validate: { params: { id: Joi.string() } }, handler: { async: Promise.coroutine(function* (request, reply) { let result = yield Promise.resolve({}); reply(result); }) } } }, { path: '/v1/teams/:id', method: 'PUT', config: { validate: { params: { id: Joi.string() }, payload: Joi.object({ name: Joi.string().required().min(2).description('Team Name'), description: Joi.string().description('Team description'), isPublic: Joi.boolean().default(false).description('Is Public'), isActive: Joi.boolean().default(true).description('Is Active') }) }, handler: { async: Promise.coroutine(function* (request, reply) { let result = yield Promise.resolve({}); reply(result); }) } } }, { path: '/v1/teams/:id', method: 'DELETE', config: { validate: { params: { id: Joi.string() } }, handler: { async: Promise.coroutine(function* (request, reply) { let result = yield Promise.resolve({}); reply(result); }) } } }, { path: '/v1/teams/:id/users/:userId', method: 'POST', config: { validate: { params: { id: Joi.string(), userId: Joi.string() }, payload: Joi.array().items(Joi.string()) }, handler: { async: Promise.coroutine(function* (request, reply) { let result = yield Promise.resolve({}); reply(result); }) } } }, { path: '/v1/teams/:id/users/:userId', method: 'DELETE', config: { validate: { params: { id: Joi.string(), userId: Joi.string() } }, handler: { async: Promise.coroutine(function* (request, reply) { let result = yield Promise.resolve({}); reply(result); }) } } } ]
{ "content_hash": "69accbb792f0b5ab68a4cdaf8038a09e", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 106, "avg_line_length": 23.67910447761194, "alnum_prop": 0.49196344153797666, "repo_name": "TylerGarlick/convergent-api", "id": "6e9ba9f4fbf7bbec0bc78cc65849d7ac7bfb89e2", "size": "3173", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "routes/teams.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "12617" } ], "symlink_target": "" }
(function (angular) { // Create all modules and define dependencies to make sure they exist // and are loaded in the correct order to satisfy dependency injection // before all nested files are concatenated by Gulp // Config angular.module('uiNotifier.config', []) .value('uiNotifier.config', { debug: true }); // Modules angular.module('uiNotifier.providers', []); angular.module('uiNotifier.controller', []); angular.module('uiNotifier.directives', []); angular.module('uiNotifier', [ 'uiNotifier.config', 'uiNotifier.directives', 'uiNotifier.providers' ]); })(angular);
{ "content_hash": "c4d6ac717a2410ae6225f99a4488303b", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 72, "avg_line_length": 29.666666666666668, "alnum_prop": 0.680577849117175, "repo_name": "mihnsen/ui-notifier", "id": "a0b1fdf6f4c448958966c7cf70761bb7a5b1348e", "size": "623", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ui-notifier/uiNotifier.module.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "2409" }, { "name": "HTML", "bytes": "8147" }, { "name": "JavaScript", "bytes": "18435" } ], "symlink_target": "" }
package net.projecteuler.barreiro.problem; import net.projecteuler.barreiro.algorithm.Primes; import java.util.HashMap; import java.util.Map; import static java.util.stream.LongStream.rangeClosed; import static net.projecteuler.barreiro.algorithm.util.LongUtils.pow; import static net.projecteuler.barreiro.algorithm.util.StreamUtils.product; /** * 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. * What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? * * @author barreiro */ public class Solver005 extends ProjectEulerSolver { public Solver005() { this( 20 ); } public Solver005(long n) { super( n ); } // --- // public long solve() { Map<Long, Long> factorMap = new HashMap<>(); // Populate the factorMap with the highest values of each of the factors rangeClosed( 1, N ).mapToObj( Primes::primeFactors ).forEach( fm -> fm.forEach( (k, v) -> factorMap.merge( k, v, Long::max ) ) ); // Calculate the product of the factors return product( factorMap.entrySet().stream().mapToLong( e -> pow( e.getKey(), e.getValue() ) ) ); } }
{ "content_hash": "aa9761dd072a405ff6b30b3e128a0e27", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 137, "avg_line_length": 29.357142857142858, "alnum_prop": 0.6828872668288727, "repo_name": "barreiro/euler", "id": "9dbbe989b97ec3ea3f380fcbda75cd4ca63af496", "size": "1288", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/net/projecteuler/barreiro/problem/Solver005.java", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "64871" }, { "name": "Java", "bytes": "169376" }, { "name": "Rust", "bytes": "286564" } ], "symlink_target": "" }
package org.lxp.crawler; import com.github.tomakehurst.wiremock.junit.WireMockRule; import org.apache.http.HttpStatus; import org.apache.http.conn.ConnectionPoolTimeoutException; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.util.StopWatch; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.Collectors; import java.util.stream.IntStream; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static org.assertj.core.api.Assertions.assertThat; public class HttpClientHelperTest { @Rule public ExpectedException expectedException = ExpectedException.none(); private AbstractHttpClientHelper helper; private final String crawlerUrl = "http://127.0.0.1:8080/crawler-test"; @Rule public WireMockRule forecastIoService = new WireMockRule(); @Before public void setUp() { forecastIoService.start(); } @After public void tearDown() { forecastIoService.stop(); } @Test public void testBatchGet() throws IOException { forecastIoService.stubFor(get(urlEqualTo("/crawler-test")).willReturn(aResponse().withFixedDelay(10).withStatus(HttpStatus.SC_OK))); // given List<String> urls = IntStream.range(0, 100) .mapToObj(index -> crawlerUrl) .collect(Collectors.toList()); // execute StopWatch stopWatch = new StopWatch(); helper = new CloseableHttpAsyncClientHelper(); stopWatch.start(); List<Integer> statusCodesAsyncBatch = helper.batchGet(urls); stopWatch.stop(); long costTimeAsyncBatch = stopWatch.getLastTaskTimeMillis(); helper = new CloseableHttpClientHelper(); stopWatch.start(); List<Integer> statusCodesBatch = helper.batchGet(urls); stopWatch.stop(); long costTimeBatch = stopWatch.getLastTaskTimeMillis(); // verify assertThat(statusCodesBatch).containsExactlyElementsOf(statusCodesAsyncBatch); assertThat(costTimeBatch).isGreaterThan(costTimeAsyncBatch); } @Test public void shouldThrowExceptionWhenAsyncSocketTimeout() throws Exception { forecastIoService.stubFor(get(urlEqualTo("/crawler-test")).willReturn(aResponse().withFixedDelay(61000).withStatus(HttpStatus.SC_OK))); expectedException.expect(ExecutionException.class); helper = new CloseableHttpAsyncClientHelper(); helper.get(crawlerUrl); } @Test public void shouldThrowExceptionWhenSocketTimeout() throws Exception { forecastIoService.stubFor(get(urlEqualTo("/crawler-test")).willReturn(aResponse().withFixedDelay(61000).withStatus(HttpStatus.SC_OK))); expectedException.expect(SocketTimeoutException.class); helper = new CloseableHttpClientHelper(); helper.get(crawlerUrl); } @Test public void shouldThrowExceptionWhenConnectTimeout() { forecastIoService.stubFor(get(urlEqualTo("/crawler-test")).willReturn(aResponse().withFixedDelay(41000).withStatus(HttpStatus.SC_OK))); expectedException.expect(RuntimeException.class); expectedException.expectMessage("ConnectionPoolTimeoutException"); helper = new CloseableHttpClientHelper(); final int size = helper.maxTotalConnection; ExecutorService executorService = Executors.newFixedThreadPool(size * 10); IntStream.range(0, size * 10).forEach(index -> CompletableFuture.runAsync(this::execute, executorService)); execute(); } private void execute() { try { helper.get(crawlerUrl); } catch (Exception e) { if (e instanceof ConnectionPoolTimeoutException) { throw new RuntimeException("ConnectionPoolTimeoutException"); } else { e.printStackTrace(); } } } }
{ "content_hash": "29a6956afa29e71e95ef7654c5f40a8c", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 143, "avg_line_length": 38.67857142857143, "alnum_prop": 0.7156048014773777, "repo_name": "hivsuper/study", "id": "fdb27632db629e51019a0830ef8422f01c812b51", "size": "4332", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web-crawler/src/test/java/org/lxp/crawler/HttpClientHelperTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "101612" }, { "name": "HTML", "bytes": "5852" }, { "name": "Java", "bytes": "2576820" }, { "name": "TSQL", "bytes": "519" } ], "symlink_target": "" }
package duckdns import ( "errors" "fmt" "net/http" "time" "github.com/go-acme/lego/v3/challenge/dns01" "github.com/go-acme/lego/v3/platform/config/env" ) // Config is used to configure the creation of the DNSProvider type Config struct { Token string PropagationTimeout time.Duration PollingInterval time.Duration SequenceInterval time.Duration HTTPClient *http.Client } // NewDefaultConfig returns a default configuration for the DNSProvider func NewDefaultConfig() *Config { return &Config{ PropagationTimeout: env.GetOrDefaultSecond("DUCKDNS_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), PollingInterval: env.GetOrDefaultSecond("DUCKDNS_POLLING_INTERVAL", dns01.DefaultPollingInterval), SequenceInterval: env.GetOrDefaultSecond("DUCKDNS_SEQUENCE_INTERVAL", dns01.DefaultPropagationTimeout), HTTPClient: &http.Client{ Timeout: env.GetOrDefaultSecond("DUCKDNS_HTTP_TIMEOUT", 30*time.Second), }, } } // DNSProvider adds and removes the record for the DNS challenge type DNSProvider struct { config *Config } // NewDNSProvider returns a new DNS provider using // environment variable DUCKDNS_TOKEN for adding and removing the DNS record. func NewDNSProvider() (*DNSProvider, error) { values, err := env.Get("DUCKDNS_TOKEN") if err != nil { return nil, fmt.Errorf("duckdns: %v", err) } config := NewDefaultConfig() config.Token = values["DUCKDNS_TOKEN"] return NewDNSProviderConfig(config) } // NewDNSProviderConfig return a DNSProvider instance configured for DuckDNS. func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { if config == nil { return nil, errors.New("duckdns: the configuration of the DNS provider is nil") } if config.Token == "" { return nil, errors.New("duckdns: credentials missing") } return &DNSProvider{config: config}, nil } // Present creates a TXT record to fulfill the dns-01 challenge. func (d *DNSProvider) Present(domain, token, keyAuth string) error { _, txtRecord := dns01.GetRecord(domain, keyAuth) return d.updateTxtRecord(domain, d.config.Token, txtRecord, false) } // CleanUp clears DuckDNS TXT record func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { return d.updateTxtRecord(domain, d.config.Token, "", true) } // Timeout returns the timeout and interval to use when checking for DNS propagation. // Adjusting here to cope with spikes in propagation times. func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { return d.config.PropagationTimeout, d.config.PollingInterval } // Sequential All DNS challenges for this provider will be resolved sequentially. // Returns the interval between each iteration. func (d *DNSProvider) Sequential() time.Duration { return d.config.SequenceInterval }
{ "content_hash": "254e15687538fef1889ceb16c9698d4a", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 109, "avg_line_length": 31.908045977011493, "alnum_prop": 0.7557636887608069, "repo_name": "xenolf/lego", "id": "aec3659117b66f349fae3f44cf307664100d95b3", "size": "2947", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "providers/dns/duckdns/duckdns.go", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "385" }, { "name": "Go", "bytes": "1021264" }, { "name": "Makefile", "bytes": "1324" }, { "name": "Roff", "bytes": "131" }, { "name": "Shell", "bytes": "541" } ], "symlink_target": "" }
package io.spine.server.command.model.given.commander; import com.google.common.collect.ImmutableList; import io.spine.core.External; import io.spine.model.contexts.projects.command.SigAddTaskToProject; import io.spine.model.contexts.projects.command.SigAssignTask; import io.spine.model.contexts.projects.command.SigCreateProject; import io.spine.model.contexts.projects.command.SigCreateTask; import io.spine.model.contexts.projects.command.SigPauseTask; import io.spine.model.contexts.projects.command.SigRemoveTaskFromProject; import io.spine.model.contexts.projects.command.SigSetProjectOwner; import io.spine.model.contexts.projects.command.SigStartTask; import io.spine.model.contexts.projects.command.SigStopTask; import io.spine.model.contexts.projects.event.SigProjectCreated; import io.spine.model.contexts.projects.event.SigProjectStopped; import io.spine.model.contexts.projects.event.SigTaskDeleted; import io.spine.model.contexts.projects.event.SigTaskMoved; import io.spine.model.contexts.projects.rejection.SigCannotCreateProject; import io.spine.server.command.AbstractCommander; import io.spine.server.command.Command; import io.spine.server.tuple.EitherOf2; import io.spine.server.tuple.Pair; import java.util.List; import java.util.Optional; import static io.spine.server.command.model.given.commander.TestCommandMessage.addTask; import static io.spine.server.command.model.given.commander.TestCommandMessage.pauseTask; import static io.spine.server.command.model.given.commander.TestCommandMessage.startTask; /** * A standalone commander which declares valid {@link Command} substitution methods. */ public final class SampleCommander extends AbstractCommander { @Command Pair<SigAddTaskToProject, Optional<SigStartTask>> pairWithOptionalResult(SigCreateTask command) { return Pair.withNullable(addTask(), null); } @Command @SuppressWarnings("DoNotCallSuggester") // Always throws for the purpose of the tests. SigSetProjectOwner declaredRejection(SigCreateProject command) throws SigCannotCreateProject { throw SigCannotCreateProject.newBuilder() .build(); } @Command SigPauseTask transform(SigRemoveTaskFromProject cmd) { return pauseTask(); } @Command List<SigStartTask> toList(SigAssignTask command) { return ImmutableList.of(startTask()); } @Command SigSetProjectOwner byEvent(SigProjectCreated event) { return SigSetProjectOwner.newBuilder().build(); } @Command EitherOf2<SigStopTask, SigAssignTask> byEvent(SigProjectStopped event) { return EitherOf2.withA(SigStopTask.getDefaultInstance()); } @Command SigRemoveTaskFromProject byExternalEvent(@External SigTaskDeleted event) { return SigRemoveTaskFromProject.newBuilder().build(); } @Command SigRemoveTaskFromProject byExternalEvent(@External SigTaskMoved event) { return SigRemoveTaskFromProject.newBuilder().build(); } }
{ "content_hash": "4a23b221c1eec0f723f6209993580c10", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 98, "avg_line_length": 37.7875, "alnum_prop": 0.7790274561693682, "repo_name": "SpineEventEngine/core-java", "id": "08c87e3f1a005bd43c778410f64f807472435227", "size": "4264", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/src/test/java/io/spine/server/command/model/given/commander/SampleCommander.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1739" }, { "name": "Java", "bytes": "6585842" }, { "name": "Kotlin", "bytes": "676484" }, { "name": "Shell", "bytes": "40419" } ], "symlink_target": "" }
OraQB ===== Oracle SQL query builder for Node.JS. [![Build Status](https://travis-ci.org/thaumant/oraqb.png?branch=master)](https://travis-ci.org/thaumant/oraqb)
{ "content_hash": "f0e6882675a1c5cbf71de4bc02ada41d", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 111, "avg_line_length": 27.166666666666668, "alnum_prop": 0.7300613496932515, "repo_name": "thaumant/node-oraqb", "id": "dce0dc460d3cbda9262fad5cf7203dafc6f67002", "size": "163", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "41447" } ], "symlink_target": "" }
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE CPP #-} {-# OPTIONS_HADDOCK hide #-} module Text.Markdown.Block ( Block (..) , ListType (..) , toBlocks , toBlockLines ) where import Prelude import Control.Monad (msum) #if MIN_VERSION_conduit(1, 0, 0) import Data.Conduit #else import Data.Conduit hiding ((=$=)) import Data.Conduit.Internal (pipeL) #endif import qualified Data.Conduit.Text as CT import qualified Data.Conduit.List as CL import Data.Text (Text) import qualified Data.Text as T import Data.Functor.Identity (runIdentity) import Data.Char (isDigit) import Text.Markdown.Types import qualified Data.Set as Set import qualified Data.Map as Map #if !MIN_VERSION_conduit(1, 0, 0) (=$=) :: Monad m => Pipe a a b x m y -> Pipe b b c y m z -> Pipe a a c x m z (=$=) = pipeL #endif toBlockLines :: Block Text -> Block [Text] toBlockLines = fmap $ map T.stripEnd . concatMap (T.splitOn " \r\n") . T.splitOn " \n" toBlocks :: Monad m => MarkdownSettings -> Conduit Text m (Block Text) toBlocks ms = mapOutput fixWS CT.lines =$= toBlocksLines ms where fixWS = T.pack . go 0 . T.unpack go _ [] = [] go i ('\r':cs) = go i cs go i ('\t':cs) = (replicate j ' ') ++ go (i + j) cs where j = 4 - (i `mod` 4) go i (c:cs) = c : go (i + 1) cs toBlocksLines :: Monad m => MarkdownSettings -> Conduit Text m (Block Text) toBlocksLines ms = awaitForever (start ms) =$= tightenLists tightenLists :: Monad m => Conduit (Either Blank (Block Text)) m (Block Text) tightenLists = go Nothing where go mTightList = await >>= maybe (return ()) go' where go' (Left Blank) = go mTightList go' (Right (BlockList ltNew contents)) = case mTightList of Just (ltOld, isTight) | ltOld == ltNew -> do yield $ BlockList ltNew $ (if isTight then tighten else untighten) contents go mTightList _ -> do isTight <- checkTight ltNew False yield $ BlockList ltNew $ (if isTight then tighten else untighten) contents go $ Just (ltNew, isTight) go' (Right b) = yield b >> go Nothing tighten (Right [BlockPara t]) = Left t tighten (Right []) = Left T.empty tighten x = x untighten (Left t) = Right [BlockPara t] untighten x = x checkTight lt sawBlank = do await >>= maybe (return $ not sawBlank) go' where go' (Left Blank) = checkTight lt True go' b@(Right (BlockList ltNext _)) | ltNext == lt = do leftover b return $ not sawBlank go' b = leftover b >> return False data Blank = Blank data LineType = LineList ListType Text | LineCode Text | LineFenced Text FencedHandler -- ^ terminator, language | LineBlockQuote Text | LineHeading Int Text | LineBlank | LineText Text | LineRule | LineHtml Text | LineReference Text Text -- ^ name, destination lineType :: MarkdownSettings -> Text -> LineType lineType ms t | T.null $ T.strip t = LineBlank | Just (term, fh) <- getFenced (Map.toList $ msFencedHandlers ms) t = LineFenced term fh | Just t' <- T.stripPrefix "> " t = LineBlockQuote t' | Just (level, t') <- stripHeading t = LineHeading level t' | Just t' <- T.stripPrefix " " t = LineCode t' | isRule t = LineRule | isHtmlStart t = LineHtml t | Just (ltype, t') <- listStart t = LineList ltype t' | Just (name, dest) <- getReference t = LineReference name dest | otherwise = LineText t where getFenced [] _ = Nothing getFenced ((x, fh):xs) t' | Just rest <- T.stripPrefix x t' = Just (x, fh $ T.strip rest) | otherwise = getFenced xs t' isRule :: Text -> Bool isRule = go . T.strip where go "* * *" = True go "***" = True go "*****" = True go "- - -" = True go "---" = True go "___" = True go "_ _ _" = True go t' = T.length (T.takeWhile (== '-') t') >= 5 stripHeading :: Text -> Maybe (Int, Text) stripHeading t' | T.null x = Nothing | otherwise = Just (T.length x, T.strip $ T.dropWhileEnd (== '#') y) where (x, y) = T.span (== '#') t' getReference :: Text -> Maybe (Text, Text) getReference a = do b <- T.stripPrefix "[" $ T.dropWhile (== ' ') a let (name, c) = T.break (== ']') b d <- T.stripPrefix "]:" c Just (name, T.strip d) start :: Monad m => MarkdownSettings -> Text -> Conduit Text m (Either Blank (Block Text)) start ms t = go $ lineType ms t where go LineBlank = yield $ Left Blank go (LineFenced term fh) = do (finished, ls) <- takeTillConsume (== term) case finished of Just _ -> do let block = case fh of FHRaw fh' -> fh' $ T.intercalate "\n" ls FHParsed fh' -> fh' $ runIdentity $ mapM_ yield ls $$ toBlocksLines ms =$ CL.consume mapM_ (yield . Right) block Nothing -> mapM_ leftover (reverse $ T.cons ' ' t : ls) go (LineBlockQuote t') = do ls <- takeQuotes =$= CL.consume let blocks = runIdentity $ mapM_ yield (t' : ls) $$ toBlocksLines ms =$ CL.consume yield $ Right $ BlockQuote blocks go (LineHeading level t') = yield $ Right $ BlockHeading level t' go (LineCode t') = do ls <- getIndented 4 =$= CL.consume yield $ Right $ BlockCode Nothing $ T.intercalate "\n" $ t' : ls go LineRule = yield $ Right BlockRule go (LineHtml t') = do if t' `Set.member` msStandaloneHtml ms then yield $ Right $ BlockHtml t' else do ls <- takeTill (T.null . T.strip) =$= CL.consume yield $ Right $ BlockHtml $ T.intercalate "\n" $ t' : ls go (LineList ltype t') = do t2 <- CL.peek case fmap (lineType ms) t2 of -- If the next line is a non-indented text line, then we have a -- lazy list. Just (LineText t2') | T.null (T.takeWhile (== ' ') t2') -> do CL.drop 1 -- Get all of the non-indented lines. let loop front = do x <- await case x of Nothing -> return $ front [] Just y -> case lineType ms y of LineText z -> loop (front . (z:)) _ -> leftover y >> return (front []) ls <- loop (\rest -> T.dropWhile (== ' ') t' : t2' : rest) yield $ Right $ BlockList ltype $ Right [BlockPara $ T.intercalate "\n" ls] -- If the next line is an indented list, then we have a sublist. I -- disagree with this interpretation of Markdown, but it's the way -- that Github implements things, so we will too. _ | Just t2' <- t2 , Just t2'' <- T.stripPrefix " " t2' , LineList _ltype' _t2''' <- lineType ms t2'' -> do ls <- getIndented 4 =$= CL.consume let blocks = runIdentity $ mapM_ yield ls $$ toBlocksLines ms =$ CL.consume let addPlainText | T.null $ T.strip t' = id | otherwise = (BlockPlainText (T.strip t'):) yield $ Right $ BlockList ltype $ Right $ addPlainText blocks _ -> do let t'' = T.dropWhile (== ' ') t' let leader = T.length t - T.length t'' ls <- getIndented leader =$= CL.consume let blocks = runIdentity $ mapM_ yield (t'' : ls) $$ toBlocksLines ms =$ CL.consume yield $ Right $ BlockList ltype $ Right blocks go (LineReference x y) = yield $ Right $ BlockReference x y go (LineText t') = do -- Check for underline headings let getUnderline :: Text -> Maybe Int getUnderline s | T.length s < 2 = Nothing | T.all (== '=') s = Just 1 | T.all (== '-') s = Just 2 | otherwise = Nothing t2 <- CL.peek case t2 >>= getUnderline of Just level -> do CL.drop 1 yield $ Right $ BlockHeading level t' Nothing -> do let listStartIndent x = case listStart x of Just (_, y) -> T.take 2 y == " " Nothing -> False isNonPara LineBlank = True isNonPara LineFenced{} = True isNonPara LineBlockQuote{} = not $ msBlankBeforeBlockquote ms isNonPara LineHtml{} = True -- See example 95 in Common Markdown spec isNonPara _ = False (mfinal, ls) <- takeTillConsume (\x -> isNonPara (lineType ms x) || listStartIndent x) maybe (return ()) leftover mfinal yield $ Right $ BlockPara $ T.intercalate "\n" $ t' : ls isHtmlStart :: T.Text -> Bool -- Allow for up to three spaces before the opening tag. isHtmlStart t | " " `T.isPrefixOf` t = False isHtmlStart t = case T.stripPrefix "<" $ T.dropWhile (== ' ') t of Nothing -> False Just t' -> let (name, rest) | Just _ <- T.stripPrefix "!--" t' = ("--", t') | otherwise = T.break (\c -> c == ' ' || c == '>') t' in (T.all isValidTagName name && not (T.null name) && (not ("/" `T.isPrefixOf` rest) || ("/>" `T.isPrefixOf` rest))) || isPI t' || isCommentCData t' where isValidTagName :: Char -> Bool isValidTagName c = ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || ('0' <= c && c <= '9') || (c == '-') || (c == '_') || (c == '/') || (c == '!') isPI = ("?" `T.isPrefixOf`) isCommentCData = ("!" `T.isPrefixOf`) takeTill :: Monad m => (i -> Bool) -> Conduit i m i takeTill f = loop where loop = await >>= maybe (return ()) (\x -> if f x then return () else yield x >> loop) --takeTillConsume :: Monad m => (i -> Bool) -> Consumer i m (Maybe i, [i]) takeTillConsume f = loop id where loop front = await >>= maybe (return (Nothing, front [])) (\x -> if f x then return (Just x, front []) else loop (front . (x:)) ) listStart :: Text -> Maybe (ListType, Text) listStart t0 | Just t' <- stripUnorderedListSeparator t = Just (Unordered, t') | Just t' <- stripNumber t, Just t'' <- stripOrderedListSeparator t' = Just (Ordered, t'') | otherwise = Nothing where t = T.stripStart t0 stripNumber :: Text -> Maybe Text stripNumber x | T.null y = Nothing | otherwise = Just z where (y, z) = T.span isDigit x stripUnorderedListSeparator :: Text -> Maybe Text stripUnorderedListSeparator = stripPrefixChoice ["* ", "*\t", "+ ", "+\t", "- ", "-\t"] stripOrderedListSeparator :: Text -> Maybe Text stripOrderedListSeparator = stripPrefixChoice [". ", ".\t", ") ", ")\t"] -- | Attempt to strip each of the prefixes in @xs@ from the start of @x@. As -- soon as one matches, return the remainder of @x@. Prefixes are tried in -- order. If none match, return @Nothing@. stripPrefixChoice :: [Text] -> Text -> Maybe Text stripPrefixChoice xs x = msum $ map (flip T.stripPrefix x) xs getIndented :: Monad m => Int -> Conduit Text m Text getIndented leader = go [] where go blanks = await >>= maybe (mapM_ leftover blanks) (go' blanks) go' blanks t | T.null $ T.strip t = go (T.drop leader t : blanks) | T.length x == leader && T.null (T.strip x) = do mapM_ yield $ reverse blanks yield y go [] | otherwise = mapM_ leftover (t:blanks) where (x, y) = T.splitAt leader t takeQuotes :: Monad m => Conduit Text m Text takeQuotes = await >>= maybe (return ()) go where go "" = return () go ">" = yield "" >> takeQuotes go t | Just t' <- T.stripPrefix "> " t = yield t' >> takeQuotes | otherwise = yield t >> takeQuotes
{ "content_hash": "c01157c4bffd59ca72af47544cd38e1c", "timestamp": "", "source": "github", "line_count": 346, "max_line_length": 112, "avg_line_length": 36.54913294797688, "alnum_prop": 0.5212715483156729, "repo_name": "thefalconfeat/markdown", "id": "a99a0199feb6119048034568c94887f5efdc55d0", "size": "12646", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Text/Markdown/Block.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "53890" }, { "name": "Haskell", "bytes": "54579" } ], "symlink_target": "" }
using Android.App; using Android.Content; using Android.Gms.Auth; using Android.Gms.Auth.Api; using Android.Gms.Auth.Api.SignIn; using Android.Gms.Common; using Android.Gms.Common.Apis; using System; using System.Reactive; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading.Tasks; using Toggl.Core.Exceptions; using Toggl.Core.Helper; using Toggl.Shared.Extensions; using Object = Java.Lang.Object; namespace Toggl.Droid.Activities { public abstract partial class ReactiveActivity<TViewModel> { private const int googleSignInResult = 123; private readonly object lockable = new object(); private readonly string scope = $"oauth2:{Scopes.Profile}"; private bool isLoggingIn; private GoogleApiClient googleApiClient; private Subject<ThirdPartyLoginInfo> loginSubject = new Subject<ThirdPartyLoginInfo>(); public IObservable<ThirdPartyLoginInfo> GetLoginInfo(ThirdPartyLoginProvider provider) { if (provider == ThirdPartyLoginProvider.Google) return getGoogleLoginInfo(); throw new InvalidOperationException("You shouldn't be doing this from Android."); } private IObservable<ThirdPartyLoginInfo> getGoogleLoginInfo() { ensureApiClientExists(); return logOutIfNeeded().SelectMany(getGoogleToken); IObservable<Unit> logOutIfNeeded() { if (!googleApiClient.IsConnected) return Observable.Return(Unit.Default); var logoutSubject = new Subject<Unit>(); var logoutCallback = new LogOutCallback(() => logoutSubject.CompleteWith(Unit.Default)); Auth.GoogleSignInApi .SignOut(googleApiClient) .SetResultCallback(logoutCallback); return logoutSubject.AsObservable(); } IObservable<ThirdPartyLoginInfo> getGoogleToken(Unit _) { lock (lockable) { if (isLoggingIn) return loginSubject.AsObservable(); isLoggingIn = true; loginSubject = new Subject<ThirdPartyLoginInfo>(); if (googleApiClient.IsConnected) { login(); return loginSubject.AsObservable(); } googleApiClient.Connect(); return loginSubject.AsObservable(); } } } private void onGoogleSignInResult(Intent data) { lock (lockable) { var signInData = Auth.GoogleSignInApi.GetSignInResultFromIntent(data); if (!signInData.IsSuccess) { loginSubject.OnError(new ThirdPartyLoginException(ThirdPartyLoginProvider.Google, signInData.Status.IsCanceled)); isLoggingIn = false; return; } Task.Run(() => { try { var token = GoogleAuthUtil.GetToken(Application.Context, signInData.SignInAccount.Account, scope); var loginInfo = new ThirdPartyLoginInfo(token); loginSubject.OnNext(loginInfo); loginSubject.OnCompleted(); } catch (Exception e) { loginSubject.OnError(e); } finally { isLoggingIn = false; } }); } } private void login() { if (!isLoggingIn) return; if (!googleApiClient.IsConnected) { throw new ThirdPartyLoginException(ThirdPartyLoginProvider.Google, false); } var intent = Auth.GoogleSignInApi.GetSignInIntent(googleApiClient); StartActivityForResult(intent, googleSignInResult); } private void onError(ConnectionResult result) { lock (lockable) { loginSubject.OnError(new ThirdPartyLoginException(ThirdPartyLoginProvider.Google, false)); isLoggingIn = false; } } private void ensureApiClientExists() { if (googleApiClient != null) return; var signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultSignIn) .RequestIdToken("{TOGGL_DROID_GOOGLE_SERVICES_CLIENT_ID}") .RequestEmail() .Build(); googleApiClient = new GoogleApiClient.Builder(Application.Context) .AddConnectionCallbacks(login) .AddOnConnectionFailedListener(onError) .AddApi(Auth.GOOGLE_SIGN_IN_API, signInOptions) .Build(); } private class LogOutCallback : Object, IResultCallback { private Action callback; public LogOutCallback(Action callback) { this.callback = callback; } public void OnResult(Object result) { callback(); } } } }
{ "content_hash": "a610748515ae2df1c24638a265ad566a", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 133, "avg_line_length": 32.76646706586826, "alnum_prop": 0.5444078947368421, "repo_name": "toggl/mobileapp", "id": "74e615412ee379a53c7e351547c9c09e0596839d", "size": "5472", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "Toggl.Droid/Activities/ReactiveActivity.ThirdPartyTokenProvider.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "5733490" }, { "name": "Makefile", "bytes": "847" }, { "name": "Objective-C", "bytes": "41986" }, { "name": "Shell", "bytes": "3407" } ], "symlink_target": "" }
package com.bh.wechat.response; import java.io.Serializable; public class Help implements Serializable { private static final long serialVersionUID = -8456386106123940446L; private int helpId; private String title; public int getHelpId() { return helpId; } public void setHelpId(int helpId) { this.helpId = helpId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
{ "content_hash": "e792b4c329dc935b19b4cb40bdfdbc26", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 71, "avg_line_length": 18.071428571428573, "alnum_prop": 0.6462450592885376, "repo_name": "liufeiit/wechat-mall", "id": "e8cf1693b74f8c3d8e26712bda7612face194baa", "size": "506", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/bh/wechat/response/Help.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "83830" }, { "name": "Java", "bytes": "593219" }, { "name": "JavaScript", "bytes": "25482" } ], "symlink_target": "" }
const std::string CLIENT_NAME("Satoshi"); // Client version number #define CLIENT_VERSION_SUFFIX "-beta" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "7f18925" # define GIT_COMMIT_DATE "Sat, 19 Apr 2014 16:22:19 +0100" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE);
{ "content_hash": "b70058acffa8a46c7485685221ad5bcf", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 155, "avg_line_length": 39.42857142857143, "alnum_prop": 0.7069746376811594, "repo_name": "nusacoin/nusacoin", "id": "4177fa94619dc3adf33e4a092a1391a40135a775", "size": "2628", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/version.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "765626" }, { "name": "C++", "bytes": "2332599" }, { "name": "CSS", "bytes": "1127" }, { "name": "IDL", "bytes": "14275" }, { "name": "Objective-C++", "bytes": "5864" }, { "name": "Python", "bytes": "3776" }, { "name": "Shell", "bytes": "1144" }, { "name": "TypeScript", "bytes": "96580" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "3740b2cc28662b37789e72387c0c7b90", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "26e45adc3c307577a0316f4d5c52d821290b49ef", "size": "179", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Achillea schugnanica/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/com_facebook_button_blue_pressed" android:state_focused="true" android:state_pressed="true" /> <item android:drawable="@drawable/com_facebook_button_blue_pressed" android:state_focused="false" android:state_pressed="true" /> <item android:drawable="@drawable/com_facebook_button_blue_focused" android:state_focused="true" /> <item android:drawable="@drawable/com_facebook_button_blue_normal" android:state_focused="false" android:state_pressed="false" /> </selector> <!-- From: file:/C:/Android/proyectos/AndroidStudio/Ciudades/facebook/res/drawable/com_facebook_button_blue.xml -->
{ "content_hash": "077264aa79087fecabf5d9f83e1a1848", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 115, "avg_line_length": 33, "alnum_prop": 0.6763636363636364, "repo_name": "Insside/android-iCiudades", "id": "f2ac1c21c9e01b5d97e2b2707ffa02c4c0bfe335", "size": "825", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "facebook/build/intermediates/bundles/debug/res/drawable/com_facebook_button_blue.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11139" }, { "name": "HTML", "bytes": "565916" }, { "name": "Java", "bytes": "324198" } ], "symlink_target": "" }